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
wangyeee/IBE-Secure-Message
jlib/ibejnilib/src/test/java/hamaster/gradesgin/test/TestIBENativeLibrary.java
// Path: jlib/ibejnilib/src/main/java/hamaster/gradesign/ibe/IBELibrary.java // public final static int decrypt(byte[] plainBufferOut, byte[] cipherIn, byte[] rIDIn, byte[] hIDIn, byte[] pairingIn) { // ensureArrayCapacity(plainBufferOut, PBC_G_SIZE); // return IBENative.decrypt_str(plainBufferOut, cipherIn, rIDIn, hIDIn, pairingIn); // } // // Path: jlib/ibejnilib/src/main/java/hamaster/gradesign/ibe/IBELibrary.java // public final static int encrypt(byte[] cipherBufferOut, byte[] plainIn, byte[] gIn, byte[] g1In, byte[] hIn, byte[] aliceIn, byte[] pairingIn) { // ensureArrayCapacity(cipherBufferOut, 3 * PBC_G_SIZE); // return IBENative.encrypt_str(cipherBufferOut, plainIn, gIn, g1In, hIn, aliceIn, pairingIn); // } // // Path: jlib/ibejnilib/src/main/java/hamaster/gradesign/ibe/IBELibrary.java // public final static int keygen(byte[] hIDOut, byte[] rIDOut, byte[] userIn, byte[] alphaIn, byte[] gIn, byte[] hIn, byte[] pairingIn) { // ensureArrayCapacity(rIDOut, PBC_ZR_SIZE); // ensureArrayCapacity(hIDOut, PBC_G_SIZE); // return IBENative.keygen_str(hIDOut, rIDOut, userIn, alphaIn, gIn, hIn, pairingIn, true); // } // // Path: jlib/ibejnilib/src/main/java/hamaster/gradesign/ibe/IBELibrary.java // public final static int setup(byte[] alphaOut, byte[] gOut, byte[] g1Out, byte[] hOut, byte[] pairingIn) { // ensureArrayCapacity(alphaOut, PBC_ZR_SIZE); // ensureArrayCapacity(gOut, PBC_G_SIZE); // ensureArrayCapacity(g1Out, PBC_G_SIZE); // ensureArrayCapacity(hOut, PBC_G_SIZE); // return IBENative.setup_str(alphaOut, gOut, g1Out, hOut, pairingIn); // }
import static hamaster.gradesign.ibe.IBELibrary.decrypt; import static hamaster.gradesign.ibe.IBELibrary.encrypt; import static hamaster.gradesign.ibe.IBELibrary.keygen; import static hamaster.gradesign.ibe.IBELibrary.setup; import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.Test;
package hamaster.gradesgin.test; public class TestIBENativeLibrary { String param = "type a q 8780710799663312522437781984754049815806883199414208211028653399266475630880222957078625179422662221423155858769582317459277713367317481324925129998224791 h 12016012264891146079388821366740534204802954401251311822919615131047207289359704531102844802183906537786776 r 730750818665451621361119245571504901405976559617 exp2 159 exp1 107 sign1 1 sign0 1 "; String data = "00023065cf3983fc810a12bf66231a826dd6374b171a5db24b8192e3c951dbdede06714f5c93e1fc013ece70a85b0df3ea365c6f333f6eefeeae408d60219c2800b48ef6ef08f6c7a20064f51f29babe3432586ff8126b3f90befddcdf1162624bb071419bd3afedf1123a12100fa4839736cfe73579fa761df472d3f64b7e44"; String user = "wangyeee@gmail.com"; @Test public void test() { byte[] pairing_str_in = param.getBytes(); byte[] h_out = new byte[128]; byte[] g1_out = new byte[128]; byte[] g_out = new byte[128]; byte[] alpha_out = new byte[20]; int i = setup(alpha_out, g_out, g1_out, h_out, pairing_str_in); byte[] hID_out = new byte[128]; byte[] rID_out = new byte[20]; i = keygen(hID_out, rID_out, user.getBytes(), alpha_out, g_out, h_out, pairing_str_in); byte[] cipher_buffer_out = new byte[128 * 3]; byte[] plain_in = unhex(data); byte[] alice_in = user.getBytes();
// Path: jlib/ibejnilib/src/main/java/hamaster/gradesign/ibe/IBELibrary.java // public final static int decrypt(byte[] plainBufferOut, byte[] cipherIn, byte[] rIDIn, byte[] hIDIn, byte[] pairingIn) { // ensureArrayCapacity(plainBufferOut, PBC_G_SIZE); // return IBENative.decrypt_str(plainBufferOut, cipherIn, rIDIn, hIDIn, pairingIn); // } // // Path: jlib/ibejnilib/src/main/java/hamaster/gradesign/ibe/IBELibrary.java // public final static int encrypt(byte[] cipherBufferOut, byte[] plainIn, byte[] gIn, byte[] g1In, byte[] hIn, byte[] aliceIn, byte[] pairingIn) { // ensureArrayCapacity(cipherBufferOut, 3 * PBC_G_SIZE); // return IBENative.encrypt_str(cipherBufferOut, plainIn, gIn, g1In, hIn, aliceIn, pairingIn); // } // // Path: jlib/ibejnilib/src/main/java/hamaster/gradesign/ibe/IBELibrary.java // public final static int keygen(byte[] hIDOut, byte[] rIDOut, byte[] userIn, byte[] alphaIn, byte[] gIn, byte[] hIn, byte[] pairingIn) { // ensureArrayCapacity(rIDOut, PBC_ZR_SIZE); // ensureArrayCapacity(hIDOut, PBC_G_SIZE); // return IBENative.keygen_str(hIDOut, rIDOut, userIn, alphaIn, gIn, hIn, pairingIn, true); // } // // Path: jlib/ibejnilib/src/main/java/hamaster/gradesign/ibe/IBELibrary.java // public final static int setup(byte[] alphaOut, byte[] gOut, byte[] g1Out, byte[] hOut, byte[] pairingIn) { // ensureArrayCapacity(alphaOut, PBC_ZR_SIZE); // ensureArrayCapacity(gOut, PBC_G_SIZE); // ensureArrayCapacity(g1Out, PBC_G_SIZE); // ensureArrayCapacity(hOut, PBC_G_SIZE); // return IBENative.setup_str(alphaOut, gOut, g1Out, hOut, pairingIn); // } // Path: jlib/ibejnilib/src/test/java/hamaster/gradesgin/test/TestIBENativeLibrary.java import static hamaster.gradesign.ibe.IBELibrary.decrypt; import static hamaster.gradesign.ibe.IBELibrary.encrypt; import static hamaster.gradesign.ibe.IBELibrary.keygen; import static hamaster.gradesign.ibe.IBELibrary.setup; import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.Test; package hamaster.gradesgin.test; public class TestIBENativeLibrary { String param = "type a q 8780710799663312522437781984754049815806883199414208211028653399266475630880222957078625179422662221423155858769582317459277713367317481324925129998224791 h 12016012264891146079388821366740534204802954401251311822919615131047207289359704531102844802183906537786776 r 730750818665451621361119245571504901405976559617 exp2 159 exp1 107 sign1 1 sign0 1 "; String data = "00023065cf3983fc810a12bf66231a826dd6374b171a5db24b8192e3c951dbdede06714f5c93e1fc013ece70a85b0df3ea365c6f333f6eefeeae408d60219c2800b48ef6ef08f6c7a20064f51f29babe3432586ff8126b3f90befddcdf1162624bb071419bd3afedf1123a12100fa4839736cfe73579fa761df472d3f64b7e44"; String user = "wangyeee@gmail.com"; @Test public void test() { byte[] pairing_str_in = param.getBytes(); byte[] h_out = new byte[128]; byte[] g1_out = new byte[128]; byte[] g_out = new byte[128]; byte[] alpha_out = new byte[20]; int i = setup(alpha_out, g_out, g1_out, h_out, pairing_str_in); byte[] hID_out = new byte[128]; byte[] rID_out = new byte[20]; i = keygen(hID_out, rID_out, user.getBytes(), alpha_out, g_out, h_out, pairing_str_in); byte[] cipher_buffer_out = new byte[128 * 3]; byte[] plain_in = unhex(data); byte[] alice_in = user.getBytes();
i = encrypt(cipher_buffer_out, plain_in, g_out, g1_out, h_out, alice_in, pairing_str_in);
wangyeee/IBE-Secure-Message
jlib/ibejnilib/src/test/java/hamaster/gradesgin/test/TestIBENativeLibrary.java
// Path: jlib/ibejnilib/src/main/java/hamaster/gradesign/ibe/IBELibrary.java // public final static int decrypt(byte[] plainBufferOut, byte[] cipherIn, byte[] rIDIn, byte[] hIDIn, byte[] pairingIn) { // ensureArrayCapacity(plainBufferOut, PBC_G_SIZE); // return IBENative.decrypt_str(plainBufferOut, cipherIn, rIDIn, hIDIn, pairingIn); // } // // Path: jlib/ibejnilib/src/main/java/hamaster/gradesign/ibe/IBELibrary.java // public final static int encrypt(byte[] cipherBufferOut, byte[] plainIn, byte[] gIn, byte[] g1In, byte[] hIn, byte[] aliceIn, byte[] pairingIn) { // ensureArrayCapacity(cipherBufferOut, 3 * PBC_G_SIZE); // return IBENative.encrypt_str(cipherBufferOut, plainIn, gIn, g1In, hIn, aliceIn, pairingIn); // } // // Path: jlib/ibejnilib/src/main/java/hamaster/gradesign/ibe/IBELibrary.java // public final static int keygen(byte[] hIDOut, byte[] rIDOut, byte[] userIn, byte[] alphaIn, byte[] gIn, byte[] hIn, byte[] pairingIn) { // ensureArrayCapacity(rIDOut, PBC_ZR_SIZE); // ensureArrayCapacity(hIDOut, PBC_G_SIZE); // return IBENative.keygen_str(hIDOut, rIDOut, userIn, alphaIn, gIn, hIn, pairingIn, true); // } // // Path: jlib/ibejnilib/src/main/java/hamaster/gradesign/ibe/IBELibrary.java // public final static int setup(byte[] alphaOut, byte[] gOut, byte[] g1Out, byte[] hOut, byte[] pairingIn) { // ensureArrayCapacity(alphaOut, PBC_ZR_SIZE); // ensureArrayCapacity(gOut, PBC_G_SIZE); // ensureArrayCapacity(g1Out, PBC_G_SIZE); // ensureArrayCapacity(hOut, PBC_G_SIZE); // return IBENative.setup_str(alphaOut, gOut, g1Out, hOut, pairingIn); // }
import static hamaster.gradesign.ibe.IBELibrary.decrypt; import static hamaster.gradesign.ibe.IBELibrary.encrypt; import static hamaster.gradesign.ibe.IBELibrary.keygen; import static hamaster.gradesign.ibe.IBELibrary.setup; import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.Test;
package hamaster.gradesgin.test; public class TestIBENativeLibrary { String param = "type a q 8780710799663312522437781984754049815806883199414208211028653399266475630880222957078625179422662221423155858769582317459277713367317481324925129998224791 h 12016012264891146079388821366740534204802954401251311822919615131047207289359704531102844802183906537786776 r 730750818665451621361119245571504901405976559617 exp2 159 exp1 107 sign1 1 sign0 1 "; String data = "00023065cf3983fc810a12bf66231a826dd6374b171a5db24b8192e3c951dbdede06714f5c93e1fc013ece70a85b0df3ea365c6f333f6eefeeae408d60219c2800b48ef6ef08f6c7a20064f51f29babe3432586ff8126b3f90befddcdf1162624bb071419bd3afedf1123a12100fa4839736cfe73579fa761df472d3f64b7e44"; String user = "wangyeee@gmail.com"; @Test public void test() { byte[] pairing_str_in = param.getBytes(); byte[] h_out = new byte[128]; byte[] g1_out = new byte[128]; byte[] g_out = new byte[128]; byte[] alpha_out = new byte[20]; int i = setup(alpha_out, g_out, g1_out, h_out, pairing_str_in); byte[] hID_out = new byte[128]; byte[] rID_out = new byte[20]; i = keygen(hID_out, rID_out, user.getBytes(), alpha_out, g_out, h_out, pairing_str_in); byte[] cipher_buffer_out = new byte[128 * 3]; byte[] plain_in = unhex(data); byte[] alice_in = user.getBytes(); i = encrypt(cipher_buffer_out, plain_in, g_out, g1_out, h_out, alice_in, pairing_str_in); byte[] plain_buffer_out = new byte[128];
// Path: jlib/ibejnilib/src/main/java/hamaster/gradesign/ibe/IBELibrary.java // public final static int decrypt(byte[] plainBufferOut, byte[] cipherIn, byte[] rIDIn, byte[] hIDIn, byte[] pairingIn) { // ensureArrayCapacity(plainBufferOut, PBC_G_SIZE); // return IBENative.decrypt_str(plainBufferOut, cipherIn, rIDIn, hIDIn, pairingIn); // } // // Path: jlib/ibejnilib/src/main/java/hamaster/gradesign/ibe/IBELibrary.java // public final static int encrypt(byte[] cipherBufferOut, byte[] plainIn, byte[] gIn, byte[] g1In, byte[] hIn, byte[] aliceIn, byte[] pairingIn) { // ensureArrayCapacity(cipherBufferOut, 3 * PBC_G_SIZE); // return IBENative.encrypt_str(cipherBufferOut, plainIn, gIn, g1In, hIn, aliceIn, pairingIn); // } // // Path: jlib/ibejnilib/src/main/java/hamaster/gradesign/ibe/IBELibrary.java // public final static int keygen(byte[] hIDOut, byte[] rIDOut, byte[] userIn, byte[] alphaIn, byte[] gIn, byte[] hIn, byte[] pairingIn) { // ensureArrayCapacity(rIDOut, PBC_ZR_SIZE); // ensureArrayCapacity(hIDOut, PBC_G_SIZE); // return IBENative.keygen_str(hIDOut, rIDOut, userIn, alphaIn, gIn, hIn, pairingIn, true); // } // // Path: jlib/ibejnilib/src/main/java/hamaster/gradesign/ibe/IBELibrary.java // public final static int setup(byte[] alphaOut, byte[] gOut, byte[] g1Out, byte[] hOut, byte[] pairingIn) { // ensureArrayCapacity(alphaOut, PBC_ZR_SIZE); // ensureArrayCapacity(gOut, PBC_G_SIZE); // ensureArrayCapacity(g1Out, PBC_G_SIZE); // ensureArrayCapacity(hOut, PBC_G_SIZE); // return IBENative.setup_str(alphaOut, gOut, g1Out, hOut, pairingIn); // } // Path: jlib/ibejnilib/src/test/java/hamaster/gradesgin/test/TestIBENativeLibrary.java import static hamaster.gradesign.ibe.IBELibrary.decrypt; import static hamaster.gradesign.ibe.IBELibrary.encrypt; import static hamaster.gradesign.ibe.IBELibrary.keygen; import static hamaster.gradesign.ibe.IBELibrary.setup; import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.List; import org.junit.jupiter.api.Test; package hamaster.gradesgin.test; public class TestIBENativeLibrary { String param = "type a q 8780710799663312522437781984754049815806883199414208211028653399266475630880222957078625179422662221423155858769582317459277713367317481324925129998224791 h 12016012264891146079388821366740534204802954401251311822919615131047207289359704531102844802183906537786776 r 730750818665451621361119245571504901405976559617 exp2 159 exp1 107 sign1 1 sign0 1 "; String data = "00023065cf3983fc810a12bf66231a826dd6374b171a5db24b8192e3c951dbdede06714f5c93e1fc013ece70a85b0df3ea365c6f333f6eefeeae408d60219c2800b48ef6ef08f6c7a20064f51f29babe3432586ff8126b3f90befddcdf1162624bb071419bd3afedf1123a12100fa4839736cfe73579fa761df472d3f64b7e44"; String user = "wangyeee@gmail.com"; @Test public void test() { byte[] pairing_str_in = param.getBytes(); byte[] h_out = new byte[128]; byte[] g1_out = new byte[128]; byte[] g_out = new byte[128]; byte[] alpha_out = new byte[20]; int i = setup(alpha_out, g_out, g1_out, h_out, pairing_str_in); byte[] hID_out = new byte[128]; byte[] rID_out = new byte[20]; i = keygen(hID_out, rID_out, user.getBytes(), alpha_out, g_out, h_out, pairing_str_in); byte[] cipher_buffer_out = new byte[128 * 3]; byte[] plain_in = unhex(data); byte[] alice_in = user.getBytes(); i = encrypt(cipher_buffer_out, plain_in, g_out, g1_out, h_out, alice_in, pairing_str_in); byte[] plain_buffer_out = new byte[128];
i = decrypt(plain_buffer_out, cipher_buffer_out, rID_out, hID_out, pairing_str_in);
wangyeee/IBE-Secure-Message
jlib/jibe/src/main/java/hamaster/gradesgin/ibe/IBEPlainText.java
// Path: jlib/jibe/src/main/java/hamaster/gradesgin/util/MemoryUtil.java // final public class MemoryUtil { // // /** // * 在新的线程中安全擦除内存块,这个方法在执行后会快速返回<br> // * 此方法与在新线程中执行immediateSecureBuffers方法等效 // * @param buffers 待擦除的内存块 // */ // public final static void fastSecureBuffers(byte[] ... buffers) { // new SecureBufferThread(buffers).start(); // } // // /** // * 立刻安全擦除内存块 // * @param buffers 待擦除的内存块 // */ // public final static void immediateSecureBuffers(byte[] ... buffers) { // BigInteger i = new BigInteger(Long.toHexString(System.nanoTime()), 16); // Random random = new SecureRandom(i.toByteArray()); // for (byte[] buffer : buffers) { // if (buffer != null) // random.nextBytes(buffer); // } // } // }
import hamaster.gradesgin.util.MemoryUtil; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Serializable; import java.util.Arrays;
int length = significantBytes.length; final int IBE_HALF = IBE_G_SIZE / 2 - 1; text.content = new byte[IBE_G_SIZE]; Arrays.fill(text.content, (byte) 0); if (length > IBE_HALF) { System.arraycopy(significantBytes, 0, text.content, IBE_G_SIZE - length - 1, length - IBE_HALF); System.arraycopy(significantBytes, length - IBE_HALF, text.content, IBE_G_SIZE - IBE_HALF, IBE_HALF); } else { System.arraycopy(significantBytes, 0, text.content, IBE_G_SIZE - length, length); } text.setLength(length); return text; } /** * 序列化字段:<br> * 明文内容 128字节<br> * 明文有效长度 1字节<br> * Serialize this object, the first 128 bytes are padded plain text and the last byte is the length of byte used(1 to 126) * @see hamaster.gradesgin.ibe.IBEConstraints#writeExternal(java.io.OutputStream) */ @Override public void writeExternal(OutputStream out) throws IOException { byte[] contentBuffer = new byte[IBE_G_SIZE]; Arrays.fill(contentBuffer, (byte) 0); if (content != null) System.arraycopy(content, 0, contentBuffer, 0, IBE_G_SIZE > content.length ? content.length : IBE_G_SIZE); out.write(contentBuffer); out.write((byte) getLength()); out.flush();
// Path: jlib/jibe/src/main/java/hamaster/gradesgin/util/MemoryUtil.java // final public class MemoryUtil { // // /** // * 在新的线程中安全擦除内存块,这个方法在执行后会快速返回<br> // * 此方法与在新线程中执行immediateSecureBuffers方法等效 // * @param buffers 待擦除的内存块 // */ // public final static void fastSecureBuffers(byte[] ... buffers) { // new SecureBufferThread(buffers).start(); // } // // /** // * 立刻安全擦除内存块 // * @param buffers 待擦除的内存块 // */ // public final static void immediateSecureBuffers(byte[] ... buffers) { // BigInteger i = new BigInteger(Long.toHexString(System.nanoTime()), 16); // Random random = new SecureRandom(i.toByteArray()); // for (byte[] buffer : buffers) { // if (buffer != null) // random.nextBytes(buffer); // } // } // } // Path: jlib/jibe/src/main/java/hamaster/gradesgin/ibe/IBEPlainText.java import hamaster.gradesgin.util.MemoryUtil; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Serializable; import java.util.Arrays; int length = significantBytes.length; final int IBE_HALF = IBE_G_SIZE / 2 - 1; text.content = new byte[IBE_G_SIZE]; Arrays.fill(text.content, (byte) 0); if (length > IBE_HALF) { System.arraycopy(significantBytes, 0, text.content, IBE_G_SIZE - length - 1, length - IBE_HALF); System.arraycopy(significantBytes, length - IBE_HALF, text.content, IBE_G_SIZE - IBE_HALF, IBE_HALF); } else { System.arraycopy(significantBytes, 0, text.content, IBE_G_SIZE - length, length); } text.setLength(length); return text; } /** * 序列化字段:<br> * 明文内容 128字节<br> * 明文有效长度 1字节<br> * Serialize this object, the first 128 bytes are padded plain text and the last byte is the length of byte used(1 to 126) * @see hamaster.gradesgin.ibe.IBEConstraints#writeExternal(java.io.OutputStream) */ @Override public void writeExternal(OutputStream out) throws IOException { byte[] contentBuffer = new byte[IBE_G_SIZE]; Arrays.fill(contentBuffer, (byte) 0); if (content != null) System.arraycopy(content, 0, contentBuffer, 0, IBE_G_SIZE > content.length ? content.length : IBE_G_SIZE); out.write(contentBuffer); out.write((byte) getLength()); out.flush();
MemoryUtil.immediateSecureBuffers(contentBuffer);
wangyeee/IBE-Secure-Message
jlib/jibe/src/main/java/hamaster/gradesgin/ibe/IBECipherText.java
// Path: jlib/jibe/src/main/java/hamaster/gradesgin/util/MemoryUtil.java // final public class MemoryUtil { // // /** // * 在新的线程中安全擦除内存块,这个方法在执行后会快速返回<br> // * 此方法与在新线程中执行immediateSecureBuffers方法等效 // * @param buffers 待擦除的内存块 // */ // public final static void fastSecureBuffers(byte[] ... buffers) { // new SecureBufferThread(buffers).start(); // } // // /** // * 立刻安全擦除内存块 // * @param buffers 待擦除的内存块 // */ // public final static void immediateSecureBuffers(byte[] ... buffers) { // BigInteger i = new BigInteger(Long.toHexString(System.nanoTime()), 16); // Random random = new SecureRandom(i.toByteArray()); // for (byte[] buffer : buffers) { // if (buffer != null) // random.nextBytes(buffer); // } // } // }
import hamaster.gradesgin.util.MemoryUtil; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Serializable; import java.util.Arrays;
return false; return true; } /* * (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "IBECipherText [uvw=" + Arrays.toString(uvw) + ", length=" + length + "]"; } /** * 序列化字段:<br/> * 密文内容 384字节<br/> * 明文有效长度 1字节<br/> * Serialize this objetc, first 384 bytes are (u,v,w) and last byte is the length of plain text(1 to 126) * @see hamaster.gradesgin.ibe.IBEConstraints#writeExternal(java.io.OutputStream) */ @Override public void writeExternal(OutputStream out) throws IOException { byte[] uvwBuffer = new byte[IBE_G_SIZE * 3]; Arrays.fill(uvwBuffer, (byte) 0); if (uvw != null) System.arraycopy(uvw, 0, uvwBuffer, 0, IBE_G_SIZE * 3 > uvw.length ? uvw.length : IBE_G_SIZE * 3); out.write(uvwBuffer); out.write((byte) length); out.flush();
// Path: jlib/jibe/src/main/java/hamaster/gradesgin/util/MemoryUtil.java // final public class MemoryUtil { // // /** // * 在新的线程中安全擦除内存块,这个方法在执行后会快速返回<br> // * 此方法与在新线程中执行immediateSecureBuffers方法等效 // * @param buffers 待擦除的内存块 // */ // public final static void fastSecureBuffers(byte[] ... buffers) { // new SecureBufferThread(buffers).start(); // } // // /** // * 立刻安全擦除内存块 // * @param buffers 待擦除的内存块 // */ // public final static void immediateSecureBuffers(byte[] ... buffers) { // BigInteger i = new BigInteger(Long.toHexString(System.nanoTime()), 16); // Random random = new SecureRandom(i.toByteArray()); // for (byte[] buffer : buffers) { // if (buffer != null) // random.nextBytes(buffer); // } // } // } // Path: jlib/jibe/src/main/java/hamaster/gradesgin/ibe/IBECipherText.java import hamaster.gradesgin.util.MemoryUtil; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Serializable; import java.util.Arrays; return false; return true; } /* * (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "IBECipherText [uvw=" + Arrays.toString(uvw) + ", length=" + length + "]"; } /** * 序列化字段:<br/> * 密文内容 384字节<br/> * 明文有效长度 1字节<br/> * Serialize this objetc, first 384 bytes are (u,v,w) and last byte is the length of plain text(1 to 126) * @see hamaster.gradesgin.ibe.IBEConstraints#writeExternal(java.io.OutputStream) */ @Override public void writeExternal(OutputStream out) throws IOException { byte[] uvwBuffer = new byte[IBE_G_SIZE * 3]; Arrays.fill(uvwBuffer, (byte) 0); if (uvw != null) System.arraycopy(uvw, 0, uvwBuffer, 0, IBE_G_SIZE * 3 > uvw.length ? uvw.length : IBE_G_SIZE * 3); out.write(uvwBuffer); out.write((byte) length); out.flush();
MemoryUtil.fastSecureBuffers(uvwBuffer);
wangyeee/IBE-Secure-Message
jlib/jibe/src/main/java/hamaster/gradesgin/ibe/IBEPublicParameter.java
// Path: jlib/jibe/src/main/java/hamaster/gradesgin/util/Hex.java // public final static int bytesToInt(byte[] bytes) { // return bytesToInt(bytes,0); // } // // Path: jlib/jibe/src/main/java/hamaster/gradesgin/util/Hex.java // public final static byte[] intToByte(int i) { // byte[] bt = new byte[4]; // bt[0] = (byte) ((0xff000000 & i) >> 24); // bt[1] = (byte) ((0xff0000 & i) >> 16); // bt[2] = (byte) ((0xff00 & i) >> 8); // bt[3] = (byte) (0xff & i); // return bt; // } // // Path: jlib/jibe/src/main/java/hamaster/gradesgin/util/MemoryUtil.java // final public class MemoryUtil { // // /** // * 在新的线程中安全擦除内存块,这个方法在执行后会快速返回<br> // * 此方法与在新线程中执行immediateSecureBuffers方法等效 // * @param buffers 待擦除的内存块 // */ // public final static void fastSecureBuffers(byte[] ... buffers) { // new SecureBufferThread(buffers).start(); // } // // /** // * 立刻安全擦除内存块 // * @param buffers 待擦除的内存块 // */ // public final static void immediateSecureBuffers(byte[] ... buffers) { // BigInteger i = new BigInteger(Long.toHexString(System.nanoTime()), 16); // Random random = new SecureRandom(i.toByteArray()); // for (byte[] buffer : buffers) { // if (buffer != null) // random.nextBytes(buffer); // } // } // }
import static hamaster.gradesgin.util.Hex.bytesToInt; import static hamaster.gradesgin.util.Hex.intToByte; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Serializable; import java.util.Arrays; import hamaster.gradesgin.util.MemoryUtil;
+ Arrays.toString(paramH) + ", pairing=" + new String(pairing) + "]"; } /** * 序列化字段:<br> * g 128字节<br> * g1 128字节<br> * h 128字节<br> * 椭圆函数参数长度 4字节<br> * 椭圆函数参数 * g 128 bytes, g1 128 bytes, h 128 bytes, length of pairing 4 bytes, pairing * @see hamaster.gradesgin.ibe.IBEConstraints#writeExternal(java.io.OutputStream) */ @Override public void writeExternal(OutputStream out) throws IOException { byte[] buffer = new byte[IBE_G_SIZE]; Arrays.fill(buffer, (byte) 0); if (paramG != null) System.arraycopy(paramG, 0, buffer, 0, IBE_G_SIZE > paramG.length ? paramG.length : IBE_G_SIZE); out.write(buffer); Arrays.fill(buffer, (byte) 0); if (paramG1 != null) System.arraycopy(paramG1, 0, buffer, 0, IBE_G_SIZE > paramG1.length ? paramG1.length : IBE_G_SIZE); out.write(buffer); Arrays.fill(buffer, (byte) 0); if (paramH != null) System.arraycopy(paramH, 0, buffer, 0, IBE_G_SIZE > paramH.length ? paramH.length : IBE_G_SIZE); out.write(buffer); int pSize = pairing == null ? IBE_G_SIZE * 4 : pairing.length;
// Path: jlib/jibe/src/main/java/hamaster/gradesgin/util/Hex.java // public final static int bytesToInt(byte[] bytes) { // return bytesToInt(bytes,0); // } // // Path: jlib/jibe/src/main/java/hamaster/gradesgin/util/Hex.java // public final static byte[] intToByte(int i) { // byte[] bt = new byte[4]; // bt[0] = (byte) ((0xff000000 & i) >> 24); // bt[1] = (byte) ((0xff0000 & i) >> 16); // bt[2] = (byte) ((0xff00 & i) >> 8); // bt[3] = (byte) (0xff & i); // return bt; // } // // Path: jlib/jibe/src/main/java/hamaster/gradesgin/util/MemoryUtil.java // final public class MemoryUtil { // // /** // * 在新的线程中安全擦除内存块,这个方法在执行后会快速返回<br> // * 此方法与在新线程中执行immediateSecureBuffers方法等效 // * @param buffers 待擦除的内存块 // */ // public final static void fastSecureBuffers(byte[] ... buffers) { // new SecureBufferThread(buffers).start(); // } // // /** // * 立刻安全擦除内存块 // * @param buffers 待擦除的内存块 // */ // public final static void immediateSecureBuffers(byte[] ... buffers) { // BigInteger i = new BigInteger(Long.toHexString(System.nanoTime()), 16); // Random random = new SecureRandom(i.toByteArray()); // for (byte[] buffer : buffers) { // if (buffer != null) // random.nextBytes(buffer); // } // } // } // Path: jlib/jibe/src/main/java/hamaster/gradesgin/ibe/IBEPublicParameter.java import static hamaster.gradesgin.util.Hex.bytesToInt; import static hamaster.gradesgin.util.Hex.intToByte; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Serializable; import java.util.Arrays; import hamaster.gradesgin.util.MemoryUtil; + Arrays.toString(paramH) + ", pairing=" + new String(pairing) + "]"; } /** * 序列化字段:<br> * g 128字节<br> * g1 128字节<br> * h 128字节<br> * 椭圆函数参数长度 4字节<br> * 椭圆函数参数 * g 128 bytes, g1 128 bytes, h 128 bytes, length of pairing 4 bytes, pairing * @see hamaster.gradesgin.ibe.IBEConstraints#writeExternal(java.io.OutputStream) */ @Override public void writeExternal(OutputStream out) throws IOException { byte[] buffer = new byte[IBE_G_SIZE]; Arrays.fill(buffer, (byte) 0); if (paramG != null) System.arraycopy(paramG, 0, buffer, 0, IBE_G_SIZE > paramG.length ? paramG.length : IBE_G_SIZE); out.write(buffer); Arrays.fill(buffer, (byte) 0); if (paramG1 != null) System.arraycopy(paramG1, 0, buffer, 0, IBE_G_SIZE > paramG1.length ? paramG1.length : IBE_G_SIZE); out.write(buffer); Arrays.fill(buffer, (byte) 0); if (paramH != null) System.arraycopy(paramH, 0, buffer, 0, IBE_G_SIZE > paramH.length ? paramH.length : IBE_G_SIZE); out.write(buffer); int pSize = pairing == null ? IBE_G_SIZE * 4 : pairing.length;
out.write(intToByte(pSize));
wangyeee/IBE-Secure-Message
jlib/jibe/src/main/java/hamaster/gradesgin/ibe/IBEPublicParameter.java
// Path: jlib/jibe/src/main/java/hamaster/gradesgin/util/Hex.java // public final static int bytesToInt(byte[] bytes) { // return bytesToInt(bytes,0); // } // // Path: jlib/jibe/src/main/java/hamaster/gradesgin/util/Hex.java // public final static byte[] intToByte(int i) { // byte[] bt = new byte[4]; // bt[0] = (byte) ((0xff000000 & i) >> 24); // bt[1] = (byte) ((0xff0000 & i) >> 16); // bt[2] = (byte) ((0xff00 & i) >> 8); // bt[3] = (byte) (0xff & i); // return bt; // } // // Path: jlib/jibe/src/main/java/hamaster/gradesgin/util/MemoryUtil.java // final public class MemoryUtil { // // /** // * 在新的线程中安全擦除内存块,这个方法在执行后会快速返回<br> // * 此方法与在新线程中执行immediateSecureBuffers方法等效 // * @param buffers 待擦除的内存块 // */ // public final static void fastSecureBuffers(byte[] ... buffers) { // new SecureBufferThread(buffers).start(); // } // // /** // * 立刻安全擦除内存块 // * @param buffers 待擦除的内存块 // */ // public final static void immediateSecureBuffers(byte[] ... buffers) { // BigInteger i = new BigInteger(Long.toHexString(System.nanoTime()), 16); // Random random = new SecureRandom(i.toByteArray()); // for (byte[] buffer : buffers) { // if (buffer != null) // random.nextBytes(buffer); // } // } // }
import static hamaster.gradesgin.util.Hex.bytesToInt; import static hamaster.gradesgin.util.Hex.intToByte; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Serializable; import java.util.Arrays; import hamaster.gradesgin.util.MemoryUtil;
* g1 128字节<br> * h 128字节<br> * 椭圆函数参数长度 4字节<br> * 椭圆函数参数 * g 128 bytes, g1 128 bytes, h 128 bytes, length of pairing 4 bytes, pairing * @see hamaster.gradesgin.ibe.IBEConstraints#writeExternal(java.io.OutputStream) */ @Override public void writeExternal(OutputStream out) throws IOException { byte[] buffer = new byte[IBE_G_SIZE]; Arrays.fill(buffer, (byte) 0); if (paramG != null) System.arraycopy(paramG, 0, buffer, 0, IBE_G_SIZE > paramG.length ? paramG.length : IBE_G_SIZE); out.write(buffer); Arrays.fill(buffer, (byte) 0); if (paramG1 != null) System.arraycopy(paramG1, 0, buffer, 0, IBE_G_SIZE > paramG1.length ? paramG1.length : IBE_G_SIZE); out.write(buffer); Arrays.fill(buffer, (byte) 0); if (paramH != null) System.arraycopy(paramH, 0, buffer, 0, IBE_G_SIZE > paramH.length ? paramH.length : IBE_G_SIZE); out.write(buffer); int pSize = pairing == null ? IBE_G_SIZE * 4 : pairing.length; out.write(intToByte(pSize)); byte[] pBuffer = new byte[IBE_G_SIZE * 4]; Arrays.fill(pBuffer, (byte) 0); if (pairing != null) System.arraycopy(pairing, 0, pBuffer, 0, pairing.length); out.write(pBuffer, 0, pairing == null ? pBuffer.length : pairing.length); out.flush();
// Path: jlib/jibe/src/main/java/hamaster/gradesgin/util/Hex.java // public final static int bytesToInt(byte[] bytes) { // return bytesToInt(bytes,0); // } // // Path: jlib/jibe/src/main/java/hamaster/gradesgin/util/Hex.java // public final static byte[] intToByte(int i) { // byte[] bt = new byte[4]; // bt[0] = (byte) ((0xff000000 & i) >> 24); // bt[1] = (byte) ((0xff0000 & i) >> 16); // bt[2] = (byte) ((0xff00 & i) >> 8); // bt[3] = (byte) (0xff & i); // return bt; // } // // Path: jlib/jibe/src/main/java/hamaster/gradesgin/util/MemoryUtil.java // final public class MemoryUtil { // // /** // * 在新的线程中安全擦除内存块,这个方法在执行后会快速返回<br> // * 此方法与在新线程中执行immediateSecureBuffers方法等效 // * @param buffers 待擦除的内存块 // */ // public final static void fastSecureBuffers(byte[] ... buffers) { // new SecureBufferThread(buffers).start(); // } // // /** // * 立刻安全擦除内存块 // * @param buffers 待擦除的内存块 // */ // public final static void immediateSecureBuffers(byte[] ... buffers) { // BigInteger i = new BigInteger(Long.toHexString(System.nanoTime()), 16); // Random random = new SecureRandom(i.toByteArray()); // for (byte[] buffer : buffers) { // if (buffer != null) // random.nextBytes(buffer); // } // } // } // Path: jlib/jibe/src/main/java/hamaster/gradesgin/ibe/IBEPublicParameter.java import static hamaster.gradesgin.util.Hex.bytesToInt; import static hamaster.gradesgin.util.Hex.intToByte; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Serializable; import java.util.Arrays; import hamaster.gradesgin.util.MemoryUtil; * g1 128字节<br> * h 128字节<br> * 椭圆函数参数长度 4字节<br> * 椭圆函数参数 * g 128 bytes, g1 128 bytes, h 128 bytes, length of pairing 4 bytes, pairing * @see hamaster.gradesgin.ibe.IBEConstraints#writeExternal(java.io.OutputStream) */ @Override public void writeExternal(OutputStream out) throws IOException { byte[] buffer = new byte[IBE_G_SIZE]; Arrays.fill(buffer, (byte) 0); if (paramG != null) System.arraycopy(paramG, 0, buffer, 0, IBE_G_SIZE > paramG.length ? paramG.length : IBE_G_SIZE); out.write(buffer); Arrays.fill(buffer, (byte) 0); if (paramG1 != null) System.arraycopy(paramG1, 0, buffer, 0, IBE_G_SIZE > paramG1.length ? paramG1.length : IBE_G_SIZE); out.write(buffer); Arrays.fill(buffer, (byte) 0); if (paramH != null) System.arraycopy(paramH, 0, buffer, 0, IBE_G_SIZE > paramH.length ? paramH.length : IBE_G_SIZE); out.write(buffer); int pSize = pairing == null ? IBE_G_SIZE * 4 : pairing.length; out.write(intToByte(pSize)); byte[] pBuffer = new byte[IBE_G_SIZE * 4]; Arrays.fill(pBuffer, (byte) 0); if (pairing != null) System.arraycopy(pairing, 0, pBuffer, 0, pairing.length); out.write(pBuffer, 0, pairing == null ? pBuffer.length : pairing.length); out.flush();
MemoryUtil.fastSecureBuffers(buffer, pBuffer);
wangyeee/IBE-Secure-Message
jlib/jibe/src/main/java/hamaster/gradesgin/ibe/IBEPublicParameter.java
// Path: jlib/jibe/src/main/java/hamaster/gradesgin/util/Hex.java // public final static int bytesToInt(byte[] bytes) { // return bytesToInt(bytes,0); // } // // Path: jlib/jibe/src/main/java/hamaster/gradesgin/util/Hex.java // public final static byte[] intToByte(int i) { // byte[] bt = new byte[4]; // bt[0] = (byte) ((0xff000000 & i) >> 24); // bt[1] = (byte) ((0xff0000 & i) >> 16); // bt[2] = (byte) ((0xff00 & i) >> 8); // bt[3] = (byte) (0xff & i); // return bt; // } // // Path: jlib/jibe/src/main/java/hamaster/gradesgin/util/MemoryUtil.java // final public class MemoryUtil { // // /** // * 在新的线程中安全擦除内存块,这个方法在执行后会快速返回<br> // * 此方法与在新线程中执行immediateSecureBuffers方法等效 // * @param buffers 待擦除的内存块 // */ // public final static void fastSecureBuffers(byte[] ... buffers) { // new SecureBufferThread(buffers).start(); // } // // /** // * 立刻安全擦除内存块 // * @param buffers 待擦除的内存块 // */ // public final static void immediateSecureBuffers(byte[] ... buffers) { // BigInteger i = new BigInteger(Long.toHexString(System.nanoTime()), 16); // Random random = new SecureRandom(i.toByteArray()); // for (byte[] buffer : buffers) { // if (buffer != null) // random.nextBytes(buffer); // } // } // }
import static hamaster.gradesgin.util.Hex.bytesToInt; import static hamaster.gradesgin.util.Hex.intToByte; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Serializable; import java.util.Arrays; import hamaster.gradesgin.util.MemoryUtil;
out.write(intToByte(pSize)); byte[] pBuffer = new byte[IBE_G_SIZE * 4]; Arrays.fill(pBuffer, (byte) 0); if (pairing != null) System.arraycopy(pairing, 0, pBuffer, 0, pairing.length); out.write(pBuffer, 0, pairing == null ? pBuffer.length : pairing.length); out.flush(); MemoryUtil.fastSecureBuffers(buffer, pBuffer); } /* * (non-Javadoc) * @see hamaster.gradesgin.ibe.IBEConstraints#readExternal(java.io.InputStream) */ @Override public void readExternal(InputStream in) throws IOException, ClassNotFoundException { byte[] buffer = new byte[IBE_G_SIZE * 3]; int pSize = in.read(buffer); if (pSize < buffer.length) { // 字节数少于期望值,数据丢失 throw new IOException("Not enough bytes for a PublicParameter"); } this.paramG = new byte[IBE_G_SIZE]; this.paramG1 = new byte[IBE_G_SIZE]; this.paramH = new byte[IBE_G_SIZE]; byte[] pTmp = new byte[4]; Arrays.fill(pTmp, (byte) 0); if (4 != in.read(pTmp)) { throw new IOException("Not enough bytes for a PublicParameter"); }
// Path: jlib/jibe/src/main/java/hamaster/gradesgin/util/Hex.java // public final static int bytesToInt(byte[] bytes) { // return bytesToInt(bytes,0); // } // // Path: jlib/jibe/src/main/java/hamaster/gradesgin/util/Hex.java // public final static byte[] intToByte(int i) { // byte[] bt = new byte[4]; // bt[0] = (byte) ((0xff000000 & i) >> 24); // bt[1] = (byte) ((0xff0000 & i) >> 16); // bt[2] = (byte) ((0xff00 & i) >> 8); // bt[3] = (byte) (0xff & i); // return bt; // } // // Path: jlib/jibe/src/main/java/hamaster/gradesgin/util/MemoryUtil.java // final public class MemoryUtil { // // /** // * 在新的线程中安全擦除内存块,这个方法在执行后会快速返回<br> // * 此方法与在新线程中执行immediateSecureBuffers方法等效 // * @param buffers 待擦除的内存块 // */ // public final static void fastSecureBuffers(byte[] ... buffers) { // new SecureBufferThread(buffers).start(); // } // // /** // * 立刻安全擦除内存块 // * @param buffers 待擦除的内存块 // */ // public final static void immediateSecureBuffers(byte[] ... buffers) { // BigInteger i = new BigInteger(Long.toHexString(System.nanoTime()), 16); // Random random = new SecureRandom(i.toByteArray()); // for (byte[] buffer : buffers) { // if (buffer != null) // random.nextBytes(buffer); // } // } // } // Path: jlib/jibe/src/main/java/hamaster/gradesgin/ibe/IBEPublicParameter.java import static hamaster.gradesgin.util.Hex.bytesToInt; import static hamaster.gradesgin.util.Hex.intToByte; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Serializable; import java.util.Arrays; import hamaster.gradesgin.util.MemoryUtil; out.write(intToByte(pSize)); byte[] pBuffer = new byte[IBE_G_SIZE * 4]; Arrays.fill(pBuffer, (byte) 0); if (pairing != null) System.arraycopy(pairing, 0, pBuffer, 0, pairing.length); out.write(pBuffer, 0, pairing == null ? pBuffer.length : pairing.length); out.flush(); MemoryUtil.fastSecureBuffers(buffer, pBuffer); } /* * (non-Javadoc) * @see hamaster.gradesgin.ibe.IBEConstraints#readExternal(java.io.InputStream) */ @Override public void readExternal(InputStream in) throws IOException, ClassNotFoundException { byte[] buffer = new byte[IBE_G_SIZE * 3]; int pSize = in.read(buffer); if (pSize < buffer.length) { // 字节数少于期望值,数据丢失 throw new IOException("Not enough bytes for a PublicParameter"); } this.paramG = new byte[IBE_G_SIZE]; this.paramG1 = new byte[IBE_G_SIZE]; this.paramH = new byte[IBE_G_SIZE]; byte[] pTmp = new byte[4]; Arrays.fill(pTmp, (byte) 0); if (4 != in.read(pTmp)) { throw new IOException("Not enough bytes for a PublicParameter"); }
pSize = bytesToInt(pTmp);
wangyeee/IBE-Secure-Message
jlib/jibe/src/main/java/hamaster/gradesgin/util/IBECapsuleAESImpl.java
// Path: jlib/jibe/src/main/java/hamaster/gradesgin/util/Hex.java // public final static int bytesToInt(byte[] bytes) { // return bytesToInt(bytes,0); // } // // Path: jlib/jibe/src/main/java/hamaster/gradesgin/util/Hex.java // public final static byte[] intToByte(int i) { // byte[] bt = new byte[4]; // bt[0] = (byte) ((0xff000000 & i) >> 24); // bt[1] = (byte) ((0xff0000 & i) >> 16); // bt[2] = (byte) ((0xff00 & i) >> 8); // bt[3] = (byte) (0xff & i); // return bt; // }
import static hamaster.gradesgin.util.Hex.bytesToInt; import static hamaster.gradesgin.util.Hex.intToByte; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.Serializable; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec;
ensureNotNull(out, data, key); byte[] key = Hash.sha256(this.key); byte[] iv = Hash.md5(this.key); byte[] keyHash = Hash.sha512(this.key); byte[] crypt = null; try { Cipher cipher = Cipher.getInstance(CRYPTO_ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(iv)); crypt = cipher.doFinal(data); } catch (NoSuchAlgorithmException e) { } catch (NoSuchPaddingException e) { } catch (InvalidKeyException e) { throw new IOException(e); } catch (InvalidAlgorithmParameterException e) { } catch (IllegalBlockSizeException e) { throw new IOException(e); } catch (BadPaddingException e) { throw new IOException(e); } finally { Arrays.fill(key, (byte) 0); Arrays.fill(iv, (byte) 0); } if (crypt == null) throw new IOException("Cannot encrypt data!"); byte cl = (byte) CRYPTO_ALGORITHM.length(); out.write(cl); out.write(CRYPTO_ALGORITHM.getBytes()); out.write((byte) HASH_ALGORITHM.length()); out.write(HASH_ALGORITHM.getBytes()); out.write(keyHash);
// Path: jlib/jibe/src/main/java/hamaster/gradesgin/util/Hex.java // public final static int bytesToInt(byte[] bytes) { // return bytesToInt(bytes,0); // } // // Path: jlib/jibe/src/main/java/hamaster/gradesgin/util/Hex.java // public final static byte[] intToByte(int i) { // byte[] bt = new byte[4]; // bt[0] = (byte) ((0xff000000 & i) >> 24); // bt[1] = (byte) ((0xff0000 & i) >> 16); // bt[2] = (byte) ((0xff00 & i) >> 8); // bt[3] = (byte) (0xff & i); // return bt; // } // Path: jlib/jibe/src/main/java/hamaster/gradesgin/util/IBECapsuleAESImpl.java import static hamaster.gradesgin.util.Hex.bytesToInt; import static hamaster.gradesgin.util.Hex.intToByte; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.Serializable; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; ensureNotNull(out, data, key); byte[] key = Hash.sha256(this.key); byte[] iv = Hash.md5(this.key); byte[] keyHash = Hash.sha512(this.key); byte[] crypt = null; try { Cipher cipher = Cipher.getInstance(CRYPTO_ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(iv)); crypt = cipher.doFinal(data); } catch (NoSuchAlgorithmException e) { } catch (NoSuchPaddingException e) { } catch (InvalidKeyException e) { throw new IOException(e); } catch (InvalidAlgorithmParameterException e) { } catch (IllegalBlockSizeException e) { throw new IOException(e); } catch (BadPaddingException e) { throw new IOException(e); } finally { Arrays.fill(key, (byte) 0); Arrays.fill(iv, (byte) 0); } if (crypt == null) throw new IOException("Cannot encrypt data!"); byte cl = (byte) CRYPTO_ALGORITHM.length(); out.write(cl); out.write(CRYPTO_ALGORITHM.getBytes()); out.write((byte) HASH_ALGORITHM.length()); out.write(HASH_ALGORITHM.getBytes()); out.write(keyHash);
out.write(intToByte(data.length));
wangyeee/IBE-Secure-Message
jlib/jibe/src/main/java/hamaster/gradesgin/util/IBECapsuleAESImpl.java
// Path: jlib/jibe/src/main/java/hamaster/gradesgin/util/Hex.java // public final static int bytesToInt(byte[] bytes) { // return bytesToInt(bytes,0); // } // // Path: jlib/jibe/src/main/java/hamaster/gradesgin/util/Hex.java // public final static byte[] intToByte(int i) { // byte[] bt = new byte[4]; // bt[0] = (byte) ((0xff000000 & i) >> 24); // bt[1] = (byte) ((0xff0000 & i) >> 16); // bt[2] = (byte) ((0xff00 & i) >> 8); // bt[3] = (byte) (0xff & i); // return bt; // }
import static hamaster.gradesgin.util.Hex.bytesToInt; import static hamaster.gradesgin.util.Hex.intToByte; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.Serializable; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec;
out.write(HASH_ALGORITHM.getBytes()); out.write(keyHash); out.write(intToByte(data.length)); out.write(intToByte(crypt.length)); out.write(crypt); out.flush(); } /* * (non-Javadoc) * @see hamaster.gradesgin.ibe.IBEConstraints#readExternal(java.io.InputStream) */ @Override public void readExternal(InputStream in) throws IOException, ClassNotFoundException { int cLength = in.read(); byte[] cBuffer = new byte[cLength]; cLength = in.read(cBuffer); if (cLength != cBuffer.length) throw new IOException("Not enough bytes!"); int hLength = in.read(); byte[] hnBuffer = new byte[hLength]; hLength = in.read(hnBuffer); if (hLength != hnBuffer.length) throw new IOException("Not enough bytes!"); this.keyHash = new byte[64]; in.read(keyHash); byte[] tmp = new byte[4]; int tLength = in.read(tmp); if (tLength != tmp.length) throw new IOException("Not enough bytes!");
// Path: jlib/jibe/src/main/java/hamaster/gradesgin/util/Hex.java // public final static int bytesToInt(byte[] bytes) { // return bytesToInt(bytes,0); // } // // Path: jlib/jibe/src/main/java/hamaster/gradesgin/util/Hex.java // public final static byte[] intToByte(int i) { // byte[] bt = new byte[4]; // bt[0] = (byte) ((0xff000000 & i) >> 24); // bt[1] = (byte) ((0xff0000 & i) >> 16); // bt[2] = (byte) ((0xff00 & i) >> 8); // bt[3] = (byte) (0xff & i); // return bt; // } // Path: jlib/jibe/src/main/java/hamaster/gradesgin/util/IBECapsuleAESImpl.java import static hamaster.gradesgin.util.Hex.bytesToInt; import static hamaster.gradesgin.util.Hex.intToByte; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.Serializable; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; out.write(HASH_ALGORITHM.getBytes()); out.write(keyHash); out.write(intToByte(data.length)); out.write(intToByte(crypt.length)); out.write(crypt); out.flush(); } /* * (non-Javadoc) * @see hamaster.gradesgin.ibe.IBEConstraints#readExternal(java.io.InputStream) */ @Override public void readExternal(InputStream in) throws IOException, ClassNotFoundException { int cLength = in.read(); byte[] cBuffer = new byte[cLength]; cLength = in.read(cBuffer); if (cLength != cBuffer.length) throw new IOException("Not enough bytes!"); int hLength = in.read(); byte[] hnBuffer = new byte[hLength]; hLength = in.read(hnBuffer); if (hLength != hnBuffer.length) throw new IOException("Not enough bytes!"); this.keyHash = new byte[64]; in.read(keyHash); byte[] tmp = new byte[4]; int tLength = in.read(tmp); if (tLength != tmp.length) throw new IOException("Not enough bytes!");
int dataLength = bytesToInt(tmp);
rzwitserloot/lombok.ast
src/printer/lombok/ast/printer/StructureFormatter.java
// Path: src/ast/lombok/ast/StructuralElement.java // public interface StructuralElement { // // Position getPosition(); // // String getContent(); // }
import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import lombok.ast.DescribedNode; import lombok.ast.Node; import lombok.ast.StructuralElement;
/* * Copyright (C) 2010-2015 The Project Lombok Authors. * * 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 lombok.ast.printer; public class StructureFormatter implements SourceFormatter { private static final String INDENT = " "; private final StringBuilder sb = new StringBuilder(); private final List<String> errors = Lists.newArrayList(); private int indent;
// Path: src/ast/lombok/ast/StructuralElement.java // public interface StructuralElement { // // Position getPosition(); // // String getContent(); // } // Path: src/printer/lombok/ast/printer/StructureFormatter.java import com.google.common.base.Joiner; import com.google.common.collect.Lists; import com.google.common.collect.Sets; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import lombok.ast.DescribedNode; import lombok.ast.Node; import lombok.ast.StructuralElement; /* * Copyright (C) 2010-2015 The Project Lombok Authors. * * 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 lombok.ast.printer; public class StructureFormatter implements SourceFormatter { private static final String INDENT = " "; private final StringBuilder sb = new StringBuilder(); private final List<String> errors = Lists.newArrayList(); private int indent;
private final Map<Node, Collection<StructuralElement>> sourceStructures;
rzwitserloot/lombok.ast
test/src/lombok/ast/grammar/TreeBuilderRunner.java
// Path: test/src/lombok/ast/grammar/RunForEachFileInDirRunner.java // public static String fixLineEndings(String in) { // String plaf = System.getProperty("line.separator", "\n"); // if (plaf.equals("\n")) return in; // return in.replace(plaf, "\n"); // } // // Path: test/src/lombok/ast/grammar/RunForEachFileInDirRunner.java // @Data // public static final class DirDescriptor implements Comparable<DirDescriptor> { // private final File directory; // private final Pattern inclusionPattern; // private final Pattern exclusionPattern; // private final File mirrorDirectory; // private final boolean recurse; // // public static DirDescriptor of(File directory, boolean recurse) { // return new DirDescriptor(directory, Pattern.compile("^.*\\.java$"), null, null, recurse); // } // // public DirDescriptor withExclusion(Pattern pattern) { // return new DirDescriptor(directory, inclusionPattern, pattern, mirrorDirectory, recurse); // } // // public DirDescriptor withInclusion(Pattern pattern) { // return new DirDescriptor(directory, pattern, exclusionPattern, mirrorDirectory, recurse); // } // // public DirDescriptor withMirror(File mirror) { // return new DirDescriptor(directory, inclusionPattern, exclusionPattern, mirror, recurse); // } // // @Override // public int compareTo(DirDescriptor other) { // int result = directory.getAbsolutePath().compareTo(other.directory.getAbsolutePath()); // if (result != 0) return result; // if (mirrorDirectory != null && other.mirrorDirectory == null) return +1; // if (mirrorDirectory == null && other.mirrorDirectory != null) return -1; // if (mirrorDirectory != null) result = mirrorDirectory.getAbsolutePath().compareTo(other.mirrorDirectory.getAbsolutePath()); // if (result != 0) return result; // if (recurse && !other.recurse) return +1; // if (!recurse && other.recurse) return -1; // if (inclusionPattern != null && other.inclusionPattern == null) return +1; // if (inclusionPattern == null && other.inclusionPattern != null) return -1; // if (inclusionPattern != null) result = inclusionPattern.pattern().compareTo(other.inclusionPattern.pattern()); // if (result != 0) return result; // if (exclusionPattern != null && other.exclusionPattern == null) return +1; // if (exclusionPattern == null && other.exclusionPattern != null) return -1; // if (exclusionPattern != null) result = exclusionPattern.pattern().compareTo(other.exclusionPattern.pattern()); // return result; // } // }
import static org.junit.Assert.*; import static lombok.ast.grammar.RunForEachFileInDirRunner.fixLineEndings; import java.io.File; import java.util.Arrays; import java.util.Collection; import lombok.ast.grammar.RunForEachFileInDirRunner.DirDescriptor;
/* * Copyright (C) 2010 The Project Lombok Authors. * * 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 lombok.ast.grammar; abstract class TreeBuilderRunner<N> extends RunForEachFileInDirRunner.SourceFileBasedTester { private final boolean lombokIsActual; protected TreeBuilderRunner(boolean lombokIsActual) { this.lombokIsActual = lombokIsActual; } @Override
// Path: test/src/lombok/ast/grammar/RunForEachFileInDirRunner.java // public static String fixLineEndings(String in) { // String plaf = System.getProperty("line.separator", "\n"); // if (plaf.equals("\n")) return in; // return in.replace(plaf, "\n"); // } // // Path: test/src/lombok/ast/grammar/RunForEachFileInDirRunner.java // @Data // public static final class DirDescriptor implements Comparable<DirDescriptor> { // private final File directory; // private final Pattern inclusionPattern; // private final Pattern exclusionPattern; // private final File mirrorDirectory; // private final boolean recurse; // // public static DirDescriptor of(File directory, boolean recurse) { // return new DirDescriptor(directory, Pattern.compile("^.*\\.java$"), null, null, recurse); // } // // public DirDescriptor withExclusion(Pattern pattern) { // return new DirDescriptor(directory, inclusionPattern, pattern, mirrorDirectory, recurse); // } // // public DirDescriptor withInclusion(Pattern pattern) { // return new DirDescriptor(directory, pattern, exclusionPattern, mirrorDirectory, recurse); // } // // public DirDescriptor withMirror(File mirror) { // return new DirDescriptor(directory, inclusionPattern, exclusionPattern, mirror, recurse); // } // // @Override // public int compareTo(DirDescriptor other) { // int result = directory.getAbsolutePath().compareTo(other.directory.getAbsolutePath()); // if (result != 0) return result; // if (mirrorDirectory != null && other.mirrorDirectory == null) return +1; // if (mirrorDirectory == null && other.mirrorDirectory != null) return -1; // if (mirrorDirectory != null) result = mirrorDirectory.getAbsolutePath().compareTo(other.mirrorDirectory.getAbsolutePath()); // if (result != 0) return result; // if (recurse && !other.recurse) return +1; // if (!recurse && other.recurse) return -1; // if (inclusionPattern != null && other.inclusionPattern == null) return +1; // if (inclusionPattern == null && other.inclusionPattern != null) return -1; // if (inclusionPattern != null) result = inclusionPattern.pattern().compareTo(other.inclusionPattern.pattern()); // if (result != 0) return result; // if (exclusionPattern != null && other.exclusionPattern == null) return +1; // if (exclusionPattern == null && other.exclusionPattern != null) return -1; // if (exclusionPattern != null) result = exclusionPattern.pattern().compareTo(other.exclusionPattern.pattern()); // return result; // } // } // Path: test/src/lombok/ast/grammar/TreeBuilderRunner.java import static org.junit.Assert.*; import static lombok.ast.grammar.RunForEachFileInDirRunner.fixLineEndings; import java.io.File; import java.util.Arrays; import java.util.Collection; import lombok.ast.grammar.RunForEachFileInDirRunner.DirDescriptor; /* * Copyright (C) 2010 The Project Lombok Authors. * * 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 lombok.ast.grammar; abstract class TreeBuilderRunner<N> extends RunForEachFileInDirRunner.SourceFileBasedTester { private final boolean lombokIsActual; protected TreeBuilderRunner(boolean lombokIsActual) { this.lombokIsActual = lombokIsActual; } @Override
protected Collection<DirDescriptor> getDirDescriptors() {
rzwitserloot/lombok.ast
test/src/lombok/ast/grammar/TreeBuilderRunner.java
// Path: test/src/lombok/ast/grammar/RunForEachFileInDirRunner.java // public static String fixLineEndings(String in) { // String plaf = System.getProperty("line.separator", "\n"); // if (plaf.equals("\n")) return in; // return in.replace(plaf, "\n"); // } // // Path: test/src/lombok/ast/grammar/RunForEachFileInDirRunner.java // @Data // public static final class DirDescriptor implements Comparable<DirDescriptor> { // private final File directory; // private final Pattern inclusionPattern; // private final Pattern exclusionPattern; // private final File mirrorDirectory; // private final boolean recurse; // // public static DirDescriptor of(File directory, boolean recurse) { // return new DirDescriptor(directory, Pattern.compile("^.*\\.java$"), null, null, recurse); // } // // public DirDescriptor withExclusion(Pattern pattern) { // return new DirDescriptor(directory, inclusionPattern, pattern, mirrorDirectory, recurse); // } // // public DirDescriptor withInclusion(Pattern pattern) { // return new DirDescriptor(directory, pattern, exclusionPattern, mirrorDirectory, recurse); // } // // public DirDescriptor withMirror(File mirror) { // return new DirDescriptor(directory, inclusionPattern, exclusionPattern, mirror, recurse); // } // // @Override // public int compareTo(DirDescriptor other) { // int result = directory.getAbsolutePath().compareTo(other.directory.getAbsolutePath()); // if (result != 0) return result; // if (mirrorDirectory != null && other.mirrorDirectory == null) return +1; // if (mirrorDirectory == null && other.mirrorDirectory != null) return -1; // if (mirrorDirectory != null) result = mirrorDirectory.getAbsolutePath().compareTo(other.mirrorDirectory.getAbsolutePath()); // if (result != 0) return result; // if (recurse && !other.recurse) return +1; // if (!recurse && other.recurse) return -1; // if (inclusionPattern != null && other.inclusionPattern == null) return +1; // if (inclusionPattern == null && other.inclusionPattern != null) return -1; // if (inclusionPattern != null) result = inclusionPattern.pattern().compareTo(other.inclusionPattern.pattern()); // if (result != 0) return result; // if (exclusionPattern != null && other.exclusionPattern == null) return +1; // if (exclusionPattern == null && other.exclusionPattern != null) return -1; // if (exclusionPattern != null) result = exclusionPattern.pattern().compareTo(other.exclusionPattern.pattern()); // return result; // } // }
import static org.junit.Assert.*; import static lombok.ast.grammar.RunForEachFileInDirRunner.fixLineEndings; import java.io.File; import java.util.Arrays; import java.util.Collection; import lombok.ast.grammar.RunForEachFileInDirRunner.DirDescriptor;
DirDescriptor.of(new File("test/resources/idempotency"), true), DirDescriptor.of(new File("test/resources/alias"), true), DirDescriptor.of(new File("test/resources/special"), true)); } protected void testCompiler(Source source) throws Exception { N parsedWithTargetCompiler = parseWithTargetCompiler(source); if (parsedWithTargetCompiler == null) { // Skip test if target compiler can't compile it. // A separate test that checks if test samples compile // at all will do error reporting. fail("Compilation error, will be reported separately"); } String targetString = convertToString(parsedWithTargetCompiler); if (checkForLombokAstParseFailure()) { source.parseCompilationUnit(); if (!source.getProblems().isEmpty()) { StringBuilder message = new StringBuilder(); for (ParseProblem p : source.getProblems()) { message.append(p.toString()); message.append("\n"); } printDebugInformation(source, targetString, null); fail(message.toString()); } } String lombokString; try {
// Path: test/src/lombok/ast/grammar/RunForEachFileInDirRunner.java // public static String fixLineEndings(String in) { // String plaf = System.getProperty("line.separator", "\n"); // if (plaf.equals("\n")) return in; // return in.replace(plaf, "\n"); // } // // Path: test/src/lombok/ast/grammar/RunForEachFileInDirRunner.java // @Data // public static final class DirDescriptor implements Comparable<DirDescriptor> { // private final File directory; // private final Pattern inclusionPattern; // private final Pattern exclusionPattern; // private final File mirrorDirectory; // private final boolean recurse; // // public static DirDescriptor of(File directory, boolean recurse) { // return new DirDescriptor(directory, Pattern.compile("^.*\\.java$"), null, null, recurse); // } // // public DirDescriptor withExclusion(Pattern pattern) { // return new DirDescriptor(directory, inclusionPattern, pattern, mirrorDirectory, recurse); // } // // public DirDescriptor withInclusion(Pattern pattern) { // return new DirDescriptor(directory, pattern, exclusionPattern, mirrorDirectory, recurse); // } // // public DirDescriptor withMirror(File mirror) { // return new DirDescriptor(directory, inclusionPattern, exclusionPattern, mirror, recurse); // } // // @Override // public int compareTo(DirDescriptor other) { // int result = directory.getAbsolutePath().compareTo(other.directory.getAbsolutePath()); // if (result != 0) return result; // if (mirrorDirectory != null && other.mirrorDirectory == null) return +1; // if (mirrorDirectory == null && other.mirrorDirectory != null) return -1; // if (mirrorDirectory != null) result = mirrorDirectory.getAbsolutePath().compareTo(other.mirrorDirectory.getAbsolutePath()); // if (result != 0) return result; // if (recurse && !other.recurse) return +1; // if (!recurse && other.recurse) return -1; // if (inclusionPattern != null && other.inclusionPattern == null) return +1; // if (inclusionPattern == null && other.inclusionPattern != null) return -1; // if (inclusionPattern != null) result = inclusionPattern.pattern().compareTo(other.inclusionPattern.pattern()); // if (result != 0) return result; // if (exclusionPattern != null && other.exclusionPattern == null) return +1; // if (exclusionPattern == null && other.exclusionPattern != null) return -1; // if (exclusionPattern != null) result = exclusionPattern.pattern().compareTo(other.exclusionPattern.pattern()); // return result; // } // } // Path: test/src/lombok/ast/grammar/TreeBuilderRunner.java import static org.junit.Assert.*; import static lombok.ast.grammar.RunForEachFileInDirRunner.fixLineEndings; import java.io.File; import java.util.Arrays; import java.util.Collection; import lombok.ast.grammar.RunForEachFileInDirRunner.DirDescriptor; DirDescriptor.of(new File("test/resources/idempotency"), true), DirDescriptor.of(new File("test/resources/alias"), true), DirDescriptor.of(new File("test/resources/special"), true)); } protected void testCompiler(Source source) throws Exception { N parsedWithTargetCompiler = parseWithTargetCompiler(source); if (parsedWithTargetCompiler == null) { // Skip test if target compiler can't compile it. // A separate test that checks if test samples compile // at all will do error reporting. fail("Compilation error, will be reported separately"); } String targetString = convertToString(parsedWithTargetCompiler); if (checkForLombokAstParseFailure()) { source.parseCompilationUnit(); if (!source.getProblems().isEmpty()) { StringBuilder message = new StringBuilder(); for (ParseProblem p : source.getProblems()) { message.append(p.toString()); message.append("\n"); } printDebugInformation(source, targetString, null); fail(message.toString()); } } String lombokString; try {
lombokString = fixLineEndings(convertToString(parseWithLombok(source)));
rzwitserloot/lombok.ast
test/src/lombok/ast/grammar/AlternativeStringConcatEcjTreeBuilderTest.java
// Path: test/src/lombok/ast/grammar/RunForEachFileInDirRunner.java // @Data // public static final class DirDescriptor implements Comparable<DirDescriptor> { // private final File directory; // private final Pattern inclusionPattern; // private final Pattern exclusionPattern; // private final File mirrorDirectory; // private final boolean recurse; // // public static DirDescriptor of(File directory, boolean recurse) { // return new DirDescriptor(directory, Pattern.compile("^.*\\.java$"), null, null, recurse); // } // // public DirDescriptor withExclusion(Pattern pattern) { // return new DirDescriptor(directory, inclusionPattern, pattern, mirrorDirectory, recurse); // } // // public DirDescriptor withInclusion(Pattern pattern) { // return new DirDescriptor(directory, pattern, exclusionPattern, mirrorDirectory, recurse); // } // // public DirDescriptor withMirror(File mirror) { // return new DirDescriptor(directory, inclusionPattern, exclusionPattern, mirror, recurse); // } // // @Override // public int compareTo(DirDescriptor other) { // int result = directory.getAbsolutePath().compareTo(other.directory.getAbsolutePath()); // if (result != 0) return result; // if (mirrorDirectory != null && other.mirrorDirectory == null) return +1; // if (mirrorDirectory == null && other.mirrorDirectory != null) return -1; // if (mirrorDirectory != null) result = mirrorDirectory.getAbsolutePath().compareTo(other.mirrorDirectory.getAbsolutePath()); // if (result != 0) return result; // if (recurse && !other.recurse) return +1; // if (!recurse && other.recurse) return -1; // if (inclusionPattern != null && other.inclusionPattern == null) return +1; // if (inclusionPattern == null && other.inclusionPattern != null) return -1; // if (inclusionPattern != null) result = inclusionPattern.pattern().compareTo(other.inclusionPattern.pattern()); // if (result != 0) return result; // if (exclusionPattern != null && other.exclusionPattern == null) return +1; // if (exclusionPattern == null && other.exclusionPattern != null) return -1; // if (exclusionPattern != null) result = exclusionPattern.pattern().compareTo(other.exclusionPattern.pattern()); // return result; // } // }
import org.junit.Test; import org.junit.runner.RunWith; import static java.util.Collections.singleton; import java.io.File; import java.util.Collection; import java.util.regex.Pattern; import lombok.ast.grammar.RunForEachFileInDirRunner.DirDescriptor; import org.eclipse.jdt.internal.compiler.impl.CompilerOptions;
/* * Copyright (C) 2010 The Project Lombok Authors. * * 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 lombok.ast.grammar; @RunWith(RunForEachFileInDirRunner.class) public class AlternativeStringConcatEcjTreeBuilderTest extends EcjTreeBuilderTest {
// Path: test/src/lombok/ast/grammar/RunForEachFileInDirRunner.java // @Data // public static final class DirDescriptor implements Comparable<DirDescriptor> { // private final File directory; // private final Pattern inclusionPattern; // private final Pattern exclusionPattern; // private final File mirrorDirectory; // private final boolean recurse; // // public static DirDescriptor of(File directory, boolean recurse) { // return new DirDescriptor(directory, Pattern.compile("^.*\\.java$"), null, null, recurse); // } // // public DirDescriptor withExclusion(Pattern pattern) { // return new DirDescriptor(directory, inclusionPattern, pattern, mirrorDirectory, recurse); // } // // public DirDescriptor withInclusion(Pattern pattern) { // return new DirDescriptor(directory, pattern, exclusionPattern, mirrorDirectory, recurse); // } // // public DirDescriptor withMirror(File mirror) { // return new DirDescriptor(directory, inclusionPattern, exclusionPattern, mirror, recurse); // } // // @Override // public int compareTo(DirDescriptor other) { // int result = directory.getAbsolutePath().compareTo(other.directory.getAbsolutePath()); // if (result != 0) return result; // if (mirrorDirectory != null && other.mirrorDirectory == null) return +1; // if (mirrorDirectory == null && other.mirrorDirectory != null) return -1; // if (mirrorDirectory != null) result = mirrorDirectory.getAbsolutePath().compareTo(other.mirrorDirectory.getAbsolutePath()); // if (result != 0) return result; // if (recurse && !other.recurse) return +1; // if (!recurse && other.recurse) return -1; // if (inclusionPattern != null && other.inclusionPattern == null) return +1; // if (inclusionPattern == null && other.inclusionPattern != null) return -1; // if (inclusionPattern != null) result = inclusionPattern.pattern().compareTo(other.inclusionPattern.pattern()); // if (result != 0) return result; // if (exclusionPattern != null && other.exclusionPattern == null) return +1; // if (exclusionPattern == null && other.exclusionPattern != null) return -1; // if (exclusionPattern != null) result = exclusionPattern.pattern().compareTo(other.exclusionPattern.pattern()); // return result; // } // } // Path: test/src/lombok/ast/grammar/AlternativeStringConcatEcjTreeBuilderTest.java import org.junit.Test; import org.junit.runner.RunWith; import static java.util.Collections.singleton; import java.io.File; import java.util.Collection; import java.util.regex.Pattern; import lombok.ast.grammar.RunForEachFileInDirRunner.DirDescriptor; import org.eclipse.jdt.internal.compiler.impl.CompilerOptions; /* * Copyright (C) 2010 The Project Lombok Authors. * * 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 lombok.ast.grammar; @RunWith(RunForEachFileInDirRunner.class) public class AlternativeStringConcatEcjTreeBuilderTest extends EcjTreeBuilderTest {
@Override protected Collection<DirDescriptor> getDirDescriptors() {
rzwitserloot/lombok.ast
test/src/lombok/ast/TemplateTest.java
// Path: src/printer/lombok/ast/printer/StructureFormatter.java // public class StructureFormatter implements SourceFormatter { // private static final String INDENT = " "; // private final StringBuilder sb = new StringBuilder(); // private final List<String> errors = Lists.newArrayList(); // private int indent; // private final Map<Node, Collection<StructuralElement>> sourceStructures; // private String name, currentType; // private final String nodeFormatString; // private Set<String> propertySkipList = Sets.newHashSet(); // // public static StructureFormatter formatterWithoutPositions() { // return new StructureFormatter(Collections.<Node, Collection<StructuralElement>>emptyMap(), false); // } // // public static StructureFormatter formatterWithPositions() { // return new StructureFormatter(Collections.<Node, Collection<StructuralElement>>emptyMap(), true); // } // // public static StructureFormatter formatterWithEverything(Map<Node, Collection<StructuralElement>> sourceStructures) { // return new StructureFormatter(sourceStructures, true); // } // // private StructureFormatter(Map<Node, Collection<StructuralElement>> sourceStructures, boolean printPositions) { // this.sourceStructures = sourceStructures; // this.nodeFormatString = printPositions ? "[%s %s%s (%d-%d)]\n" : "[%s %s%s]\n"; // } // // private void a(String in, Object... args) { // for (int i = 0; i < indent; i++) sb.append(INDENT); // if (name != null) { // sb.append(name).append(": "); // name = null; // } // if (args.length == 0) sb.append(in); // else sb.append(String.format(in, args)); // } // // @Override public void buildInline(Node node) { // buildNode("I", node); // } // // @Override public void buildBlock(Node node) { // buildNode("B", node); // } // // private void buildNode(String type, Node node) { // if (node == null) { // indent++; // return; // } // String name = node.getClass().getSimpleName(); // currentType = name; // String description = ""; // if (node instanceof DescribedNode) description = " " + ((DescribedNode)node).getDescription(); // a(nodeFormatString, type, name, description, node.getPosition().getStart(), node.getPosition().getEnd()); // indent++; // if (sourceStructures.containsKey(node)) { // for (StructuralElement struct : sourceStructures.get(node)) { // a("STRUCT: %s (%d-%d)\n", struct.getContent(), struct.getPosition().getStart(), struct.getPosition().getEnd()); // } // } // } // // @Override public void fail(String fail) { // a("FAIL: " + fail); // } // // @Override public void property(String name, Object value) { // if (!propertySkipList.contains(currentType + "/" + name)) a("PROPERTY: %s = %s\n", name, value); // } // // public StructureFormatter skipProperty(Class<? extends Node> type, String propertyName) { // propertySkipList.add(type.getSimpleName() + "/" + propertyName); // return this; // } // // @Override public void keyword(String text) { // } // // @Override public void operator(String text) { // } // // @Override public void verticalSpace() { // } // // @Override public void space() { // } // // @Override public void append(String text) { // } // // @Override public void startSuppressBlock() { // } // // @Override public void endSuppressBlock() { // } // // @Override public void startSuppressIndent() { // } // // @Override public void endSuppressIndent() { // } // // @Override public void closeInline() { // indent--; // } // // @Override public void closeBlock() { // indent--; // } // // @Override public void addError(int errorStart, int errorEnd, String errorMessage) { // errors.add(String.format("%d-%d: %s", errorStart, errorEnd, errorMessage)); // } // // @Override public String finish() { // if (!errors.isEmpty()) { // indent = 0; // a("\n\n\nERRORS: \n"); // a(Joiner.on('\n').join(errors)); // errors.clear(); // } // return sb.toString(); // } // // @Override public void setTimeTaken(long taken) { // } // // @Override public void nameNextElement(String name) { // this.name = name; // } // }
import static org.junit.Assert.*; import java.util.Arrays; import lombok.ast.grammar.Template; import lombok.ast.printer.SourcePrinter; import lombok.ast.printer.StructureFormatter; import org.junit.Test;
package lombok.ast; public class TemplateTest { private static String literal(String... args) { StringBuilder sb = new StringBuilder(); for (String arg : args) sb.append(arg).append("\n"); return sb.toString(); } @Test public void testIdentifier() { MethodDeclaration method = Template.parseMethod("public static int testing(int foo) { return 5; }"); Template<MethodDeclaration> template = Template.of(method); template.setStartPosition(10); template.replaceIdentifier("testing", "floobargle", new Position(50, 60)); template.replaceIdentifier("foo", "bar", new Position(80, 90)); MethodDeclaration finish = template.finish();
// Path: src/printer/lombok/ast/printer/StructureFormatter.java // public class StructureFormatter implements SourceFormatter { // private static final String INDENT = " "; // private final StringBuilder sb = new StringBuilder(); // private final List<String> errors = Lists.newArrayList(); // private int indent; // private final Map<Node, Collection<StructuralElement>> sourceStructures; // private String name, currentType; // private final String nodeFormatString; // private Set<String> propertySkipList = Sets.newHashSet(); // // public static StructureFormatter formatterWithoutPositions() { // return new StructureFormatter(Collections.<Node, Collection<StructuralElement>>emptyMap(), false); // } // // public static StructureFormatter formatterWithPositions() { // return new StructureFormatter(Collections.<Node, Collection<StructuralElement>>emptyMap(), true); // } // // public static StructureFormatter formatterWithEverything(Map<Node, Collection<StructuralElement>> sourceStructures) { // return new StructureFormatter(sourceStructures, true); // } // // private StructureFormatter(Map<Node, Collection<StructuralElement>> sourceStructures, boolean printPositions) { // this.sourceStructures = sourceStructures; // this.nodeFormatString = printPositions ? "[%s %s%s (%d-%d)]\n" : "[%s %s%s]\n"; // } // // private void a(String in, Object... args) { // for (int i = 0; i < indent; i++) sb.append(INDENT); // if (name != null) { // sb.append(name).append(": "); // name = null; // } // if (args.length == 0) sb.append(in); // else sb.append(String.format(in, args)); // } // // @Override public void buildInline(Node node) { // buildNode("I", node); // } // // @Override public void buildBlock(Node node) { // buildNode("B", node); // } // // private void buildNode(String type, Node node) { // if (node == null) { // indent++; // return; // } // String name = node.getClass().getSimpleName(); // currentType = name; // String description = ""; // if (node instanceof DescribedNode) description = " " + ((DescribedNode)node).getDescription(); // a(nodeFormatString, type, name, description, node.getPosition().getStart(), node.getPosition().getEnd()); // indent++; // if (sourceStructures.containsKey(node)) { // for (StructuralElement struct : sourceStructures.get(node)) { // a("STRUCT: %s (%d-%d)\n", struct.getContent(), struct.getPosition().getStart(), struct.getPosition().getEnd()); // } // } // } // // @Override public void fail(String fail) { // a("FAIL: " + fail); // } // // @Override public void property(String name, Object value) { // if (!propertySkipList.contains(currentType + "/" + name)) a("PROPERTY: %s = %s\n", name, value); // } // // public StructureFormatter skipProperty(Class<? extends Node> type, String propertyName) { // propertySkipList.add(type.getSimpleName() + "/" + propertyName); // return this; // } // // @Override public void keyword(String text) { // } // // @Override public void operator(String text) { // } // // @Override public void verticalSpace() { // } // // @Override public void space() { // } // // @Override public void append(String text) { // } // // @Override public void startSuppressBlock() { // } // // @Override public void endSuppressBlock() { // } // // @Override public void startSuppressIndent() { // } // // @Override public void endSuppressIndent() { // } // // @Override public void closeInline() { // indent--; // } // // @Override public void closeBlock() { // indent--; // } // // @Override public void addError(int errorStart, int errorEnd, String errorMessage) { // errors.add(String.format("%d-%d: %s", errorStart, errorEnd, errorMessage)); // } // // @Override public String finish() { // if (!errors.isEmpty()) { // indent = 0; // a("\n\n\nERRORS: \n"); // a(Joiner.on('\n').join(errors)); // errors.clear(); // } // return sb.toString(); // } // // @Override public void setTimeTaken(long taken) { // } // // @Override public void nameNextElement(String name) { // this.name = name; // } // } // Path: test/src/lombok/ast/TemplateTest.java import static org.junit.Assert.*; import java.util.Arrays; import lombok.ast.grammar.Template; import lombok.ast.printer.SourcePrinter; import lombok.ast.printer.StructureFormatter; import org.junit.Test; package lombok.ast; public class TemplateTest { private static String literal(String... args) { StringBuilder sb = new StringBuilder(); for (String arg : args) sb.append(arg).append("\n"); return sb.toString(); } @Test public void testIdentifier() { MethodDeclaration method = Template.parseMethod("public static int testing(int foo) { return 5; }"); Template<MethodDeclaration> template = Template.of(method); template.setStartPosition(10); template.replaceIdentifier("testing", "floobargle", new Position(50, 60)); template.replaceIdentifier("foo", "bar", new Position(80, 90)); MethodDeclaration finish = template.finish();
StructureFormatter sf = StructureFormatter.formatterWithPositions();
rzwitserloot/lombok.ast
src/ast/lombok/ast/resolve/Resolver.java
// Path: src/ast/lombok/ast/RawListAccessor.java // public interface RawListAccessor<T extends Node, P extends Node> extends Iterable<Node> { // P up(); // Node owner(); // void clear(); // boolean isEmpty(); // int size(); // Node first(); // Node last(); // boolean contains(Node source); // P migrateAllFrom(RawListAccessor<?, ?> otherList); // P addToStart(Node node); // P addToEnd(Node node); // P addBefore(Node ref, Node node); // P addAfter(Node ref, Node node); // boolean replace(Node source, Node replacement); // boolean remove(Node source); // StrictListAccessor<T, P> asStrictAccessor(); // }
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import lombok.ast.Annotation; import lombok.ast.Block; import lombok.ast.CompilationUnit; import lombok.ast.Expression; import lombok.ast.Identifier; import lombok.ast.ImportDeclaration; import lombok.ast.Node; import lombok.ast.NullLiteral; import lombok.ast.PackageDeclaration; import lombok.ast.RawListAccessor; import lombok.ast.ResolutionException; import lombok.ast.Select; import lombok.ast.TypeBody; import lombok.ast.TypeDeclaration; import lombok.ast.TypeReference; import lombok.ast.VariableReference;
String wantedPkg = dot == -1 ? "" : wanted.substring(0, dot); String wantedName = dot == -1 ? wanted : wanted.substring(dot + 1); // If type ref appears fully qualified and it hasn't matched by now, we're done. if (name.indexOf('.') > -1) return false; // 'Baz' will never be a match for foo.bar.NotBaz. if (!wantedName.equals(name)) return false; ImportList imports = getImportList(typeReference); /* If matching List to java.util.List and java.awt.List is explicitly imported, no match. */ { String ending = "." + wantedName; for (String explicit : imports.explicits) { if (explicit.endsWith(ending) && !explicit.equals(wanted)) return false; } } potentialMatchFound: /* To match List to java.util.List either there has to be a java.util.* or java.util.List import. */ { if (wantedPkg.length() > 0 && imports.stars.contains(wantedPkg)) break potentialMatchFound; if (imports.explicits.contains(wanted)) break potentialMatchFound; return false; } //name is definitely a simple name, and it might match. Walk up type tree and if it doesn't match any of those, delve into import statements. Node n = typeReference.getParent(); Node prevN = null; CompilationUnit cu = null; while (n != null) {
// Path: src/ast/lombok/ast/RawListAccessor.java // public interface RawListAccessor<T extends Node, P extends Node> extends Iterable<Node> { // P up(); // Node owner(); // void clear(); // boolean isEmpty(); // int size(); // Node first(); // Node last(); // boolean contains(Node source); // P migrateAllFrom(RawListAccessor<?, ?> otherList); // P addToStart(Node node); // P addToEnd(Node node); // P addBefore(Node ref, Node node); // P addAfter(Node ref, Node node); // boolean replace(Node source, Node replacement); // boolean remove(Node source); // StrictListAccessor<T, P> asStrictAccessor(); // } // Path: src/ast/lombok/ast/resolve/Resolver.java import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import lombok.ast.Annotation; import lombok.ast.Block; import lombok.ast.CompilationUnit; import lombok.ast.Expression; import lombok.ast.Identifier; import lombok.ast.ImportDeclaration; import lombok.ast.Node; import lombok.ast.NullLiteral; import lombok.ast.PackageDeclaration; import lombok.ast.RawListAccessor; import lombok.ast.ResolutionException; import lombok.ast.Select; import lombok.ast.TypeBody; import lombok.ast.TypeDeclaration; import lombok.ast.TypeReference; import lombok.ast.VariableReference; String wantedPkg = dot == -1 ? "" : wanted.substring(0, dot); String wantedName = dot == -1 ? wanted : wanted.substring(dot + 1); // If type ref appears fully qualified and it hasn't matched by now, we're done. if (name.indexOf('.') > -1) return false; // 'Baz' will never be a match for foo.bar.NotBaz. if (!wantedName.equals(name)) return false; ImportList imports = getImportList(typeReference); /* If matching List to java.util.List and java.awt.List is explicitly imported, no match. */ { String ending = "." + wantedName; for (String explicit : imports.explicits) { if (explicit.endsWith(ending) && !explicit.equals(wanted)) return false; } } potentialMatchFound: /* To match List to java.util.List either there has to be a java.util.* or java.util.List import. */ { if (wantedPkg.length() > 0 && imports.stars.contains(wantedPkg)) break potentialMatchFound; if (imports.explicits.contains(wanted)) break potentialMatchFound; return false; } //name is definitely a simple name, and it might match. Walk up type tree and if it doesn't match any of those, delve into import statements. Node n = typeReference.getParent(); Node prevN = null; CompilationUnit cu = null; while (n != null) {
RawListAccessor<?, ?> list;
rzwitserloot/lombok.ast
src/main/lombok/ast/grammar/Source.java
// Path: src/ast/lombok/ast/StructuralElement.java // public interface StructuralElement { // // Position getPosition(); // // String getContent(); // }
import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.TreeMap; import lombok.Getter; import lombok.ast.Comment; import lombok.ast.Expression; import lombok.ast.ForwardingAstVisitor; import lombok.ast.JavadocContainer; import lombok.ast.Node; import lombok.ast.Position; import lombok.ast.StructuralElement; import org.parboiled.Context; import org.parboiled.RecoveringParseRunner; import org.parboiled.errors.ParseError; import org.parboiled.support.ParsingResult; import com.google.common.collect.ImmutableList; import com.google.common.collect.LinkedListMultimap; import com.google.common.collect.ListMultimap; import com.google.common.collect.Lists; import com.google.common.collect.MapMaker; import com.google.common.collect.Maps;
/* * Copyright (C) 2010-2015 The Project Lombok Authors. * * 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 lombok.ast.grammar; public class Source { @Getter private final String name; @Getter private final String rawInput; private List<Node> nodes; private List<ParseProblem> problems; private List<Comment> comments; private boolean parsed; private ParsingResult<Node> parsingResult; private TreeMap<Integer, Integer> positionDeltas; private Map<org.parboiled.Node<Node>, Node> registeredStructures; private Map<org.parboiled.Node<Node>, List<Comment>> registeredComments; private String preprocessed;
// Path: src/ast/lombok/ast/StructuralElement.java // public interface StructuralElement { // // Position getPosition(); // // String getContent(); // } // Path: src/main/lombok/ast/grammar/Source.java import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.TreeMap; import lombok.Getter; import lombok.ast.Comment; import lombok.ast.Expression; import lombok.ast.ForwardingAstVisitor; import lombok.ast.JavadocContainer; import lombok.ast.Node; import lombok.ast.Position; import lombok.ast.StructuralElement; import org.parboiled.Context; import org.parboiled.RecoveringParseRunner; import org.parboiled.errors.ParseError; import org.parboiled.support.ParsingResult; import com.google.common.collect.ImmutableList; import com.google.common.collect.LinkedListMultimap; import com.google.common.collect.ListMultimap; import com.google.common.collect.Lists; import com.google.common.collect.MapMaker; import com.google.common.collect.Maps; /* * Copyright (C) 2010-2015 The Project Lombok Authors. * * 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 lombok.ast.grammar; public class Source { @Getter private final String name; @Getter private final String rawInput; private List<Node> nodes; private List<ParseProblem> problems; private List<Comment> comments; private boolean parsed; private ParsingResult<Node> parsingResult; private TreeMap<Integer, Integer> positionDeltas; private Map<org.parboiled.Node<Node>, Node> registeredStructures; private Map<org.parboiled.Node<Node>, List<Comment>> registeredComments; private String preprocessed;
private Map<Node, Collection<StructuralElement>> cachedSourceStructures;
rzwitserloot/lombok.ast
test/src/lombok/ast/grammar/AlternativeStringConcatEcjTreeConverterType2Test.java
// Path: test/src/lombok/ast/grammar/RunForEachFileInDirRunner.java // @Data // public static final class DirDescriptor implements Comparable<DirDescriptor> { // private final File directory; // private final Pattern inclusionPattern; // private final Pattern exclusionPattern; // private final File mirrorDirectory; // private final boolean recurse; // // public static DirDescriptor of(File directory, boolean recurse) { // return new DirDescriptor(directory, Pattern.compile("^.*\\.java$"), null, null, recurse); // } // // public DirDescriptor withExclusion(Pattern pattern) { // return new DirDescriptor(directory, inclusionPattern, pattern, mirrorDirectory, recurse); // } // // public DirDescriptor withInclusion(Pattern pattern) { // return new DirDescriptor(directory, pattern, exclusionPattern, mirrorDirectory, recurse); // } // // public DirDescriptor withMirror(File mirror) { // return new DirDescriptor(directory, inclusionPattern, exclusionPattern, mirror, recurse); // } // // @Override // public int compareTo(DirDescriptor other) { // int result = directory.getAbsolutePath().compareTo(other.directory.getAbsolutePath()); // if (result != 0) return result; // if (mirrorDirectory != null && other.mirrorDirectory == null) return +1; // if (mirrorDirectory == null && other.mirrorDirectory != null) return -1; // if (mirrorDirectory != null) result = mirrorDirectory.getAbsolutePath().compareTo(other.mirrorDirectory.getAbsolutePath()); // if (result != 0) return result; // if (recurse && !other.recurse) return +1; // if (!recurse && other.recurse) return -1; // if (inclusionPattern != null && other.inclusionPattern == null) return +1; // if (inclusionPattern == null && other.inclusionPattern != null) return -1; // if (inclusionPattern != null) result = inclusionPattern.pattern().compareTo(other.inclusionPattern.pattern()); // if (result != 0) return result; // if (exclusionPattern != null && other.exclusionPattern == null) return +1; // if (exclusionPattern == null && other.exclusionPattern != null) return -1; // if (exclusionPattern != null) result = exclusionPattern.pattern().compareTo(other.exclusionPattern.pattern()); // return result; // } // }
import java.io.File; import java.util.Arrays; import java.util.Collection; import java.util.regex.Pattern; import lombok.ast.grammar.RunForEachFileInDirRunner.DirDescriptor; import org.eclipse.jdt.internal.compiler.impl.CompilerOptions; import org.junit.Test;
/* * Copyright (C) 2010 The Project Lombok Authors. * * 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 lombok.ast.grammar; public class AlternativeStringConcatEcjTreeConverterType2Test extends EcjTreeConverterType2Test { @Test public void testEcjTreeConverter(Source source) throws Exception { testCompiler(source); }
// Path: test/src/lombok/ast/grammar/RunForEachFileInDirRunner.java // @Data // public static final class DirDescriptor implements Comparable<DirDescriptor> { // private final File directory; // private final Pattern inclusionPattern; // private final Pattern exclusionPattern; // private final File mirrorDirectory; // private final boolean recurse; // // public static DirDescriptor of(File directory, boolean recurse) { // return new DirDescriptor(directory, Pattern.compile("^.*\\.java$"), null, null, recurse); // } // // public DirDescriptor withExclusion(Pattern pattern) { // return new DirDescriptor(directory, inclusionPattern, pattern, mirrorDirectory, recurse); // } // // public DirDescriptor withInclusion(Pattern pattern) { // return new DirDescriptor(directory, pattern, exclusionPattern, mirrorDirectory, recurse); // } // // public DirDescriptor withMirror(File mirror) { // return new DirDescriptor(directory, inclusionPattern, exclusionPattern, mirror, recurse); // } // // @Override // public int compareTo(DirDescriptor other) { // int result = directory.getAbsolutePath().compareTo(other.directory.getAbsolutePath()); // if (result != 0) return result; // if (mirrorDirectory != null && other.mirrorDirectory == null) return +1; // if (mirrorDirectory == null && other.mirrorDirectory != null) return -1; // if (mirrorDirectory != null) result = mirrorDirectory.getAbsolutePath().compareTo(other.mirrorDirectory.getAbsolutePath()); // if (result != 0) return result; // if (recurse && !other.recurse) return +1; // if (!recurse && other.recurse) return -1; // if (inclusionPattern != null && other.inclusionPattern == null) return +1; // if (inclusionPattern == null && other.inclusionPattern != null) return -1; // if (inclusionPattern != null) result = inclusionPattern.pattern().compareTo(other.inclusionPattern.pattern()); // if (result != 0) return result; // if (exclusionPattern != null && other.exclusionPattern == null) return +1; // if (exclusionPattern == null && other.exclusionPattern != null) return -1; // if (exclusionPattern != null) result = exclusionPattern.pattern().compareTo(other.exclusionPattern.pattern()); // return result; // } // } // Path: test/src/lombok/ast/grammar/AlternativeStringConcatEcjTreeConverterType2Test.java import java.io.File; import java.util.Arrays; import java.util.Collection; import java.util.regex.Pattern; import lombok.ast.grammar.RunForEachFileInDirRunner.DirDescriptor; import org.eclipse.jdt.internal.compiler.impl.CompilerOptions; import org.junit.Test; /* * Copyright (C) 2010 The Project Lombok Authors. * * 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 lombok.ast.grammar; public class AlternativeStringConcatEcjTreeConverterType2Test extends EcjTreeConverterType2Test { @Test public void testEcjTreeConverter(Source source) throws Exception { testCompiler(source); }
@Override protected Collection<DirDescriptor> getDirDescriptors() {
groupon/robo-remote
UIAutomatorClient/src/main/com/groupon/roboremote/uiautomatorclient/components/UiObject.java
// Path: UIAutomatorClient/src/main/com/groupon/roboremote/uiautomatorclient/QueryBuilder.java // public class QueryBuilder extends com.groupon.roboremote.roboremoteclientcommon.QueryBuilder { // // Returns a QueryBuilder on the UIAutomator port // public QueryBuilder() { // super(PortSingleton.getInstance().getPort()); // } // }
import com.groupon.roboremote.uiautomatorclient.QueryBuilder; import org.json.JSONArray; import java.util.UUID;
/* Copyright (c) 2012, 2013, 2014, Groupon, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of GROUPON nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.groupon.roboremote.uiautomatorclient.components; public class UiObject extends BaseObject { public UiObject(String storedId) { super(storedId); } public UiObject(UiSelector selector) throws Exception { storedId = UUID.randomUUID().toString();
// Path: UIAutomatorClient/src/main/com/groupon/roboremote/uiautomatorclient/QueryBuilder.java // public class QueryBuilder extends com.groupon.roboremote.roboremoteclientcommon.QueryBuilder { // // Returns a QueryBuilder on the UIAutomator port // public QueryBuilder() { // super(PortSingleton.getInstance().getPort()); // } // } // Path: UIAutomatorClient/src/main/com/groupon/roboremote/uiautomatorclient/components/UiObject.java import com.groupon.roboremote.uiautomatorclient.QueryBuilder; import org.json.JSONArray; import java.util.UUID; /* Copyright (c) 2012, 2013, 2014, Groupon, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of GROUPON nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.groupon.roboremote.uiautomatorclient.components; public class UiObject extends BaseObject { public UiObject(String storedId) { super(storedId); } public UiObject(UiSelector selector) throws Exception { storedId = UUID.randomUUID().toString();
new QueryBuilder().instantiate("com.android.uiautomator.core.UiObject", QueryBuilder.getStoredValue(selector.getStoredId())).storeResult(storedId).execute();
groupon/robo-remote
UIAutomatorClient/src/main/com/groupon/roboremote/uiautomatorclient/components/UiCollection.java
// Path: UIAutomatorClient/src/main/com/groupon/roboremote/uiautomatorclient/QueryBuilder.java // public class QueryBuilder extends com.groupon.roboremote.roboremoteclientcommon.QueryBuilder { // // Returns a QueryBuilder on the UIAutomator port // public QueryBuilder() { // super(PortSingleton.getInstance().getPort()); // } // }
import com.groupon.roboremote.uiautomatorclient.QueryBuilder; import org.json.JSONArray; import java.util.UUID;
/* Copyright (c) 2012, 2013, 2014, Groupon, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of GROUPON nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.groupon.roboremote.uiautomatorclient.components; public class UiCollection extends BaseObject { public UiCollection(UiSelector selector) throws Exception { storedId = UUID.randomUUID().toString();
// Path: UIAutomatorClient/src/main/com/groupon/roboremote/uiautomatorclient/QueryBuilder.java // public class QueryBuilder extends com.groupon.roboremote.roboremoteclientcommon.QueryBuilder { // // Returns a QueryBuilder on the UIAutomator port // public QueryBuilder() { // super(PortSingleton.getInstance().getPort()); // } // } // Path: UIAutomatorClient/src/main/com/groupon/roboremote/uiautomatorclient/components/UiCollection.java import com.groupon.roboremote.uiautomatorclient.QueryBuilder; import org.json.JSONArray; import java.util.UUID; /* Copyright (c) 2012, 2013, 2014, Groupon, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of GROUPON nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.groupon.roboremote.uiautomatorclient.components; public class UiCollection extends BaseObject { public UiCollection(UiSelector selector) throws Exception { storedId = UUID.randomUUID().toString();
new QueryBuilder().instantiate("com.android.uiautomator.core.UiCollection", QueryBuilder.getStoredValue(selector.getStoredId())).storeResult(storedId).execute();
groupon/robo-remote
UIAutomatorClient/src/main/com/groupon/roboremote/uiautomatorclient/components/UiDevice.java
// Path: UIAutomatorClient/src/main/com/groupon/roboremote/uiautomatorclient/Client.java // public class Client extends com.groupon.roboremote.roboremoteclientcommon.Client { // private static Client instance = null; // // /** // * Gets a client instance on the uiautomator port // * @return // */ // public static Client getInstance() { // if(instance == null) { // instance = new Client(); // } // // instance.API_PORT = PortSingleton.getInstance().getPort(); // return instance; // } // } // // Path: UIAutomatorClient/src/main/com/groupon/roboremote/uiautomatorclient/Constants.java // public class Constants { // // robotium constants // public static final String UIAUTOMATOR_UIDEVICE = "getUiDevice"; // }
import com.groupon.roboremote.uiautomatorclient.Client; import com.groupon.roboremote.uiautomatorclient.Constants;
/* Copyright (c) 2012, 2013, 2014, Groupon, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of GROUPON nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.groupon.roboremote.uiautomatorclient.components; public class UiDevice { /** * Open notification shade * @return * @throws Exception */ public static boolean openNotification() throws Exception { boolean success = false; // get API level
// Path: UIAutomatorClient/src/main/com/groupon/roboremote/uiautomatorclient/Client.java // public class Client extends com.groupon.roboremote.roboremoteclientcommon.Client { // private static Client instance = null; // // /** // * Gets a client instance on the uiautomator port // * @return // */ // public static Client getInstance() { // if(instance == null) { // instance = new Client(); // } // // instance.API_PORT = PortSingleton.getInstance().getPort(); // return instance; // } // } // // Path: UIAutomatorClient/src/main/com/groupon/roboremote/uiautomatorclient/Constants.java // public class Constants { // // robotium constants // public static final String UIAUTOMATOR_UIDEVICE = "getUiDevice"; // } // Path: UIAutomatorClient/src/main/com/groupon/roboremote/uiautomatorclient/components/UiDevice.java import com.groupon.roboremote.uiautomatorclient.Client; import com.groupon.roboremote.uiautomatorclient.Constants; /* Copyright (c) 2012, 2013, 2014, Groupon, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of GROUPON nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.groupon.roboremote.uiautomatorclient.components; public class UiDevice { /** * Open notification shade * @return * @throws Exception */ public static boolean openNotification() throws Exception { boolean success = false; // get API level
int apiLevel = Client.getInstance().mapField("android.os.Build$VERSION", "SDK_INT").getInt(0);
groupon/robo-remote
UIAutomatorClient/src/main/com/groupon/roboremote/uiautomatorclient/components/UiDevice.java
// Path: UIAutomatorClient/src/main/com/groupon/roboremote/uiautomatorclient/Client.java // public class Client extends com.groupon.roboremote.roboremoteclientcommon.Client { // private static Client instance = null; // // /** // * Gets a client instance on the uiautomator port // * @return // */ // public static Client getInstance() { // if(instance == null) { // instance = new Client(); // } // // instance.API_PORT = PortSingleton.getInstance().getPort(); // return instance; // } // } // // Path: UIAutomatorClient/src/main/com/groupon/roboremote/uiautomatorclient/Constants.java // public class Constants { // // robotium constants // public static final String UIAUTOMATOR_UIDEVICE = "getUiDevice"; // }
import com.groupon.roboremote.uiautomatorclient.Client; import com.groupon.roboremote.uiautomatorclient.Constants;
/* Copyright (c) 2012, 2013, 2014, Groupon, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of GROUPON nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.groupon.roboremote.uiautomatorclient.components; public class UiDevice { /** * Open notification shade * @return * @throws Exception */ public static boolean openNotification() throws Exception { boolean success = false; // get API level int apiLevel = Client.getInstance().mapField("android.os.Build$VERSION", "SDK_INT").getInt(0); if (apiLevel >= 18) {
// Path: UIAutomatorClient/src/main/com/groupon/roboremote/uiautomatorclient/Client.java // public class Client extends com.groupon.roboremote.roboremoteclientcommon.Client { // private static Client instance = null; // // /** // * Gets a client instance on the uiautomator port // * @return // */ // public static Client getInstance() { // if(instance == null) { // instance = new Client(); // } // // instance.API_PORT = PortSingleton.getInstance().getPort(); // return instance; // } // } // // Path: UIAutomatorClient/src/main/com/groupon/roboremote/uiautomatorclient/Constants.java // public class Constants { // // robotium constants // public static final String UIAUTOMATOR_UIDEVICE = "getUiDevice"; // } // Path: UIAutomatorClient/src/main/com/groupon/roboremote/uiautomatorclient/components/UiDevice.java import com.groupon.roboremote.uiautomatorclient.Client; import com.groupon.roboremote.uiautomatorclient.Constants; /* Copyright (c) 2012, 2013, 2014, Groupon, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of GROUPON nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.groupon.roboremote.uiautomatorclient.components; public class UiDevice { /** * Open notification shade * @return * @throws Exception */ public static boolean openNotification() throws Exception { boolean success = false; // get API level int apiLevel = Client.getInstance().mapField("android.os.Build$VERSION", "SDK_INT").getInt(0); if (apiLevel >= 18) {
success = Client.getInstance().map(Constants.UIAUTOMATOR_UIDEVICE, "openNotification").getBoolean(0);
groupon/robo-remote
RoboRemoteClient/src/main/com/groupon/roboremote/roboremoteclient/components/Screen.java
// Path: RoboRemoteClient/src/main/com/groupon/roboremote/roboremoteclient/QueryBuilder.java // public class QueryBuilder extends com.groupon.roboremote.roboremoteclientcommon.QueryBuilder { // public QueryBuilder() { // super(PortSingleton.getInstance().getPort()); // } // }
import com.groupon.roboremote.roboremoteclient.QueryBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/* Copyright (c) 2012, 2013, 2014, Groupon, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of GROUPON nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.groupon.roboremote.roboremoteclient.components; public class Screen { private static final Logger logger = LoggerFactory.getLogger("test"); public static int getScreenWidth() throws Exception {
// Path: RoboRemoteClient/src/main/com/groupon/roboremote/roboremoteclient/QueryBuilder.java // public class QueryBuilder extends com.groupon.roboremote.roboremoteclientcommon.QueryBuilder { // public QueryBuilder() { // super(PortSingleton.getInstance().getPort()); // } // } // Path: RoboRemoteClient/src/main/com/groupon/roboremote/roboremoteclient/components/Screen.java import com.groupon.roboremote.roboremoteclient.QueryBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* Copyright (c) 2012, 2013, 2014, Groupon, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of GROUPON nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.groupon.roboremote.roboremoteclient.components; public class Screen { private static final Logger logger = LoggerFactory.getLogger("test"); public static int getScreenWidth() throws Exception {
return new QueryBuilder().map("solo", "getCurrentActivity").call("getWindow").call("getDecorView").call("getRootView").call("getWidth").execute().getInt(0);
groupon/robo-remote
UIAutomatorClient/src/main/com/groupon/roboremote/uiautomatorclient/components/UiSelector.java
// Path: UIAutomatorClient/src/main/com/groupon/roboremote/uiautomatorclient/QueryBuilder.java // public class QueryBuilder extends com.groupon.roboremote.roboremoteclientcommon.QueryBuilder { // // Returns a QueryBuilder on the UIAutomator port // public QueryBuilder() { // super(PortSingleton.getInstance().getPort()); // } // }
import com.groupon.roboremote.uiautomatorclient.QueryBuilder; import java.util.UUID;
/* Copyright (c) 2012, 2013, 2014, Groupon, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of GROUPON nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.groupon.roboremote.uiautomatorclient.components; public class UiSelector extends BaseObject { public UiSelector() throws Exception { storedId = UUID.randomUUID().toString();
// Path: UIAutomatorClient/src/main/com/groupon/roboremote/uiautomatorclient/QueryBuilder.java // public class QueryBuilder extends com.groupon.roboremote.roboremoteclientcommon.QueryBuilder { // // Returns a QueryBuilder on the UIAutomator port // public QueryBuilder() { // super(PortSingleton.getInstance().getPort()); // } // } // Path: UIAutomatorClient/src/main/com/groupon/roboremote/uiautomatorclient/components/UiSelector.java import com.groupon.roboremote.uiautomatorclient.QueryBuilder; import java.util.UUID; /* Copyright (c) 2012, 2013, 2014, Groupon, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of GROUPON nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.groupon.roboremote.uiautomatorclient.components; public class UiSelector extends BaseObject { public UiSelector() throws Exception { storedId = UUID.randomUUID().toString();
new QueryBuilder().instantiate("com.android.uiautomator.core.UiSelector").storeResult(storedId).execute();
groupon/robo-remote
RoboRemoteClientCommon/src/main/com/groupon/roboremote/roboremoteclientcommon/Client.java
// Path: RoboRemoteClientCommon/src/main/com/groupon/roboremote/roboremoteclientcommon/http/Get.java // public class Get { // public Get() { // // } // // public static String get(String baseurl, String verb, String params) throws Exception { // String response = ""; // // URL oracle = new URL(baseurl + "/" + verb + "?" + params); // URLConnection yc = oracle.openConnection(); // BufferedReader in = new BufferedReader(new InputStreamReader( // yc.getInputStream())); // String inputLine; // while ((inputLine = in.readLine()) != null) { // response += inputLine; // } // in.close(); // // return response; // } // }
import com.groupon.roboremote.roboremoteclientcommon.http.Get; import org.json.JSONArray; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.Exception; import java.lang.Object; import java.lang.String; import java.net.URLEncoder; import java.util.Date;
/* Copyright (c) 2012, 2013, 2014, Groupon, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of GROUPON nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.groupon.roboremote.roboremoteclientcommon; public class Client { private static final Logger logger = LoggerFactory.getLogger("test"); private static String API_BASE_URL = "http://localhost"; protected int API_PORT = com.groupon.roboremote.Constants.ROBOREMOTE_SERVER_PORT; private static Client instance = null; protected Client() { // Exists only to defeat instantiation. } protected static Client getInstance() { return instance; } protected static Client getInstance(int port) { if(instance == null) { instance = new Client(); } // TODO: This is not safe instance.API_PORT = port; return instance; } /** * Returns true if there is RoboRemoteServer currently listening * @return * @throws Exception */ public boolean isListening() throws Exception { try {
// Path: RoboRemoteClientCommon/src/main/com/groupon/roboremote/roboremoteclientcommon/http/Get.java // public class Get { // public Get() { // // } // // public static String get(String baseurl, String verb, String params) throws Exception { // String response = ""; // // URL oracle = new URL(baseurl + "/" + verb + "?" + params); // URLConnection yc = oracle.openConnection(); // BufferedReader in = new BufferedReader(new InputStreamReader( // yc.getInputStream())); // String inputLine; // while ((inputLine = in.readLine()) != null) { // response += inputLine; // } // in.close(); // // return response; // } // } // Path: RoboRemoteClientCommon/src/main/com/groupon/roboremote/roboremoteclientcommon/Client.java import com.groupon.roboremote.roboremoteclientcommon.http.Get; import org.json.JSONArray; import org.json.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.Exception; import java.lang.Object; import java.lang.String; import java.net.URLEncoder; import java.util.Date; /* Copyright (c) 2012, 2013, 2014, Groupon, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of GROUPON nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.groupon.roboremote.roboremoteclientcommon; public class Client { private static final Logger logger = LoggerFactory.getLogger("test"); private static String API_BASE_URL = "http://localhost"; protected int API_PORT = com.groupon.roboremote.Constants.ROBOREMOTE_SERVER_PORT; private static Client instance = null; protected Client() { // Exists only to defeat instantiation. } protected static Client getInstance() { return instance; } protected static Client getInstance(int port) { if(instance == null) { instance = new Client(); } // TODO: This is not safe instance.API_PORT = port; return instance; } /** * Returns true if there is RoboRemoteServer currently listening * @return * @throws Exception */ public boolean isListening() throws Exception { try {
JSONObject resp = new JSONObject(Get.get(API_BASE_URL + ":" + API_PORT, Constants.REQUEST_HEARTBEAT, ""));
groupon/robo-remote
RoboRemoteClientCommon/src/main/com/groupon/roboremote/roboremoteclientcommon/Device.java
// Path: RoboRemoteClientCommon/src/main/com/groupon/roboremote/roboremoteclientcommon/logging/TestLogger.java // public class TestLogger { // private static final String LoggerName = "test"; // protected static final Logger logger = LoggerFactory.getLogger(LoggerName); // // public static Logger get() // { // return logger; // } // }
import com.google.common.io.Files; import com.groupon.roboremote.roboremoteclientcommon.logging.TestLogger; import java.io.*;
/* Copyright (c) 2012, 2013, 2014, Groupon, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of GROUPON nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.groupon.roboremote.roboremoteclientcommon; /** * This class defines general device/emulator commands */ public class Device { static boolean emulator = false; static String current_log_dir = null; public static boolean isEmulator() throws Exception { return DebugBridge.get().isEmulator(); } public static void clearAppData(String packageName) throws Exception { // clear app data DebugBridge.get().runShellCommand("pm clear " + packageName); } /** * Stores the specified log for this test * @throws Exception */ public static void storeLogs(String sourceLogFileName, String destLogFileName) throws Exception { // assumes eventmanager is running // store logs String tmpdir = System.getProperty("java.io.tmpdir"); if (tmpdir == null || tmpdir == "null") { tmpdir = "/tmp"; } File tmpLogFile = new File(tmpdir + File.separator + sourceLogFileName); File destFile = new File(current_log_dir + File.separator + destLogFileName); Files.copy(tmpLogFile, destFile); } public static void storeFailurePng() throws Exception { File failureFile = new File("FAILURE.png"); File destFile = new File(current_log_dir + File.separator + "FAILURE.png"); Files.copy(failureFile, destFile); } public static void setupLogDirectories(String testName) throws Exception { File log_dir = new File(getLogDirectory(testName) + File.separator + "test.log");
// Path: RoboRemoteClientCommon/src/main/com/groupon/roboremote/roboremoteclientcommon/logging/TestLogger.java // public class TestLogger { // private static final String LoggerName = "test"; // protected static final Logger logger = LoggerFactory.getLogger(LoggerName); // // public static Logger get() // { // return logger; // } // } // Path: RoboRemoteClientCommon/src/main/com/groupon/roboremote/roboremoteclientcommon/Device.java import com.google.common.io.Files; import com.groupon.roboremote.roboremoteclientcommon.logging.TestLogger; import java.io.*; /* Copyright (c) 2012, 2013, 2014, Groupon, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of GROUPON nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.groupon.roboremote.roboremoteclientcommon; /** * This class defines general device/emulator commands */ public class Device { static boolean emulator = false; static String current_log_dir = null; public static boolean isEmulator() throws Exception { return DebugBridge.get().isEmulator(); } public static void clearAppData(String packageName) throws Exception { // clear app data DebugBridge.get().runShellCommand("pm clear " + packageName); } /** * Stores the specified log for this test * @throws Exception */ public static void storeLogs(String sourceLogFileName, String destLogFileName) throws Exception { // assumes eventmanager is running // store logs String tmpdir = System.getProperty("java.io.tmpdir"); if (tmpdir == null || tmpdir == "null") { tmpdir = "/tmp"; } File tmpLogFile = new File(tmpdir + File.separator + sourceLogFileName); File destFile = new File(current_log_dir + File.separator + destLogFileName); Files.copy(tmpLogFile, destFile); } public static void storeFailurePng() throws Exception { File failureFile = new File("FAILURE.png"); File destFile = new File(current_log_dir + File.separator + "FAILURE.png"); Files.copy(failureFile, destFile); } public static void setupLogDirectories(String testName) throws Exception { File log_dir = new File(getLogDirectory(testName) + File.separator + "test.log");
TestLogger.get().info("Log directory: {}", log_dir.getParent());
groupon/robo-remote
UIAutomatorClient/src/main/com/groupon/roboremote/uiautomatorclient/components/Notification.java
// Path: UIAutomatorClient/src/main/com/groupon/roboremote/uiautomatorclient/Client.java // public class Client extends com.groupon.roboremote.roboremoteclientcommon.Client { // private static Client instance = null; // // /** // * Gets a client instance on the uiautomator port // * @return // */ // public static Client getInstance() { // if(instance == null) { // instance = new Client(); // } // // instance.API_PORT = PortSingleton.getInstance().getPort(); // return instance; // } // } // // Path: UIAutomatorClient/src/main/com/groupon/roboremote/uiautomatorclient/Constants.java // public class Constants { // // robotium constants // public static final String UIAUTOMATOR_UIDEVICE = "getUiDevice"; // } // // Path: UIAutomatorClient/src/main/com/groupon/roboremote/uiautomatorclient/QueryBuilder.java // public class QueryBuilder extends com.groupon.roboremote.roboremoteclientcommon.QueryBuilder { // // Returns a QueryBuilder on the UIAutomator port // public QueryBuilder() { // super(PortSingleton.getInstance().getPort()); // } // }
import com.groupon.roboremote.uiautomatorclient.Client; import com.groupon.roboremote.uiautomatorclient.Constants; import com.groupon.roboremote.uiautomatorclient.QueryBuilder;
package com.groupon.roboremote.uiautomatorclient.components; /** * Created with IntelliJ IDEA. * User: davidv * Date: 10/15/13 * Time: 3:40 PM * To change this template use File | Settings | File Templates. */ public class Notification { public static void click(String notificationLabel) throws Exception {
// Path: UIAutomatorClient/src/main/com/groupon/roboremote/uiautomatorclient/Client.java // public class Client extends com.groupon.roboremote.roboremoteclientcommon.Client { // private static Client instance = null; // // /** // * Gets a client instance on the uiautomator port // * @return // */ // public static Client getInstance() { // if(instance == null) { // instance = new Client(); // } // // instance.API_PORT = PortSingleton.getInstance().getPort(); // return instance; // } // } // // Path: UIAutomatorClient/src/main/com/groupon/roboremote/uiautomatorclient/Constants.java // public class Constants { // // robotium constants // public static final String UIAUTOMATOR_UIDEVICE = "getUiDevice"; // } // // Path: UIAutomatorClient/src/main/com/groupon/roboremote/uiautomatorclient/QueryBuilder.java // public class QueryBuilder extends com.groupon.roboremote.roboremoteclientcommon.QueryBuilder { // // Returns a QueryBuilder on the UIAutomator port // public QueryBuilder() { // super(PortSingleton.getInstance().getPort()); // } // } // Path: UIAutomatorClient/src/main/com/groupon/roboremote/uiautomatorclient/components/Notification.java import com.groupon.roboremote.uiautomatorclient.Client; import com.groupon.roboremote.uiautomatorclient.Constants; import com.groupon.roboremote.uiautomatorclient.QueryBuilder; package com.groupon.roboremote.uiautomatorclient.components; /** * Created with IntelliJ IDEA. * User: davidv * Date: 10/15/13 * Time: 3:40 PM * To change this template use File | Settings | File Templates. */ public class Notification { public static void click(String notificationLabel) throws Exception {
new QueryBuilder().map("com.android.uiautomator.core.UiSelector", "className", "android.widget.TextView").call("text", notificationLabel).execute();
groupon/robo-remote
RoboRemoteServer/apklib/src/main/com/groupon/roboremote/roboremoteserver/RemoteTest.java
// Path: RoboRemoteConstants/src/main/com/groupon/roboremote/Constants.java // public class Constants { // // Port constants // public static final int ROBOREMOTE_SERVER_PORT = 20300; // public static final int UIAUTOMATOR_SERVER_PORT = 20301; // }
import org.junit.Before; import org.junit.Rule; import android.app.Activity; import android.app.Instrumentation; import com.groupon.roboremote.Constants; import com.groupon.roboremote.roboremoteserver.robotium.*; import android.support.test.InstrumentationRegistry; import android.support.test.rule.ActivityTestRule;
/* Copyright (c) 2012, 2013, 2014, Groupon, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of GROUPON nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.groupon.roboremote.roboremoteserver; public abstract class RemoteTest<T extends Activity> { protected Solo2 solo; private Object lastResponseObject = null; private Boolean appStarted = false; private RoboRemoteServer rrs = null; @Rule public ActivityTestRule<T> mActivityRule; public RemoteTest(Class<T> activityClass) throws ClassNotFoundException { rrs = new RoboRemoteServer(null, getInstrumentation(), this); mActivityRule = new ActivityTestRule(activityClass); } public Instrumentation getInstrumentation() { return InstrumentationRegistry.getInstrumentation(); } public void startServer() throws Exception {
// Path: RoboRemoteConstants/src/main/com/groupon/roboremote/Constants.java // public class Constants { // // Port constants // public static final int ROBOREMOTE_SERVER_PORT = 20300; // public static final int UIAUTOMATOR_SERVER_PORT = 20301; // } // Path: RoboRemoteServer/apklib/src/main/com/groupon/roboremote/roboremoteserver/RemoteTest.java import org.junit.Before; import org.junit.Rule; import android.app.Activity; import android.app.Instrumentation; import com.groupon.roboremote.Constants; import com.groupon.roboremote.roboremoteserver.robotium.*; import android.support.test.InstrumentationRegistry; import android.support.test.rule.ActivityTestRule; /* Copyright (c) 2012, 2013, 2014, Groupon, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of GROUPON nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.groupon.roboremote.roboremoteserver; public abstract class RemoteTest<T extends Activity> { protected Solo2 solo; private Object lastResponseObject = null; private Boolean appStarted = false; private RoboRemoteServer rrs = null; @Rule public ActivityTestRule<T> mActivityRule; public RemoteTest(Class<T> activityClass) throws ClassNotFoundException { rrs = new RoboRemoteServer(null, getInstrumentation(), this); mActivityRule = new ActivityTestRule(activityClass); } public Instrumentation getInstrumentation() { return InstrumentationRegistry.getInstrumentation(); } public void startServer() throws Exception {
int port = Constants.ROBOREMOTE_SERVER_PORT;
groupon/robo-remote
UIAutomatorClient/src/main/com/groupon/roboremote/uiautomatorclient/components/BaseObject.java
// Path: UIAutomatorClient/src/main/com/groupon/roboremote/uiautomatorclient/QueryBuilder.java // public class QueryBuilder extends com.groupon.roboremote.roboremoteclientcommon.QueryBuilder { // // Returns a QueryBuilder on the UIAutomator port // public QueryBuilder() { // super(PortSingleton.getInstance().getPort()); // } // }
import com.groupon.roboremote.uiautomatorclient.QueryBuilder; import org.json.JSONArray;
/* Copyright (c) 2012, 2013, 2014, Groupon, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of GROUPON nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.groupon.roboremote.uiautomatorclient.components; public class BaseObject { String storedId; protected BaseObject() throws Exception { } /** * Creates a new object based on the storedId of an object * @param storedId */ public BaseObject(String storedId) { this.storedId = storedId; } // returns the stored ID for other operations to use protected String getStoredId() { return storedId; } /** * Call a function on this object * @param method * @param args * @return * @throws Exception */ protected JSONArray callMethod(String method, Object ... args) throws Exception {
// Path: UIAutomatorClient/src/main/com/groupon/roboremote/uiautomatorclient/QueryBuilder.java // public class QueryBuilder extends com.groupon.roboremote.roboremoteclientcommon.QueryBuilder { // // Returns a QueryBuilder on the UIAutomator port // public QueryBuilder() { // super(PortSingleton.getInstance().getPort()); // } // } // Path: UIAutomatorClient/src/main/com/groupon/roboremote/uiautomatorclient/components/BaseObject.java import com.groupon.roboremote.uiautomatorclient.QueryBuilder; import org.json.JSONArray; /* Copyright (c) 2012, 2013, 2014, Groupon, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of GROUPON nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.groupon.roboremote.uiautomatorclient.components; public class BaseObject { String storedId; protected BaseObject() throws Exception { } /** * Creates a new object based on the storedId of an object * @param storedId */ public BaseObject(String storedId) { this.storedId = storedId; } // returns the stored ID for other operations to use protected String getStoredId() { return storedId; } /** * Call a function on this object * @param method * @param args * @return * @throws Exception */ protected JSONArray callMethod(String method, Object ... args) throws Exception {
return new QueryBuilder().retrieveResult(storedId).call(method, args).storeResult("LAST_" + getStoredId()).execute();
groupon/robo-remote
RoboRemoteClientJUnit/src/main/com/groupon/roboremote/roboremoteclient/junit/TestBase.java
// Path: RoboRemoteConstants/src/main/com/groupon/roboremote/Constants.java // public class Constants { // // Port constants // public static final int ROBOREMOTE_SERVER_PORT = 20300; // public static final int UIAUTOMATOR_SERVER_PORT = 20301; // } // // Path: RoboRemoteClientCommon/src/main/com/groupon/roboremote/roboremoteclientcommon/Utils.java // public class Utils { // public static final Logger logger = LoggerFactory.getLogger(Utils.class); // // public static ArrayList<String> jsonArrayToStringList(JSONArray arry) throws Exception { // ArrayList<String> newArray = new ArrayList<String>(); // for (int x = 0; x < arry.length(); x++) { // newArray.add(arry.getString(x)); // } // // return newArray; // } // // /** // * returns values for a key in the following order: // * 1. First checks environment variables // * 2. Falls back to system properties // * // * @param name // * @param defaultValue // * @return // */ // public static String getEnv(String name, String defaultValue) { // Map<String, String> env = System.getenv(); // // // try to get value from environment variables // if (env.get(name) != null) { // return env.get(name); // } // // // fall back to system properties // return System.getProperty(name, defaultValue); // } // // public static int getFreePort() throws Exception { // ServerSocket serverSocket = new ServerSocket(0); // int port = serverSocket.getLocalPort(); // serverSocket.close(); // // return port; // } // // public static String executeLocalCommand(String[] command) { // StringBuffer output = new StringBuffer(); // // Process p; // try { // p = Runtime.getRuntime().exec(command); // p.waitFor(); // BufferedReader reader = // new BufferedReader(new InputStreamReader(p.getInputStream())); // // String line = ""; // while ((line = reader.readLine()) != null) { // output.append(line + "\n"); // } // // reader = // new BufferedReader(new InputStreamReader(p.getErrorStream())); // // line = ""; // while ((line = reader.readLine()) != null) { // output.append(line + "\n"); // } // // } catch (Exception e) { // e.printStackTrace(); // } // // return output.toString(); // } // // public static void clearStaleADBTunnels(String type) throws Exception { // // looks for PID style files with the specified type, removes tunnels and deletes files // String lsResult = executeLocalCommand(new String[] {"adb", "-s", DebugBridge.get().getSerialNumber(), "shell", "ls", "/data/local/tmp"}); // String[] lsResults = lsResult.split(System.getProperty("line.separator")); // for (String file : lsResults) { // if (file.startsWith(type + "_PORT_")) { // String portStr = file.replace(type + "_PORT_", ""); // int port = Integer.parseInt(portStr); // try { // DebugBridge.get().deleteTunnel(port, port); // } catch (Exception e) { // // ddmlib will throw an exception if the tunnel doesn't exist // logger.info("Exception deleting tunnel ignored. Tunnel may not have existed."); // } // DebugBridge.get().runShellCommand("rm /data/local/tmp/" + file); // // logger.info("Removed stale port forward: {}", port); // } // } // } // // public static void addADBTunnelWithPIDFile(String type, int port) throws Exception { // DebugBridge.get().createTunnel(port, port); // DebugBridge.get().runShellCommand("touch /data/local/tmp/" + type + "_PORT_" + port); // } // // public static void deleteDirectory(File f) throws IOException { // if (f.isDirectory()) { // for (File c : f.listFiles()) { // deleteDirectory(c); // } // } // if (!f.delete()) // throw new FileNotFoundException("Failed to delete file: " + f); // } // }
import com.groupon.roboremote.Constants; import com.groupon.roboremote.roboremoteclientcommon.Utils; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.rules.MethodRule; import org.junit.rules.TestName; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.Statement; import static org.junit.Assert.fail;
onFailure(); } catch (Exception ee) { // don't want a new failure here to change the the teardown flow // just swallow this error } failed = true; error = e; } logger.info("Calling onFail/onPass functions"); if (failed) { // do failure stuff here // for writing own fail function in custom com.groupon.roboremote.uiautomatorclient.TestBase onFail(m); } else { // do passed stuff here // for writing own pass function in custom com.groupon.roboremote.uiautomatorclient.TestBase onPass(m); } // tear down robotium remote logger.info("Calling tearDown"); tearDown(); // tear down uiautomator remote
// Path: RoboRemoteConstants/src/main/com/groupon/roboremote/Constants.java // public class Constants { // // Port constants // public static final int ROBOREMOTE_SERVER_PORT = 20300; // public static final int UIAUTOMATOR_SERVER_PORT = 20301; // } // // Path: RoboRemoteClientCommon/src/main/com/groupon/roboremote/roboremoteclientcommon/Utils.java // public class Utils { // public static final Logger logger = LoggerFactory.getLogger(Utils.class); // // public static ArrayList<String> jsonArrayToStringList(JSONArray arry) throws Exception { // ArrayList<String> newArray = new ArrayList<String>(); // for (int x = 0; x < arry.length(); x++) { // newArray.add(arry.getString(x)); // } // // return newArray; // } // // /** // * returns values for a key in the following order: // * 1. First checks environment variables // * 2. Falls back to system properties // * // * @param name // * @param defaultValue // * @return // */ // public static String getEnv(String name, String defaultValue) { // Map<String, String> env = System.getenv(); // // // try to get value from environment variables // if (env.get(name) != null) { // return env.get(name); // } // // // fall back to system properties // return System.getProperty(name, defaultValue); // } // // public static int getFreePort() throws Exception { // ServerSocket serverSocket = new ServerSocket(0); // int port = serverSocket.getLocalPort(); // serverSocket.close(); // // return port; // } // // public static String executeLocalCommand(String[] command) { // StringBuffer output = new StringBuffer(); // // Process p; // try { // p = Runtime.getRuntime().exec(command); // p.waitFor(); // BufferedReader reader = // new BufferedReader(new InputStreamReader(p.getInputStream())); // // String line = ""; // while ((line = reader.readLine()) != null) { // output.append(line + "\n"); // } // // reader = // new BufferedReader(new InputStreamReader(p.getErrorStream())); // // line = ""; // while ((line = reader.readLine()) != null) { // output.append(line + "\n"); // } // // } catch (Exception e) { // e.printStackTrace(); // } // // return output.toString(); // } // // public static void clearStaleADBTunnels(String type) throws Exception { // // looks for PID style files with the specified type, removes tunnels and deletes files // String lsResult = executeLocalCommand(new String[] {"adb", "-s", DebugBridge.get().getSerialNumber(), "shell", "ls", "/data/local/tmp"}); // String[] lsResults = lsResult.split(System.getProperty("line.separator")); // for (String file : lsResults) { // if (file.startsWith(type + "_PORT_")) { // String portStr = file.replace(type + "_PORT_", ""); // int port = Integer.parseInt(portStr); // try { // DebugBridge.get().deleteTunnel(port, port); // } catch (Exception e) { // // ddmlib will throw an exception if the tunnel doesn't exist // logger.info("Exception deleting tunnel ignored. Tunnel may not have existed."); // } // DebugBridge.get().runShellCommand("rm /data/local/tmp/" + file); // // logger.info("Removed stale port forward: {}", port); // } // } // } // // public static void addADBTunnelWithPIDFile(String type, int port) throws Exception { // DebugBridge.get().createTunnel(port, port); // DebugBridge.get().runShellCommand("touch /data/local/tmp/" + type + "_PORT_" + port); // } // // public static void deleteDirectory(File f) throws IOException { // if (f.isDirectory()) { // for (File c : f.listFiles()) { // deleteDirectory(c); // } // } // if (!f.delete()) // throw new FileNotFoundException("Failed to delete file: " + f); // } // } // Path: RoboRemoteClientJUnit/src/main/com/groupon/roboremote/roboremoteclient/junit/TestBase.java import com.groupon.roboremote.Constants; import com.groupon.roboremote.roboremoteclientcommon.Utils; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.rules.MethodRule; import org.junit.rules.TestName; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.Statement; import static org.junit.Assert.fail; onFailure(); } catch (Exception ee) { // don't want a new failure here to change the the teardown flow // just swallow this error } failed = true; error = e; } logger.info("Calling onFail/onPass functions"); if (failed) { // do failure stuff here // for writing own fail function in custom com.groupon.roboremote.uiautomatorclient.TestBase onFail(m); } else { // do passed stuff here // for writing own pass function in custom com.groupon.roboremote.uiautomatorclient.TestBase onPass(m); } // tear down robotium remote logger.info("Calling tearDown"); tearDown(); // tear down uiautomator remote
if (Utils.getEnv("ROBO_UIAUTOMATOR_JAR", null) != null) {
groupon/robo-remote
UIAutomatorClient/src/main/com/groupon/roboremote/uiautomatorclient/components/UiScrollable.java
// Path: UIAutomatorClient/src/main/com/groupon/roboremote/uiautomatorclient/QueryBuilder.java // public class QueryBuilder extends com.groupon.roboremote.roboremoteclientcommon.QueryBuilder { // // Returns a QueryBuilder on the UIAutomator port // public QueryBuilder() { // super(PortSingleton.getInstance().getPort()); // } // }
import com.groupon.roboremote.uiautomatorclient.QueryBuilder; import org.json.JSONArray; import java.util.UUID;
/* Copyright (c) 2012, 2013, 2014, Groupon, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of GROUPON nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.groupon.roboremote.uiautomatorclient.components; public class UiScrollable extends BaseObject { public UiScrollable(UiSelector selector) throws Exception { storedId = UUID.randomUUID().toString();
// Path: UIAutomatorClient/src/main/com/groupon/roboremote/uiautomatorclient/QueryBuilder.java // public class QueryBuilder extends com.groupon.roboremote.roboremoteclientcommon.QueryBuilder { // // Returns a QueryBuilder on the UIAutomator port // public QueryBuilder() { // super(PortSingleton.getInstance().getPort()); // } // } // Path: UIAutomatorClient/src/main/com/groupon/roboremote/uiautomatorclient/components/UiScrollable.java import com.groupon.roboremote.uiautomatorclient.QueryBuilder; import org.json.JSONArray; import java.util.UUID; /* Copyright (c) 2012, 2013, 2014, Groupon, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of GROUPON nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.groupon.roboremote.uiautomatorclient.components; public class UiScrollable extends BaseObject { public UiScrollable(UiSelector selector) throws Exception { storedId = UUID.randomUUID().toString();
new QueryBuilder().instantiate("com.android.uiautomator.core.UiScrollable", QueryBuilder.getStoredValue(selector.getStoredId())).storeResult(storedId).execute();
open-io/oio-api-java
src/main/java/io/openio/sds/models/LinkedServiceInfo.java
// Path: src/main/java/io/openio/sds/common/MoreObjects.java // public class MoreObjects { // // public static ToStringHelper toStringHelper(String name) { // return new ToStringHelper(name); // } // // public static ToStringHelper toStringHelper(Object o) { // return new ToStringHelper(o.getClass().getSimpleName()); // } // // public static class ToStringHelper { // // private String name; // private HashMap<String, Object> fields = new HashMap<String, Object>(); // private boolean skipNulls = false; // // private ToStringHelper(String name) { // this.name = name; // } // // public ToStringHelper add(String key, Object value) { // if (null != key && (null != value || !skipNulls)) // fields.put(key, value); // return this; // } // // public ToStringHelper omitNullValues(){ // this.skipNulls = true; // return this; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(name) // .append("={"); // for (Entry<String, Object> e : fields.entrySet()) { // sb.append("\"") // .append(e.getKey()) // .append("\":\"") // .append(e.getValue()) // .append("\","); // } // // return sb.replace(sb.length() - 1, sb.length(), "}") // .toString(); // } // } // }
import io.openio.sds.common.MoreObjects;
public String type() { return type; } public LinkedServiceInfo type(String type) { this.type = type; return this; } public String host() { return host; } public LinkedServiceInfo host(String host) { this.host = host; return this; } public String args() { return args; } public LinkedServiceInfo args(String args) { this.args = args; return this; } @Override public String toString(){
// Path: src/main/java/io/openio/sds/common/MoreObjects.java // public class MoreObjects { // // public static ToStringHelper toStringHelper(String name) { // return new ToStringHelper(name); // } // // public static ToStringHelper toStringHelper(Object o) { // return new ToStringHelper(o.getClass().getSimpleName()); // } // // public static class ToStringHelper { // // private String name; // private HashMap<String, Object> fields = new HashMap<String, Object>(); // private boolean skipNulls = false; // // private ToStringHelper(String name) { // this.name = name; // } // // public ToStringHelper add(String key, Object value) { // if (null != key && (null != value || !skipNulls)) // fields.put(key, value); // return this; // } // // public ToStringHelper omitNullValues(){ // this.skipNulls = true; // return this; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(name) // .append("={"); // for (Entry<String, Object> e : fields.entrySet()) { // sb.append("\"") // .append(e.getKey()) // .append("\":\"") // .append(e.getValue()) // .append("\","); // } // // return sb.replace(sb.length() - 1, sb.length(), "}") // .toString(); // } // } // } // Path: src/main/java/io/openio/sds/models/LinkedServiceInfo.java import io.openio.sds.common.MoreObjects; public String type() { return type; } public LinkedServiceInfo type(String type) { this.type = type; return this; } public String host() { return host; } public LinkedServiceInfo host(String host) { this.host = host; return this; } public String args() { return args; } public LinkedServiceInfo args(String args) { this.args = args; return this; } @Override public String toString(){
return MoreObjects.toStringHelper(this)
open-io/oio-api-java
src/main/java/io/openio/sds/common/JsonUtils.java
// Path: src/main/java/io/openio/sds/common/OioConstants.java // public static final Charset OIO_CHARSET = Charset.forName("UTF-8"); // // Path: src/main/java/io/openio/sds/models/Position.java // public class Position { // // private static final Pattern POSITION_PATTERN = Pattern // .compile("^([\\d]+)(\\.([\\d]+))?$"); // // private int meta; // private int sub; // // private Position(int meta, int sub) { // this.meta = meta; // this.sub = sub; // } // // public static Position parse(String pos) { // Matcher m = POSITION_PATTERN.matcher(pos); // checkArgument(m.matches(), // String.format("Invalid position %s", pos)); // if (null == m.group(2)) // return simple(Integer.parseInt(m.group(1))); // return composed(Integer.parseInt(m.group(1)), // Integer.parseInt(m.group(3))); // } // // public static Position simple(int meta) { // checkArgument(0 <= meta, "Invalid position"); // return new Position(meta, -1); // } // // public static Position composed(int meta, int sub) { // checkArgument(0 <= meta, "Invalid meta position"); // checkArgument(0 <= sub, "Invalid sub position"); // return new Position(meta, sub); // } // // public int meta() { // return meta; // } // // public int sub() { // return sub; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder().append(meta); // if (-1 != sub) // sb.append(".").append(sub); // return sb.toString(); // } // // /** // * Returns negative, 0 or positive int if the position is lower, equals or // * higher than the specified one . // * <p> // * This method compares the meta position, if equals, // * it compares the sub position. // * // * @param pos // * the position to compare to // * @return negative, 0 or positive int if the position is lower, equals or // * higher than the specified one . // */ // public int compare(Position pos) { // if (meta == pos.meta()) return sub - pos.sub(); // else return meta - pos.meta(); // } // }
import static io.openio.sds.common.OioConstants.OIO_CHARSET; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.Type; import java.util.Map; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; import io.openio.sds.models.Position;
package io.openio.sds.common; /** * Gson utility class */ public class JsonUtils { private static final GsonBuilder builder = new GsonBuilder()
// Path: src/main/java/io/openio/sds/common/OioConstants.java // public static final Charset OIO_CHARSET = Charset.forName("UTF-8"); // // Path: src/main/java/io/openio/sds/models/Position.java // public class Position { // // private static final Pattern POSITION_PATTERN = Pattern // .compile("^([\\d]+)(\\.([\\d]+))?$"); // // private int meta; // private int sub; // // private Position(int meta, int sub) { // this.meta = meta; // this.sub = sub; // } // // public static Position parse(String pos) { // Matcher m = POSITION_PATTERN.matcher(pos); // checkArgument(m.matches(), // String.format("Invalid position %s", pos)); // if (null == m.group(2)) // return simple(Integer.parseInt(m.group(1))); // return composed(Integer.parseInt(m.group(1)), // Integer.parseInt(m.group(3))); // } // // public static Position simple(int meta) { // checkArgument(0 <= meta, "Invalid position"); // return new Position(meta, -1); // } // // public static Position composed(int meta, int sub) { // checkArgument(0 <= meta, "Invalid meta position"); // checkArgument(0 <= sub, "Invalid sub position"); // return new Position(meta, sub); // } // // public int meta() { // return meta; // } // // public int sub() { // return sub; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder().append(meta); // if (-1 != sub) // sb.append(".").append(sub); // return sb.toString(); // } // // /** // * Returns negative, 0 or positive int if the position is lower, equals or // * higher than the specified one . // * <p> // * This method compares the meta position, if equals, // * it compares the sub position. // * // * @param pos // * the position to compare to // * @return negative, 0 or positive int if the position is lower, equals or // * higher than the specified one . // */ // public int compare(Position pos) { // if (meta == pos.meta()) return sub - pos.sub(); // else return meta - pos.meta(); // } // } // Path: src/main/java/io/openio/sds/common/JsonUtils.java import static io.openio.sds.common.OioConstants.OIO_CHARSET; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.Type; import java.util.Map; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; import io.openio.sds.models.Position; package io.openio.sds.common; /** * Gson utility class */ public class JsonUtils { private static final GsonBuilder builder = new GsonBuilder()
.registerTypeAdapter(Position.class, new PositionAdapter());
open-io/oio-api-java
src/main/java/io/openio/sds/common/JsonUtils.java
// Path: src/main/java/io/openio/sds/common/OioConstants.java // public static final Charset OIO_CHARSET = Charset.forName("UTF-8"); // // Path: src/main/java/io/openio/sds/models/Position.java // public class Position { // // private static final Pattern POSITION_PATTERN = Pattern // .compile("^([\\d]+)(\\.([\\d]+))?$"); // // private int meta; // private int sub; // // private Position(int meta, int sub) { // this.meta = meta; // this.sub = sub; // } // // public static Position parse(String pos) { // Matcher m = POSITION_PATTERN.matcher(pos); // checkArgument(m.matches(), // String.format("Invalid position %s", pos)); // if (null == m.group(2)) // return simple(Integer.parseInt(m.group(1))); // return composed(Integer.parseInt(m.group(1)), // Integer.parseInt(m.group(3))); // } // // public static Position simple(int meta) { // checkArgument(0 <= meta, "Invalid position"); // return new Position(meta, -1); // } // // public static Position composed(int meta, int sub) { // checkArgument(0 <= meta, "Invalid meta position"); // checkArgument(0 <= sub, "Invalid sub position"); // return new Position(meta, sub); // } // // public int meta() { // return meta; // } // // public int sub() { // return sub; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder().append(meta); // if (-1 != sub) // sb.append(".").append(sub); // return sb.toString(); // } // // /** // * Returns negative, 0 or positive int if the position is lower, equals or // * higher than the specified one . // * <p> // * This method compares the meta position, if equals, // * it compares the sub position. // * // * @param pos // * the position to compare to // * @return negative, 0 or positive int if the position is lower, equals or // * higher than the specified one . // */ // public int compare(Position pos) { // if (meta == pos.meta()) return sub - pos.sub(); // else return meta - pos.meta(); // } // }
import static io.openio.sds.common.OioConstants.OIO_CHARSET; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.Type; import java.util.Map; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; import io.openio.sds.models.Position;
package io.openio.sds.common; /** * Gson utility class */ public class JsonUtils { private static final GsonBuilder builder = new GsonBuilder() .registerTypeAdapter(Position.class, new PositionAdapter()); private static final ObjectMapper mapper = new ObjectMapper(); private static final Type MAP_TYPE = new TypeToken<Map<String, String>>() { }.getType(); private static final Type MAP_MAP_TYPE = new TypeToken<Map<String, Map<String, String>>>() { }.getType(); /** * Returns a new {@code Gson} instance with OpenIO adapters * * @return the gson instance */ public static Gson gson() { return builder.create(); } public static Gson gsonForObject() { return builder.serializeNulls().create(); } public static Map<String, String> jsonToMap(String map) { return gson().fromJson(map, MAP_TYPE); } public static Map<String, String> jsonToMap(InputStream in) { return gson().fromJson(
// Path: src/main/java/io/openio/sds/common/OioConstants.java // public static final Charset OIO_CHARSET = Charset.forName("UTF-8"); // // Path: src/main/java/io/openio/sds/models/Position.java // public class Position { // // private static final Pattern POSITION_PATTERN = Pattern // .compile("^([\\d]+)(\\.([\\d]+))?$"); // // private int meta; // private int sub; // // private Position(int meta, int sub) { // this.meta = meta; // this.sub = sub; // } // // public static Position parse(String pos) { // Matcher m = POSITION_PATTERN.matcher(pos); // checkArgument(m.matches(), // String.format("Invalid position %s", pos)); // if (null == m.group(2)) // return simple(Integer.parseInt(m.group(1))); // return composed(Integer.parseInt(m.group(1)), // Integer.parseInt(m.group(3))); // } // // public static Position simple(int meta) { // checkArgument(0 <= meta, "Invalid position"); // return new Position(meta, -1); // } // // public static Position composed(int meta, int sub) { // checkArgument(0 <= meta, "Invalid meta position"); // checkArgument(0 <= sub, "Invalid sub position"); // return new Position(meta, sub); // } // // public int meta() { // return meta; // } // // public int sub() { // return sub; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder().append(meta); // if (-1 != sub) // sb.append(".").append(sub); // return sb.toString(); // } // // /** // * Returns negative, 0 or positive int if the position is lower, equals or // * higher than the specified one . // * <p> // * This method compares the meta position, if equals, // * it compares the sub position. // * // * @param pos // * the position to compare to // * @return negative, 0 or positive int if the position is lower, equals or // * higher than the specified one . // */ // public int compare(Position pos) { // if (meta == pos.meta()) return sub - pos.sub(); // else return meta - pos.meta(); // } // } // Path: src/main/java/io/openio/sds/common/JsonUtils.java import static io.openio.sds.common.OioConstants.OIO_CHARSET; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.Type; import java.util.Map; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.JsonProcessingException; import io.openio.sds.models.Position; package io.openio.sds.common; /** * Gson utility class */ public class JsonUtils { private static final GsonBuilder builder = new GsonBuilder() .registerTypeAdapter(Position.class, new PositionAdapter()); private static final ObjectMapper mapper = new ObjectMapper(); private static final Type MAP_TYPE = new TypeToken<Map<String, String>>() { }.getType(); private static final Type MAP_MAP_TYPE = new TypeToken<Map<String, Map<String, String>>>() { }.getType(); /** * Returns a new {@code Gson} instance with OpenIO adapters * * @return the gson instance */ public static Gson gson() { return builder.create(); } public static Gson gsonForObject() { return builder.serializeNulls().create(); } public static Map<String, String> jsonToMap(String map) { return gson().fromJson(map, MAP_TYPE); } public static Map<String, String> jsonToMap(InputStream in) { return gson().fromJson(
new JsonReader(new InputStreamReader(in, OIO_CHARSET)),
open-io/oio-api-java
src/main/java/io/openio/sds/models/ProxyError.java
// Path: src/main/java/io/openio/sds/common/OioConstants.java // public static final String PROXY_ERROR_FORMAT = "(%d) %s";
import static io.openio.sds.common.OioConstants.PROXY_ERROR_FORMAT; import static java.lang.String.format;
package io.openio.sds.models; /** * * @author Christopher Dedeurwaerder * */ public class ProxyError { private Integer status; private String message; public ProxyError() { } public Integer status() { return status; } public ProxyError status(Integer status) { this.status = status; return this; } public String message() { return message; } public ProxyError message(String message) { this.message = message; return this; } @Override public String toString() {
// Path: src/main/java/io/openio/sds/common/OioConstants.java // public static final String PROXY_ERROR_FORMAT = "(%d) %s"; // Path: src/main/java/io/openio/sds/models/ProxyError.java import static io.openio.sds.common.OioConstants.PROXY_ERROR_FORMAT; import static java.lang.String.format; package io.openio.sds.models; /** * * @author Christopher Dedeurwaerder * */ public class ProxyError { private Integer status; private String message; public ProxyError() { } public Integer status() { return status; } public ProxyError status(Integer status) { this.status = status; return this; } public String message() { return message; } public ProxyError message(String message) { this.message = message; return this; } @Override public String toString() {
return format(PROXY_ERROR_FORMAT, status, message);
open-io/oio-api-java
src/main/java/io/openio/sds/common/AbstractSocketProvider.java
// Path: src/main/java/io/openio/sds/exceptions/OioException.java // @SuppressWarnings("deprecation") // public class OioException extends SdsException { // // /** // * // */ // private static final long serialVersionUID = 3270900242235005338L; // // public OioException(String message) { // super(message); // } // // public OioException(String message, Throwable t) { // super(message, t); // } // } // // Path: src/main/java/io/openio/sds/http/OioHttpSettings.java // public class OioHttpSettings { // // private Integer sendBufferSize = 131072; // private Integer receiveBufferSize = 131072; // private Boolean setSocketBufferSize = false; // private Integer connectTimeout = 30000; // private Integer readTimeout = 60000; // private String userAgent = "oio-http"; // // public OioHttpSettings() { // } // // public Integer sendBufferSize() { // return sendBufferSize; // } // // public OioHttpSettings sendBufferSize(Integer sendBufferSize) { // this.sendBufferSize = sendBufferSize; // return this; // } // // public Integer receiveBufferSize() { // return receiveBufferSize; // } // // public OioHttpSettings receiveBufferSize(Integer receiveBufferSize) { // this.receiveBufferSize = receiveBufferSize; // return this; // } // // /** // * Should the size of the socket buffers be explicitly set? // * When true, explicitly set the send buffer size (resp. receive buffer // * size) to {@link #sendBufferSize} (resp. {@link #receiveBufferSize}). // * When false, let the kernel adjust the size automatically. // * // * @return true when the API should set the socket buffer sizes, // * false when it should let the kernel decide. // */ // public Boolean setSocketBufferSize() { // return this.setSocketBufferSize; // } // // /** // * Should the size of the socket buffers be explicitly set? // * When true, explicitly set the send buffer size (resp. receive buffer // * size) to {@link #sendBufferSize} (resp. {@link #receiveBufferSize}). // * When false, let the kernel adjust the size automatically. // * // * @param setSocketBufferSize // * @return this // */ // public OioHttpSettings setSocketBufferSize(Boolean setSocketBufferSize) { // this.setSocketBufferSize = setSocketBufferSize; // return this; // } // // public Integer connectTimeout() { // return connectTimeout; // } // // public OioHttpSettings connectTimeout(Integer connectTimeout) { // this.connectTimeout = connectTimeout; // return this; // } // // public Integer readTimeout() { // return readTimeout; // } // // public OioHttpSettings readTimeout(Integer readTimeout) { // this.readTimeout = readTimeout; // return this; // } // // public String userAgent() { // return userAgent; // } // // public OioHttpSettings userAgent(String userAgent) { // this.userAgent = userAgent; // return this; // } // } // // Path: src/main/java/io/openio/sds/common/Check.java // public static void checkArgument(boolean condition, String msg) { // if (!condition) // throw new IllegalArgumentException(msg); // }
import static java.lang.String.format; import io.openio.sds.exceptions.OioException; import io.openio.sds.http.OioHttpSettings; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import static io.openio.sds.common.Check.checkArgument;
package io.openio.sds.common; /** * * @author Florent Vennetier * */ public abstract class AbstractSocketProvider implements SocketProvider { /** * Configure an already created Socket with provided settings, and establish the connection. * * @param sock A Socket instance * @param target The address to connect the socket to * @param http The settings to apply * @throws OioException if an error occurs during connection */ protected void configureAndConnect(Socket sock, InetSocketAddress target, OioHttpSettings http)
// Path: src/main/java/io/openio/sds/exceptions/OioException.java // @SuppressWarnings("deprecation") // public class OioException extends SdsException { // // /** // * // */ // private static final long serialVersionUID = 3270900242235005338L; // // public OioException(String message) { // super(message); // } // // public OioException(String message, Throwable t) { // super(message, t); // } // } // // Path: src/main/java/io/openio/sds/http/OioHttpSettings.java // public class OioHttpSettings { // // private Integer sendBufferSize = 131072; // private Integer receiveBufferSize = 131072; // private Boolean setSocketBufferSize = false; // private Integer connectTimeout = 30000; // private Integer readTimeout = 60000; // private String userAgent = "oio-http"; // // public OioHttpSettings() { // } // // public Integer sendBufferSize() { // return sendBufferSize; // } // // public OioHttpSettings sendBufferSize(Integer sendBufferSize) { // this.sendBufferSize = sendBufferSize; // return this; // } // // public Integer receiveBufferSize() { // return receiveBufferSize; // } // // public OioHttpSettings receiveBufferSize(Integer receiveBufferSize) { // this.receiveBufferSize = receiveBufferSize; // return this; // } // // /** // * Should the size of the socket buffers be explicitly set? // * When true, explicitly set the send buffer size (resp. receive buffer // * size) to {@link #sendBufferSize} (resp. {@link #receiveBufferSize}). // * When false, let the kernel adjust the size automatically. // * // * @return true when the API should set the socket buffer sizes, // * false when it should let the kernel decide. // */ // public Boolean setSocketBufferSize() { // return this.setSocketBufferSize; // } // // /** // * Should the size of the socket buffers be explicitly set? // * When true, explicitly set the send buffer size (resp. receive buffer // * size) to {@link #sendBufferSize} (resp. {@link #receiveBufferSize}). // * When false, let the kernel adjust the size automatically. // * // * @param setSocketBufferSize // * @return this // */ // public OioHttpSettings setSocketBufferSize(Boolean setSocketBufferSize) { // this.setSocketBufferSize = setSocketBufferSize; // return this; // } // // public Integer connectTimeout() { // return connectTimeout; // } // // public OioHttpSettings connectTimeout(Integer connectTimeout) { // this.connectTimeout = connectTimeout; // return this; // } // // public Integer readTimeout() { // return readTimeout; // } // // public OioHttpSettings readTimeout(Integer readTimeout) { // this.readTimeout = readTimeout; // return this; // } // // public String userAgent() { // return userAgent; // } // // public OioHttpSettings userAgent(String userAgent) { // this.userAgent = userAgent; // return this; // } // } // // Path: src/main/java/io/openio/sds/common/Check.java // public static void checkArgument(boolean condition, String msg) { // if (!condition) // throw new IllegalArgumentException(msg); // } // Path: src/main/java/io/openio/sds/common/AbstractSocketProvider.java import static java.lang.String.format; import io.openio.sds.exceptions.OioException; import io.openio.sds.http.OioHttpSettings; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import static io.openio.sds.common.Check.checkArgument; package io.openio.sds.common; /** * * @author Florent Vennetier * */ public abstract class AbstractSocketProvider implements SocketProvider { /** * Configure an already created Socket with provided settings, and establish the connection. * * @param sock A Socket instance * @param target The address to connect the socket to * @param http The settings to apply * @throws OioException if an error occurs during connection */ protected void configureAndConnect(Socket sock, InetSocketAddress target, OioHttpSettings http)
throws OioException {
open-io/oio-api-java
src/main/java/io/openio/sds/common/AbstractSocketProvider.java
// Path: src/main/java/io/openio/sds/exceptions/OioException.java // @SuppressWarnings("deprecation") // public class OioException extends SdsException { // // /** // * // */ // private static final long serialVersionUID = 3270900242235005338L; // // public OioException(String message) { // super(message); // } // // public OioException(String message, Throwable t) { // super(message, t); // } // } // // Path: src/main/java/io/openio/sds/http/OioHttpSettings.java // public class OioHttpSettings { // // private Integer sendBufferSize = 131072; // private Integer receiveBufferSize = 131072; // private Boolean setSocketBufferSize = false; // private Integer connectTimeout = 30000; // private Integer readTimeout = 60000; // private String userAgent = "oio-http"; // // public OioHttpSettings() { // } // // public Integer sendBufferSize() { // return sendBufferSize; // } // // public OioHttpSettings sendBufferSize(Integer sendBufferSize) { // this.sendBufferSize = sendBufferSize; // return this; // } // // public Integer receiveBufferSize() { // return receiveBufferSize; // } // // public OioHttpSettings receiveBufferSize(Integer receiveBufferSize) { // this.receiveBufferSize = receiveBufferSize; // return this; // } // // /** // * Should the size of the socket buffers be explicitly set? // * When true, explicitly set the send buffer size (resp. receive buffer // * size) to {@link #sendBufferSize} (resp. {@link #receiveBufferSize}). // * When false, let the kernel adjust the size automatically. // * // * @return true when the API should set the socket buffer sizes, // * false when it should let the kernel decide. // */ // public Boolean setSocketBufferSize() { // return this.setSocketBufferSize; // } // // /** // * Should the size of the socket buffers be explicitly set? // * When true, explicitly set the send buffer size (resp. receive buffer // * size) to {@link #sendBufferSize} (resp. {@link #receiveBufferSize}). // * When false, let the kernel adjust the size automatically. // * // * @param setSocketBufferSize // * @return this // */ // public OioHttpSettings setSocketBufferSize(Boolean setSocketBufferSize) { // this.setSocketBufferSize = setSocketBufferSize; // return this; // } // // public Integer connectTimeout() { // return connectTimeout; // } // // public OioHttpSettings connectTimeout(Integer connectTimeout) { // this.connectTimeout = connectTimeout; // return this; // } // // public Integer readTimeout() { // return readTimeout; // } // // public OioHttpSettings readTimeout(Integer readTimeout) { // this.readTimeout = readTimeout; // return this; // } // // public String userAgent() { // return userAgent; // } // // public OioHttpSettings userAgent(String userAgent) { // this.userAgent = userAgent; // return this; // } // } // // Path: src/main/java/io/openio/sds/common/Check.java // public static void checkArgument(boolean condition, String msg) { // if (!condition) // throw new IllegalArgumentException(msg); // }
import static java.lang.String.format; import io.openio.sds.exceptions.OioException; import io.openio.sds.http.OioHttpSettings; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import static io.openio.sds.common.Check.checkArgument;
package io.openio.sds.common; /** * * @author Florent Vennetier * */ public abstract class AbstractSocketProvider implements SocketProvider { /** * Configure an already created Socket with provided settings, and establish the connection. * * @param sock A Socket instance * @param target The address to connect the socket to * @param http The settings to apply * @throws OioException if an error occurs during connection */ protected void configureAndConnect(Socket sock, InetSocketAddress target, OioHttpSettings http) throws OioException {
// Path: src/main/java/io/openio/sds/exceptions/OioException.java // @SuppressWarnings("deprecation") // public class OioException extends SdsException { // // /** // * // */ // private static final long serialVersionUID = 3270900242235005338L; // // public OioException(String message) { // super(message); // } // // public OioException(String message, Throwable t) { // super(message, t); // } // } // // Path: src/main/java/io/openio/sds/http/OioHttpSettings.java // public class OioHttpSettings { // // private Integer sendBufferSize = 131072; // private Integer receiveBufferSize = 131072; // private Boolean setSocketBufferSize = false; // private Integer connectTimeout = 30000; // private Integer readTimeout = 60000; // private String userAgent = "oio-http"; // // public OioHttpSettings() { // } // // public Integer sendBufferSize() { // return sendBufferSize; // } // // public OioHttpSettings sendBufferSize(Integer sendBufferSize) { // this.sendBufferSize = sendBufferSize; // return this; // } // // public Integer receiveBufferSize() { // return receiveBufferSize; // } // // public OioHttpSettings receiveBufferSize(Integer receiveBufferSize) { // this.receiveBufferSize = receiveBufferSize; // return this; // } // // /** // * Should the size of the socket buffers be explicitly set? // * When true, explicitly set the send buffer size (resp. receive buffer // * size) to {@link #sendBufferSize} (resp. {@link #receiveBufferSize}). // * When false, let the kernel adjust the size automatically. // * // * @return true when the API should set the socket buffer sizes, // * false when it should let the kernel decide. // */ // public Boolean setSocketBufferSize() { // return this.setSocketBufferSize; // } // // /** // * Should the size of the socket buffers be explicitly set? // * When true, explicitly set the send buffer size (resp. receive buffer // * size) to {@link #sendBufferSize} (resp. {@link #receiveBufferSize}). // * When false, let the kernel adjust the size automatically. // * // * @param setSocketBufferSize // * @return this // */ // public OioHttpSettings setSocketBufferSize(Boolean setSocketBufferSize) { // this.setSocketBufferSize = setSocketBufferSize; // return this; // } // // public Integer connectTimeout() { // return connectTimeout; // } // // public OioHttpSettings connectTimeout(Integer connectTimeout) { // this.connectTimeout = connectTimeout; // return this; // } // // public Integer readTimeout() { // return readTimeout; // } // // public OioHttpSettings readTimeout(Integer readTimeout) { // this.readTimeout = readTimeout; // return this; // } // // public String userAgent() { // return userAgent; // } // // public OioHttpSettings userAgent(String userAgent) { // this.userAgent = userAgent; // return this; // } // } // // Path: src/main/java/io/openio/sds/common/Check.java // public static void checkArgument(boolean condition, String msg) { // if (!condition) // throw new IllegalArgumentException(msg); // } // Path: src/main/java/io/openio/sds/common/AbstractSocketProvider.java import static java.lang.String.format; import io.openio.sds.exceptions.OioException; import io.openio.sds.http.OioHttpSettings; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import static io.openio.sds.common.Check.checkArgument; package io.openio.sds.common; /** * * @author Florent Vennetier * */ public abstract class AbstractSocketProvider implements SocketProvider { /** * Configure an already created Socket with provided settings, and establish the connection. * * @param sock A Socket instance * @param target The address to connect the socket to * @param http The settings to apply * @throws OioException if an error occurs during connection */ protected void configureAndConnect(Socket sock, InetSocketAddress target, OioHttpSettings http) throws OioException {
checkArgument(sock != null, "'sock' argument should not be null");
open-io/oio-api-java
src/main/java/io/openio/sds/models/OioUrl.java
// Path: src/main/java/io/openio/sds/common/Check.java // public static void checkArgument(boolean condition, String msg) { // if (!condition) // throw new IllegalArgumentException(msg); // } // // Path: src/main/java/io/openio/sds/common/OioConstants.java // public static final Charset OIO_CHARSET = Charset.forName("UTF-8"); // // Path: src/main/java/io/openio/sds/common/Strings.java // public static boolean nullOrEmpty(String string) { // return null == string || 0 == string.length(); // } // // Path: src/main/java/io/openio/sds/common/Hash.java // public class Hash { // // private MessageDigest md; // // private Hash(MessageDigest md) { // this.md = md; // } // // /** // * Returns an {@link Hash} instance ready to compute a md5 hash // * // * @return an {@link Hash} instance ready to compute a md5 hash // */ // public static Hash md5() { // try { // return new Hash(MessageDigest.getInstance("MD5")); // } catch (NoSuchAlgorithmException e) { // throw new RuntimeException(e); // } // } // // /** // * Returns an {@link Hash} instance ready to compute a md5 hash // * // * @return an {@link Hash} instance ready to compute a md5 hash // */ // public static Hash sha256() { // try { // return new Hash(MessageDigest.getInstance("SHA-256")); // } catch (NoSuchAlgorithmException e) { // throw new RuntimeException(e); // } // } // // /** // * Updates the current hash with the specified bytes // * // * @param bytes // * the bytes to add // * @return this // */ // public Hash putBytes(byte[] bytes) { // this.md.update(bytes); // return this; // } // // /** // * Completes the current hash computation // * // * @return an {@link Hex} instance handling the computed hash // */ // public Hex hash() { // return Hex.fromBytes(this.md.digest()); // } // // /** // * Add a final update to the current hash and completes it // * // * @param bytes // * the final bytes to add // * @return an {@link Hex} instance handling the computed hash // */ // public Hex hashBytes(byte[] bytes) { // return Hex.fromBytes(this.md.digest(bytes)); // } // } // // Path: src/main/java/io/openio/sds/common/MoreObjects.java // public class MoreObjects { // // public static ToStringHelper toStringHelper(String name) { // return new ToStringHelper(name); // } // // public static ToStringHelper toStringHelper(Object o) { // return new ToStringHelper(o.getClass().getSimpleName()); // } // // public static class ToStringHelper { // // private String name; // private HashMap<String, Object> fields = new HashMap<String, Object>(); // private boolean skipNulls = false; // // private ToStringHelper(String name) { // this.name = name; // } // // public ToStringHelper add(String key, Object value) { // if (null != key && (null != value || !skipNulls)) // fields.put(key, value); // return this; // } // // public ToStringHelper omitNullValues(){ // this.skipNulls = true; // return this; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(name) // .append("={"); // for (Entry<String, Object> e : fields.entrySet()) { // sb.append("\"") // .append(e.getKey()) // .append("\":\"") // .append(e.getValue()) // .append("\","); // } // // return sb.replace(sb.length() - 1, sb.length(), "}") // .toString(); // } // } // }
import static io.openio.sds.common.Check.checkArgument; import static io.openio.sds.common.OioConstants.OIO_CHARSET; import static io.openio.sds.common.Strings.nullOrEmpty; import io.openio.sds.common.Hash; import io.openio.sds.common.MoreObjects;
package io.openio.sds.models; /** * * * */ public class OioUrl { private static final byte[] BACK_ZERO = { '\0' }; private String ns; private String account; private String container; private String cid; private String object; private OioUrl(String ns, String account, String container, String cid, String object) { this.ns = ns; this.account = account; this.container = container; this.cid = cid; this.object = object; } public static OioUrl url(String account, String container) { return url(account, container, null); } public static OioUrl url(String account, String container, String object) {
// Path: src/main/java/io/openio/sds/common/Check.java // public static void checkArgument(boolean condition, String msg) { // if (!condition) // throw new IllegalArgumentException(msg); // } // // Path: src/main/java/io/openio/sds/common/OioConstants.java // public static final Charset OIO_CHARSET = Charset.forName("UTF-8"); // // Path: src/main/java/io/openio/sds/common/Strings.java // public static boolean nullOrEmpty(String string) { // return null == string || 0 == string.length(); // } // // Path: src/main/java/io/openio/sds/common/Hash.java // public class Hash { // // private MessageDigest md; // // private Hash(MessageDigest md) { // this.md = md; // } // // /** // * Returns an {@link Hash} instance ready to compute a md5 hash // * // * @return an {@link Hash} instance ready to compute a md5 hash // */ // public static Hash md5() { // try { // return new Hash(MessageDigest.getInstance("MD5")); // } catch (NoSuchAlgorithmException e) { // throw new RuntimeException(e); // } // } // // /** // * Returns an {@link Hash} instance ready to compute a md5 hash // * // * @return an {@link Hash} instance ready to compute a md5 hash // */ // public static Hash sha256() { // try { // return new Hash(MessageDigest.getInstance("SHA-256")); // } catch (NoSuchAlgorithmException e) { // throw new RuntimeException(e); // } // } // // /** // * Updates the current hash with the specified bytes // * // * @param bytes // * the bytes to add // * @return this // */ // public Hash putBytes(byte[] bytes) { // this.md.update(bytes); // return this; // } // // /** // * Completes the current hash computation // * // * @return an {@link Hex} instance handling the computed hash // */ // public Hex hash() { // return Hex.fromBytes(this.md.digest()); // } // // /** // * Add a final update to the current hash and completes it // * // * @param bytes // * the final bytes to add // * @return an {@link Hex} instance handling the computed hash // */ // public Hex hashBytes(byte[] bytes) { // return Hex.fromBytes(this.md.digest(bytes)); // } // } // // Path: src/main/java/io/openio/sds/common/MoreObjects.java // public class MoreObjects { // // public static ToStringHelper toStringHelper(String name) { // return new ToStringHelper(name); // } // // public static ToStringHelper toStringHelper(Object o) { // return new ToStringHelper(o.getClass().getSimpleName()); // } // // public static class ToStringHelper { // // private String name; // private HashMap<String, Object> fields = new HashMap<String, Object>(); // private boolean skipNulls = false; // // private ToStringHelper(String name) { // this.name = name; // } // // public ToStringHelper add(String key, Object value) { // if (null != key && (null != value || !skipNulls)) // fields.put(key, value); // return this; // } // // public ToStringHelper omitNullValues(){ // this.skipNulls = true; // return this; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(name) // .append("={"); // for (Entry<String, Object> e : fields.entrySet()) { // sb.append("\"") // .append(e.getKey()) // .append("\":\"") // .append(e.getValue()) // .append("\","); // } // // return sb.replace(sb.length() - 1, sb.length(), "}") // .toString(); // } // } // } // Path: src/main/java/io/openio/sds/models/OioUrl.java import static io.openio.sds.common.Check.checkArgument; import static io.openio.sds.common.OioConstants.OIO_CHARSET; import static io.openio.sds.common.Strings.nullOrEmpty; import io.openio.sds.common.Hash; import io.openio.sds.common.MoreObjects; package io.openio.sds.models; /** * * * */ public class OioUrl { private static final byte[] BACK_ZERO = { '\0' }; private String ns; private String account; private String container; private String cid; private String object; private OioUrl(String ns, String account, String container, String cid, String object) { this.ns = ns; this.account = account; this.container = container; this.cid = cid; this.object = object; } public static OioUrl url(String account, String container) { return url(account, container, null); } public static OioUrl url(String account, String container, String object) {
checkArgument(!nullOrEmpty(account),
open-io/oio-api-java
src/main/java/io/openio/sds/models/OioUrl.java
// Path: src/main/java/io/openio/sds/common/Check.java // public static void checkArgument(boolean condition, String msg) { // if (!condition) // throw new IllegalArgumentException(msg); // } // // Path: src/main/java/io/openio/sds/common/OioConstants.java // public static final Charset OIO_CHARSET = Charset.forName("UTF-8"); // // Path: src/main/java/io/openio/sds/common/Strings.java // public static boolean nullOrEmpty(String string) { // return null == string || 0 == string.length(); // } // // Path: src/main/java/io/openio/sds/common/Hash.java // public class Hash { // // private MessageDigest md; // // private Hash(MessageDigest md) { // this.md = md; // } // // /** // * Returns an {@link Hash} instance ready to compute a md5 hash // * // * @return an {@link Hash} instance ready to compute a md5 hash // */ // public static Hash md5() { // try { // return new Hash(MessageDigest.getInstance("MD5")); // } catch (NoSuchAlgorithmException e) { // throw new RuntimeException(e); // } // } // // /** // * Returns an {@link Hash} instance ready to compute a md5 hash // * // * @return an {@link Hash} instance ready to compute a md5 hash // */ // public static Hash sha256() { // try { // return new Hash(MessageDigest.getInstance("SHA-256")); // } catch (NoSuchAlgorithmException e) { // throw new RuntimeException(e); // } // } // // /** // * Updates the current hash with the specified bytes // * // * @param bytes // * the bytes to add // * @return this // */ // public Hash putBytes(byte[] bytes) { // this.md.update(bytes); // return this; // } // // /** // * Completes the current hash computation // * // * @return an {@link Hex} instance handling the computed hash // */ // public Hex hash() { // return Hex.fromBytes(this.md.digest()); // } // // /** // * Add a final update to the current hash and completes it // * // * @param bytes // * the final bytes to add // * @return an {@link Hex} instance handling the computed hash // */ // public Hex hashBytes(byte[] bytes) { // return Hex.fromBytes(this.md.digest(bytes)); // } // } // // Path: src/main/java/io/openio/sds/common/MoreObjects.java // public class MoreObjects { // // public static ToStringHelper toStringHelper(String name) { // return new ToStringHelper(name); // } // // public static ToStringHelper toStringHelper(Object o) { // return new ToStringHelper(o.getClass().getSimpleName()); // } // // public static class ToStringHelper { // // private String name; // private HashMap<String, Object> fields = new HashMap<String, Object>(); // private boolean skipNulls = false; // // private ToStringHelper(String name) { // this.name = name; // } // // public ToStringHelper add(String key, Object value) { // if (null != key && (null != value || !skipNulls)) // fields.put(key, value); // return this; // } // // public ToStringHelper omitNullValues(){ // this.skipNulls = true; // return this; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(name) // .append("={"); // for (Entry<String, Object> e : fields.entrySet()) { // sb.append("\"") // .append(e.getKey()) // .append("\":\"") // .append(e.getValue()) // .append("\","); // } // // return sb.replace(sb.length() - 1, sb.length(), "}") // .toString(); // } // } // }
import static io.openio.sds.common.Check.checkArgument; import static io.openio.sds.common.OioConstants.OIO_CHARSET; import static io.openio.sds.common.Strings.nullOrEmpty; import io.openio.sds.common.Hash; import io.openio.sds.common.MoreObjects;
package io.openio.sds.models; /** * * * */ public class OioUrl { private static final byte[] BACK_ZERO = { '\0' }; private String ns; private String account; private String container; private String cid; private String object; private OioUrl(String ns, String account, String container, String cid, String object) { this.ns = ns; this.account = account; this.container = container; this.cid = cid; this.object = object; } public static OioUrl url(String account, String container) { return url(account, container, null); } public static OioUrl url(String account, String container, String object) {
// Path: src/main/java/io/openio/sds/common/Check.java // public static void checkArgument(boolean condition, String msg) { // if (!condition) // throw new IllegalArgumentException(msg); // } // // Path: src/main/java/io/openio/sds/common/OioConstants.java // public static final Charset OIO_CHARSET = Charset.forName("UTF-8"); // // Path: src/main/java/io/openio/sds/common/Strings.java // public static boolean nullOrEmpty(String string) { // return null == string || 0 == string.length(); // } // // Path: src/main/java/io/openio/sds/common/Hash.java // public class Hash { // // private MessageDigest md; // // private Hash(MessageDigest md) { // this.md = md; // } // // /** // * Returns an {@link Hash} instance ready to compute a md5 hash // * // * @return an {@link Hash} instance ready to compute a md5 hash // */ // public static Hash md5() { // try { // return new Hash(MessageDigest.getInstance("MD5")); // } catch (NoSuchAlgorithmException e) { // throw new RuntimeException(e); // } // } // // /** // * Returns an {@link Hash} instance ready to compute a md5 hash // * // * @return an {@link Hash} instance ready to compute a md5 hash // */ // public static Hash sha256() { // try { // return new Hash(MessageDigest.getInstance("SHA-256")); // } catch (NoSuchAlgorithmException e) { // throw new RuntimeException(e); // } // } // // /** // * Updates the current hash with the specified bytes // * // * @param bytes // * the bytes to add // * @return this // */ // public Hash putBytes(byte[] bytes) { // this.md.update(bytes); // return this; // } // // /** // * Completes the current hash computation // * // * @return an {@link Hex} instance handling the computed hash // */ // public Hex hash() { // return Hex.fromBytes(this.md.digest()); // } // // /** // * Add a final update to the current hash and completes it // * // * @param bytes // * the final bytes to add // * @return an {@link Hex} instance handling the computed hash // */ // public Hex hashBytes(byte[] bytes) { // return Hex.fromBytes(this.md.digest(bytes)); // } // } // // Path: src/main/java/io/openio/sds/common/MoreObjects.java // public class MoreObjects { // // public static ToStringHelper toStringHelper(String name) { // return new ToStringHelper(name); // } // // public static ToStringHelper toStringHelper(Object o) { // return new ToStringHelper(o.getClass().getSimpleName()); // } // // public static class ToStringHelper { // // private String name; // private HashMap<String, Object> fields = new HashMap<String, Object>(); // private boolean skipNulls = false; // // private ToStringHelper(String name) { // this.name = name; // } // // public ToStringHelper add(String key, Object value) { // if (null != key && (null != value || !skipNulls)) // fields.put(key, value); // return this; // } // // public ToStringHelper omitNullValues(){ // this.skipNulls = true; // return this; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(name) // .append("={"); // for (Entry<String, Object> e : fields.entrySet()) { // sb.append("\"") // .append(e.getKey()) // .append("\":\"") // .append(e.getValue()) // .append("\","); // } // // return sb.replace(sb.length() - 1, sb.length(), "}") // .toString(); // } // } // } // Path: src/main/java/io/openio/sds/models/OioUrl.java import static io.openio.sds.common.Check.checkArgument; import static io.openio.sds.common.OioConstants.OIO_CHARSET; import static io.openio.sds.common.Strings.nullOrEmpty; import io.openio.sds.common.Hash; import io.openio.sds.common.MoreObjects; package io.openio.sds.models; /** * * * */ public class OioUrl { private static final byte[] BACK_ZERO = { '\0' }; private String ns; private String account; private String container; private String cid; private String object; private OioUrl(String ns, String account, String container, String cid, String object) { this.ns = ns; this.account = account; this.container = container; this.cid = cid; this.object = object; } public static OioUrl url(String account, String container) { return url(account, container, null); } public static OioUrl url(String account, String container, String object) {
checkArgument(!nullOrEmpty(account),
open-io/oio-api-java
src/main/java/io/openio/sds/models/OioUrl.java
// Path: src/main/java/io/openio/sds/common/Check.java // public static void checkArgument(boolean condition, String msg) { // if (!condition) // throw new IllegalArgumentException(msg); // } // // Path: src/main/java/io/openio/sds/common/OioConstants.java // public static final Charset OIO_CHARSET = Charset.forName("UTF-8"); // // Path: src/main/java/io/openio/sds/common/Strings.java // public static boolean nullOrEmpty(String string) { // return null == string || 0 == string.length(); // } // // Path: src/main/java/io/openio/sds/common/Hash.java // public class Hash { // // private MessageDigest md; // // private Hash(MessageDigest md) { // this.md = md; // } // // /** // * Returns an {@link Hash} instance ready to compute a md5 hash // * // * @return an {@link Hash} instance ready to compute a md5 hash // */ // public static Hash md5() { // try { // return new Hash(MessageDigest.getInstance("MD5")); // } catch (NoSuchAlgorithmException e) { // throw new RuntimeException(e); // } // } // // /** // * Returns an {@link Hash} instance ready to compute a md5 hash // * // * @return an {@link Hash} instance ready to compute a md5 hash // */ // public static Hash sha256() { // try { // return new Hash(MessageDigest.getInstance("SHA-256")); // } catch (NoSuchAlgorithmException e) { // throw new RuntimeException(e); // } // } // // /** // * Updates the current hash with the specified bytes // * // * @param bytes // * the bytes to add // * @return this // */ // public Hash putBytes(byte[] bytes) { // this.md.update(bytes); // return this; // } // // /** // * Completes the current hash computation // * // * @return an {@link Hex} instance handling the computed hash // */ // public Hex hash() { // return Hex.fromBytes(this.md.digest()); // } // // /** // * Add a final update to the current hash and completes it // * // * @param bytes // * the final bytes to add // * @return an {@link Hex} instance handling the computed hash // */ // public Hex hashBytes(byte[] bytes) { // return Hex.fromBytes(this.md.digest(bytes)); // } // } // // Path: src/main/java/io/openio/sds/common/MoreObjects.java // public class MoreObjects { // // public static ToStringHelper toStringHelper(String name) { // return new ToStringHelper(name); // } // // public static ToStringHelper toStringHelper(Object o) { // return new ToStringHelper(o.getClass().getSimpleName()); // } // // public static class ToStringHelper { // // private String name; // private HashMap<String, Object> fields = new HashMap<String, Object>(); // private boolean skipNulls = false; // // private ToStringHelper(String name) { // this.name = name; // } // // public ToStringHelper add(String key, Object value) { // if (null != key && (null != value || !skipNulls)) // fields.put(key, value); // return this; // } // // public ToStringHelper omitNullValues(){ // this.skipNulls = true; // return this; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(name) // .append("={"); // for (Entry<String, Object> e : fields.entrySet()) { // sb.append("\"") // .append(e.getKey()) // .append("\":\"") // .append(e.getValue()) // .append("\","); // } // // return sb.replace(sb.length() - 1, sb.length(), "}") // .toString(); // } // } // }
import static io.openio.sds.common.Check.checkArgument; import static io.openio.sds.common.OioConstants.OIO_CHARSET; import static io.openio.sds.common.Strings.nullOrEmpty; import io.openio.sds.common.Hash; import io.openio.sds.common.MoreObjects;
public OioUrl account(String account) { this.account = account; return this; } public String container() { return container; } public OioUrl container(String container) { this.container = container; return this; } public String object() { return object; } public OioUrl object(String object) { this.object = object; return this; } public String cid() { return cid; } @Override public String toString() {
// Path: src/main/java/io/openio/sds/common/Check.java // public static void checkArgument(boolean condition, String msg) { // if (!condition) // throw new IllegalArgumentException(msg); // } // // Path: src/main/java/io/openio/sds/common/OioConstants.java // public static final Charset OIO_CHARSET = Charset.forName("UTF-8"); // // Path: src/main/java/io/openio/sds/common/Strings.java // public static boolean nullOrEmpty(String string) { // return null == string || 0 == string.length(); // } // // Path: src/main/java/io/openio/sds/common/Hash.java // public class Hash { // // private MessageDigest md; // // private Hash(MessageDigest md) { // this.md = md; // } // // /** // * Returns an {@link Hash} instance ready to compute a md5 hash // * // * @return an {@link Hash} instance ready to compute a md5 hash // */ // public static Hash md5() { // try { // return new Hash(MessageDigest.getInstance("MD5")); // } catch (NoSuchAlgorithmException e) { // throw new RuntimeException(e); // } // } // // /** // * Returns an {@link Hash} instance ready to compute a md5 hash // * // * @return an {@link Hash} instance ready to compute a md5 hash // */ // public static Hash sha256() { // try { // return new Hash(MessageDigest.getInstance("SHA-256")); // } catch (NoSuchAlgorithmException e) { // throw new RuntimeException(e); // } // } // // /** // * Updates the current hash with the specified bytes // * // * @param bytes // * the bytes to add // * @return this // */ // public Hash putBytes(byte[] bytes) { // this.md.update(bytes); // return this; // } // // /** // * Completes the current hash computation // * // * @return an {@link Hex} instance handling the computed hash // */ // public Hex hash() { // return Hex.fromBytes(this.md.digest()); // } // // /** // * Add a final update to the current hash and completes it // * // * @param bytes // * the final bytes to add // * @return an {@link Hex} instance handling the computed hash // */ // public Hex hashBytes(byte[] bytes) { // return Hex.fromBytes(this.md.digest(bytes)); // } // } // // Path: src/main/java/io/openio/sds/common/MoreObjects.java // public class MoreObjects { // // public static ToStringHelper toStringHelper(String name) { // return new ToStringHelper(name); // } // // public static ToStringHelper toStringHelper(Object o) { // return new ToStringHelper(o.getClass().getSimpleName()); // } // // public static class ToStringHelper { // // private String name; // private HashMap<String, Object> fields = new HashMap<String, Object>(); // private boolean skipNulls = false; // // private ToStringHelper(String name) { // this.name = name; // } // // public ToStringHelper add(String key, Object value) { // if (null != key && (null != value || !skipNulls)) // fields.put(key, value); // return this; // } // // public ToStringHelper omitNullValues(){ // this.skipNulls = true; // return this; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(name) // .append("={"); // for (Entry<String, Object> e : fields.entrySet()) { // sb.append("\"") // .append(e.getKey()) // .append("\":\"") // .append(e.getValue()) // .append("\","); // } // // return sb.replace(sb.length() - 1, sb.length(), "}") // .toString(); // } // } // } // Path: src/main/java/io/openio/sds/models/OioUrl.java import static io.openio.sds.common.Check.checkArgument; import static io.openio.sds.common.OioConstants.OIO_CHARSET; import static io.openio.sds.common.Strings.nullOrEmpty; import io.openio.sds.common.Hash; import io.openio.sds.common.MoreObjects; public OioUrl account(String account) { this.account = account; return this; } public String container() { return container; } public OioUrl container(String container) { this.container = container; return this; } public String object() { return object; } public OioUrl object(String object) { this.object = object; return this; } public String cid() { return cid; } @Override public String toString() {
return MoreObjects.toStringHelper(this)
open-io/oio-api-java
src/main/java/io/openio/sds/models/OioUrl.java
// Path: src/main/java/io/openio/sds/common/Check.java // public static void checkArgument(boolean condition, String msg) { // if (!condition) // throw new IllegalArgumentException(msg); // } // // Path: src/main/java/io/openio/sds/common/OioConstants.java // public static final Charset OIO_CHARSET = Charset.forName("UTF-8"); // // Path: src/main/java/io/openio/sds/common/Strings.java // public static boolean nullOrEmpty(String string) { // return null == string || 0 == string.length(); // } // // Path: src/main/java/io/openio/sds/common/Hash.java // public class Hash { // // private MessageDigest md; // // private Hash(MessageDigest md) { // this.md = md; // } // // /** // * Returns an {@link Hash} instance ready to compute a md5 hash // * // * @return an {@link Hash} instance ready to compute a md5 hash // */ // public static Hash md5() { // try { // return new Hash(MessageDigest.getInstance("MD5")); // } catch (NoSuchAlgorithmException e) { // throw new RuntimeException(e); // } // } // // /** // * Returns an {@link Hash} instance ready to compute a md5 hash // * // * @return an {@link Hash} instance ready to compute a md5 hash // */ // public static Hash sha256() { // try { // return new Hash(MessageDigest.getInstance("SHA-256")); // } catch (NoSuchAlgorithmException e) { // throw new RuntimeException(e); // } // } // // /** // * Updates the current hash with the specified bytes // * // * @param bytes // * the bytes to add // * @return this // */ // public Hash putBytes(byte[] bytes) { // this.md.update(bytes); // return this; // } // // /** // * Completes the current hash computation // * // * @return an {@link Hex} instance handling the computed hash // */ // public Hex hash() { // return Hex.fromBytes(this.md.digest()); // } // // /** // * Add a final update to the current hash and completes it // * // * @param bytes // * the final bytes to add // * @return an {@link Hex} instance handling the computed hash // */ // public Hex hashBytes(byte[] bytes) { // return Hex.fromBytes(this.md.digest(bytes)); // } // } // // Path: src/main/java/io/openio/sds/common/MoreObjects.java // public class MoreObjects { // // public static ToStringHelper toStringHelper(String name) { // return new ToStringHelper(name); // } // // public static ToStringHelper toStringHelper(Object o) { // return new ToStringHelper(o.getClass().getSimpleName()); // } // // public static class ToStringHelper { // // private String name; // private HashMap<String, Object> fields = new HashMap<String, Object>(); // private boolean skipNulls = false; // // private ToStringHelper(String name) { // this.name = name; // } // // public ToStringHelper add(String key, Object value) { // if (null != key && (null != value || !skipNulls)) // fields.put(key, value); // return this; // } // // public ToStringHelper omitNullValues(){ // this.skipNulls = true; // return this; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(name) // .append("={"); // for (Entry<String, Object> e : fields.entrySet()) { // sb.append("\"") // .append(e.getKey()) // .append("\":\"") // .append(e.getValue()) // .append("\","); // } // // return sb.replace(sb.length() - 1, sb.length(), "}") // .toString(); // } // } // }
import static io.openio.sds.common.Check.checkArgument; import static io.openio.sds.common.OioConstants.OIO_CHARSET; import static io.openio.sds.common.Strings.nullOrEmpty; import io.openio.sds.common.Hash; import io.openio.sds.common.MoreObjects;
public OioUrl object(String object) { this.object = object; return this; } public String cid() { return cid; } @Override public String toString() { return MoreObjects.toStringHelper(this) .omitNullValues() .add("namespace", ns) .add("account", account) .add("container", container) .add("object", object) .toString(); } /** * Generates the container id from the specified account and container name * * @param account * the name of the account * @param container * the name of the container * @return the generated id */ public static String cid(String account, String container) {
// Path: src/main/java/io/openio/sds/common/Check.java // public static void checkArgument(boolean condition, String msg) { // if (!condition) // throw new IllegalArgumentException(msg); // } // // Path: src/main/java/io/openio/sds/common/OioConstants.java // public static final Charset OIO_CHARSET = Charset.forName("UTF-8"); // // Path: src/main/java/io/openio/sds/common/Strings.java // public static boolean nullOrEmpty(String string) { // return null == string || 0 == string.length(); // } // // Path: src/main/java/io/openio/sds/common/Hash.java // public class Hash { // // private MessageDigest md; // // private Hash(MessageDigest md) { // this.md = md; // } // // /** // * Returns an {@link Hash} instance ready to compute a md5 hash // * // * @return an {@link Hash} instance ready to compute a md5 hash // */ // public static Hash md5() { // try { // return new Hash(MessageDigest.getInstance("MD5")); // } catch (NoSuchAlgorithmException e) { // throw new RuntimeException(e); // } // } // // /** // * Returns an {@link Hash} instance ready to compute a md5 hash // * // * @return an {@link Hash} instance ready to compute a md5 hash // */ // public static Hash sha256() { // try { // return new Hash(MessageDigest.getInstance("SHA-256")); // } catch (NoSuchAlgorithmException e) { // throw new RuntimeException(e); // } // } // // /** // * Updates the current hash with the specified bytes // * // * @param bytes // * the bytes to add // * @return this // */ // public Hash putBytes(byte[] bytes) { // this.md.update(bytes); // return this; // } // // /** // * Completes the current hash computation // * // * @return an {@link Hex} instance handling the computed hash // */ // public Hex hash() { // return Hex.fromBytes(this.md.digest()); // } // // /** // * Add a final update to the current hash and completes it // * // * @param bytes // * the final bytes to add // * @return an {@link Hex} instance handling the computed hash // */ // public Hex hashBytes(byte[] bytes) { // return Hex.fromBytes(this.md.digest(bytes)); // } // } // // Path: src/main/java/io/openio/sds/common/MoreObjects.java // public class MoreObjects { // // public static ToStringHelper toStringHelper(String name) { // return new ToStringHelper(name); // } // // public static ToStringHelper toStringHelper(Object o) { // return new ToStringHelper(o.getClass().getSimpleName()); // } // // public static class ToStringHelper { // // private String name; // private HashMap<String, Object> fields = new HashMap<String, Object>(); // private boolean skipNulls = false; // // private ToStringHelper(String name) { // this.name = name; // } // // public ToStringHelper add(String key, Object value) { // if (null != key && (null != value || !skipNulls)) // fields.put(key, value); // return this; // } // // public ToStringHelper omitNullValues(){ // this.skipNulls = true; // return this; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(name) // .append("={"); // for (Entry<String, Object> e : fields.entrySet()) { // sb.append("\"") // .append(e.getKey()) // .append("\":\"") // .append(e.getValue()) // .append("\","); // } // // return sb.replace(sb.length() - 1, sb.length(), "}") // .toString(); // } // } // } // Path: src/main/java/io/openio/sds/models/OioUrl.java import static io.openio.sds.common.Check.checkArgument; import static io.openio.sds.common.OioConstants.OIO_CHARSET; import static io.openio.sds.common.Strings.nullOrEmpty; import io.openio.sds.common.Hash; import io.openio.sds.common.MoreObjects; public OioUrl object(String object) { this.object = object; return this; } public String cid() { return cid; } @Override public String toString() { return MoreObjects.toStringHelper(this) .omitNullValues() .add("namespace", ns) .add("account", account) .add("container", container) .add("object", object) .toString(); } /** * Generates the container id from the specified account and container name * * @param account * the name of the account * @param container * the name of the container * @return the generated id */ public static String cid(String account, String container) {
return Hash.sha256()
open-io/oio-api-java
src/main/java/io/openio/sds/models/OioUrl.java
// Path: src/main/java/io/openio/sds/common/Check.java // public static void checkArgument(boolean condition, String msg) { // if (!condition) // throw new IllegalArgumentException(msg); // } // // Path: src/main/java/io/openio/sds/common/OioConstants.java // public static final Charset OIO_CHARSET = Charset.forName("UTF-8"); // // Path: src/main/java/io/openio/sds/common/Strings.java // public static boolean nullOrEmpty(String string) { // return null == string || 0 == string.length(); // } // // Path: src/main/java/io/openio/sds/common/Hash.java // public class Hash { // // private MessageDigest md; // // private Hash(MessageDigest md) { // this.md = md; // } // // /** // * Returns an {@link Hash} instance ready to compute a md5 hash // * // * @return an {@link Hash} instance ready to compute a md5 hash // */ // public static Hash md5() { // try { // return new Hash(MessageDigest.getInstance("MD5")); // } catch (NoSuchAlgorithmException e) { // throw new RuntimeException(e); // } // } // // /** // * Returns an {@link Hash} instance ready to compute a md5 hash // * // * @return an {@link Hash} instance ready to compute a md5 hash // */ // public static Hash sha256() { // try { // return new Hash(MessageDigest.getInstance("SHA-256")); // } catch (NoSuchAlgorithmException e) { // throw new RuntimeException(e); // } // } // // /** // * Updates the current hash with the specified bytes // * // * @param bytes // * the bytes to add // * @return this // */ // public Hash putBytes(byte[] bytes) { // this.md.update(bytes); // return this; // } // // /** // * Completes the current hash computation // * // * @return an {@link Hex} instance handling the computed hash // */ // public Hex hash() { // return Hex.fromBytes(this.md.digest()); // } // // /** // * Add a final update to the current hash and completes it // * // * @param bytes // * the final bytes to add // * @return an {@link Hex} instance handling the computed hash // */ // public Hex hashBytes(byte[] bytes) { // return Hex.fromBytes(this.md.digest(bytes)); // } // } // // Path: src/main/java/io/openio/sds/common/MoreObjects.java // public class MoreObjects { // // public static ToStringHelper toStringHelper(String name) { // return new ToStringHelper(name); // } // // public static ToStringHelper toStringHelper(Object o) { // return new ToStringHelper(o.getClass().getSimpleName()); // } // // public static class ToStringHelper { // // private String name; // private HashMap<String, Object> fields = new HashMap<String, Object>(); // private boolean skipNulls = false; // // private ToStringHelper(String name) { // this.name = name; // } // // public ToStringHelper add(String key, Object value) { // if (null != key && (null != value || !skipNulls)) // fields.put(key, value); // return this; // } // // public ToStringHelper omitNullValues(){ // this.skipNulls = true; // return this; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(name) // .append("={"); // for (Entry<String, Object> e : fields.entrySet()) { // sb.append("\"") // .append(e.getKey()) // .append("\":\"") // .append(e.getValue()) // .append("\","); // } // // return sb.replace(sb.length() - 1, sb.length(), "}") // .toString(); // } // } // }
import static io.openio.sds.common.Check.checkArgument; import static io.openio.sds.common.OioConstants.OIO_CHARSET; import static io.openio.sds.common.Strings.nullOrEmpty; import io.openio.sds.common.Hash; import io.openio.sds.common.MoreObjects;
this.object = object; return this; } public String cid() { return cid; } @Override public String toString() { return MoreObjects.toStringHelper(this) .omitNullValues() .add("namespace", ns) .add("account", account) .add("container", container) .add("object", object) .toString(); } /** * Generates the container id from the specified account and container name * * @param account * the name of the account * @param container * the name of the container * @return the generated id */ public static String cid(String account, String container) { return Hash.sha256()
// Path: src/main/java/io/openio/sds/common/Check.java // public static void checkArgument(boolean condition, String msg) { // if (!condition) // throw new IllegalArgumentException(msg); // } // // Path: src/main/java/io/openio/sds/common/OioConstants.java // public static final Charset OIO_CHARSET = Charset.forName("UTF-8"); // // Path: src/main/java/io/openio/sds/common/Strings.java // public static boolean nullOrEmpty(String string) { // return null == string || 0 == string.length(); // } // // Path: src/main/java/io/openio/sds/common/Hash.java // public class Hash { // // private MessageDigest md; // // private Hash(MessageDigest md) { // this.md = md; // } // // /** // * Returns an {@link Hash} instance ready to compute a md5 hash // * // * @return an {@link Hash} instance ready to compute a md5 hash // */ // public static Hash md5() { // try { // return new Hash(MessageDigest.getInstance("MD5")); // } catch (NoSuchAlgorithmException e) { // throw new RuntimeException(e); // } // } // // /** // * Returns an {@link Hash} instance ready to compute a md5 hash // * // * @return an {@link Hash} instance ready to compute a md5 hash // */ // public static Hash sha256() { // try { // return new Hash(MessageDigest.getInstance("SHA-256")); // } catch (NoSuchAlgorithmException e) { // throw new RuntimeException(e); // } // } // // /** // * Updates the current hash with the specified bytes // * // * @param bytes // * the bytes to add // * @return this // */ // public Hash putBytes(byte[] bytes) { // this.md.update(bytes); // return this; // } // // /** // * Completes the current hash computation // * // * @return an {@link Hex} instance handling the computed hash // */ // public Hex hash() { // return Hex.fromBytes(this.md.digest()); // } // // /** // * Add a final update to the current hash and completes it // * // * @param bytes // * the final bytes to add // * @return an {@link Hex} instance handling the computed hash // */ // public Hex hashBytes(byte[] bytes) { // return Hex.fromBytes(this.md.digest(bytes)); // } // } // // Path: src/main/java/io/openio/sds/common/MoreObjects.java // public class MoreObjects { // // public static ToStringHelper toStringHelper(String name) { // return new ToStringHelper(name); // } // // public static ToStringHelper toStringHelper(Object o) { // return new ToStringHelper(o.getClass().getSimpleName()); // } // // public static class ToStringHelper { // // private String name; // private HashMap<String, Object> fields = new HashMap<String, Object>(); // private boolean skipNulls = false; // // private ToStringHelper(String name) { // this.name = name; // } // // public ToStringHelper add(String key, Object value) { // if (null != key && (null != value || !skipNulls)) // fields.put(key, value); // return this; // } // // public ToStringHelper omitNullValues(){ // this.skipNulls = true; // return this; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(name) // .append("={"); // for (Entry<String, Object> e : fields.entrySet()) { // sb.append("\"") // .append(e.getKey()) // .append("\":\"") // .append(e.getValue()) // .append("\","); // } // // return sb.replace(sb.length() - 1, sb.length(), "}") // .toString(); // } // } // } // Path: src/main/java/io/openio/sds/models/OioUrl.java import static io.openio.sds.common.Check.checkArgument; import static io.openio.sds.common.OioConstants.OIO_CHARSET; import static io.openio.sds.common.Strings.nullOrEmpty; import io.openio.sds.common.Hash; import io.openio.sds.common.MoreObjects; this.object = object; return this; } public String cid() { return cid; } @Override public String toString() { return MoreObjects.toStringHelper(this) .omitNullValues() .add("namespace", ns) .add("account", account) .add("container", container) .add("object", object) .toString(); } /** * Generates the container id from the specified account and container name * * @param account * the name of the account * @param container * the name of the container * @return the generated id */ public static String cid(String account, String container) { return Hash.sha256()
.putBytes(account.getBytes(OIO_CHARSET))
open-io/oio-api-java
src/main/java/io/openio/sds/models/ChunkInfo.java
// Path: src/main/java/io/openio/sds/common/MoreObjects.java // public class MoreObjects { // // public static ToStringHelper toStringHelper(String name) { // return new ToStringHelper(name); // } // // public static ToStringHelper toStringHelper(Object o) { // return new ToStringHelper(o.getClass().getSimpleName()); // } // // public static class ToStringHelper { // // private String name; // private HashMap<String, Object> fields = new HashMap<String, Object>(); // private boolean skipNulls = false; // // private ToStringHelper(String name) { // this.name = name; // } // // public ToStringHelper add(String key, Object value) { // if (null != key && (null != value || !skipNulls)) // fields.put(key, value); // return this; // } // // public ToStringHelper omitNullValues(){ // this.skipNulls = true; // return this; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(name) // .append("={"); // for (Entry<String, Object> e : fields.entrySet()) { // sb.append("\"") // .append(e.getKey()) // .append("\":\"") // .append(e.getValue()) // .append("\","); // } // // return sb.replace(sb.length() - 1, sb.length(), "}") // .toString(); // } // } // }
import io.openio.sds.common.MoreObjects;
} public ChunkInfo size(Long size) { this.size = size; return this; } public ChunkInfo hash(String hash) { this.hash = hash; return this; } public ChunkInfo pos(Position pos) { this.pos = pos; return this; } public String id(){ return url.substring(url.lastIndexOf("/") + 1); } public String finalUrl() { if (real_url != null && real_url.length() > 0) { return real_url; } return url; } @Override public String toString() {
// Path: src/main/java/io/openio/sds/common/MoreObjects.java // public class MoreObjects { // // public static ToStringHelper toStringHelper(String name) { // return new ToStringHelper(name); // } // // public static ToStringHelper toStringHelper(Object o) { // return new ToStringHelper(o.getClass().getSimpleName()); // } // // public static class ToStringHelper { // // private String name; // private HashMap<String, Object> fields = new HashMap<String, Object>(); // private boolean skipNulls = false; // // private ToStringHelper(String name) { // this.name = name; // } // // public ToStringHelper add(String key, Object value) { // if (null != key && (null != value || !skipNulls)) // fields.put(key, value); // return this; // } // // public ToStringHelper omitNullValues(){ // this.skipNulls = true; // return this; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(name) // .append("={"); // for (Entry<String, Object> e : fields.entrySet()) { // sb.append("\"") // .append(e.getKey()) // .append("\":\"") // .append(e.getValue()) // .append("\","); // } // // return sb.replace(sb.length() - 1, sb.length(), "}") // .toString(); // } // } // } // Path: src/main/java/io/openio/sds/models/ChunkInfo.java import io.openio.sds.common.MoreObjects; } public ChunkInfo size(Long size) { this.size = size; return this; } public ChunkInfo hash(String hash) { this.hash = hash; return this; } public ChunkInfo pos(Position pos) { this.pos = pos; return this; } public String id(){ return url.substring(url.lastIndexOf("/") + 1); } public String finalUrl() { if (real_url != null && real_url.length() > 0) { return real_url; } return url; } @Override public String toString() {
return MoreObjects.toStringHelper(this)
open-io/oio-api-java
src/main/java/io/openio/sds/common/IdGen.java
// Path: src/main/java/io/openio/sds/common/Hex.java // public static String toHex(byte[] bytes) { // char[] hexChars = new char[bytes.length * 2]; // for (int j = 0; j < bytes.length; j++) { // int v = bytes[j] & 0xFF; // hexChars[j * 2] = hexArray[v >>> 4]; // hexChars[j * 2 + 1] = hexArray[v & 0x0F]; // } // return new String(hexChars); // }
import static io.openio.sds.common.Hex.toHex; import java.util.Random;
package io.openio.sds.common; /** * * @author Christopher Dedeurwaerder * */ public class IdGen { private static final int REQ_ID_LENGTH = 16; private static Random rand = new Random(); /** * Generates a new random request id * @return the generated id */ public static String requestId() {
// Path: src/main/java/io/openio/sds/common/Hex.java // public static String toHex(byte[] bytes) { // char[] hexChars = new char[bytes.length * 2]; // for (int j = 0; j < bytes.length; j++) { // int v = bytes[j] & 0xFF; // hexChars[j * 2] = hexArray[v >>> 4]; // hexChars[j * 2 + 1] = hexArray[v & 0x0F]; // } // return new String(hexChars); // } // Path: src/main/java/io/openio/sds/common/IdGen.java import static io.openio.sds.common.Hex.toHex; import java.util.Random; package io.openio.sds.common; /** * * @author Christopher Dedeurwaerder * */ public class IdGen { private static final int REQ_ID_LENGTH = 16; private static Random rand = new Random(); /** * Generates a new random request id * @return the generated id */ public static String requestId() {
return toHex(bytes(REQ_ID_LENGTH));
open-io/oio-api-java
src/main/java/io/openio/sds/http/OioHttpRequest.java
// Path: src/main/java/io/openio/sds/common/OioConstants.java // public static final Charset OIO_CHARSET = Charset.forName("UTF-8"); // // Path: src/main/java/io/openio/sds/common/Strings.java // public static boolean nullOrEmpty(String string) { // return null == string || 0 == string.length(); // }
import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.util.HashMap; import java.util.Map; import static io.openio.sds.common.OioConstants.OIO_CHARSET; import static io.openio.sds.common.Strings.nullOrEmpty; import static java.lang.String.format;
package io.openio.sds.http; public class OioHttpRequest { private static final int R = 1; private static final int RN = 2; private static final int RNR = 3; private static final int RNRN = 3; private static byte BS_R = '\r'; private static byte BS_N = '\n'; private RequestHead head; private InputStream is; public OioHttpRequest(InputStream is) { this.is = is; } public static OioHttpRequest build(InputStream is) throws IOException { OioHttpRequest r = new OioHttpRequest(is); r.parseHead(); return r; } private void parseHead() throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); int state = 0; while (state < RNRN) { state = next(bos, state); } read();
// Path: src/main/java/io/openio/sds/common/OioConstants.java // public static final Charset OIO_CHARSET = Charset.forName("UTF-8"); // // Path: src/main/java/io/openio/sds/common/Strings.java // public static boolean nullOrEmpty(String string) { // return null == string || 0 == string.length(); // } // Path: src/main/java/io/openio/sds/http/OioHttpRequest.java import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.util.HashMap; import java.util.Map; import static io.openio.sds.common.OioConstants.OIO_CHARSET; import static io.openio.sds.common.Strings.nullOrEmpty; import static java.lang.String.format; package io.openio.sds.http; public class OioHttpRequest { private static final int R = 1; private static final int RN = 2; private static final int RNR = 3; private static final int RNRN = 3; private static byte BS_R = '\r'; private static byte BS_N = '\n'; private RequestHead head; private InputStream is; public OioHttpRequest(InputStream is) { this.is = is; } public static OioHttpRequest build(InputStream is) throws IOException { OioHttpRequest r = new OioHttpRequest(is); r.parseHead(); return r; } private void parseHead() throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); int state = 0; while (state < RNRN) { state = next(bos, state); } read();
head = RequestHead.parse(new String(bos.toByteArray(), OIO_CHARSET));
open-io/oio-api-java
src/main/java/io/openio/sds/http/OioHttpRequest.java
// Path: src/main/java/io/openio/sds/common/OioConstants.java // public static final Charset OIO_CHARSET = Charset.forName("UTF-8"); // // Path: src/main/java/io/openio/sds/common/Strings.java // public static boolean nullOrEmpty(String string) { // return null == string || 0 == string.length(); // }
import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.util.HashMap; import java.util.Map; import static io.openio.sds.common.OioConstants.OIO_CHARSET; import static io.openio.sds.common.Strings.nullOrEmpty; import static java.lang.String.format;
public String header(String key) { return head.headers().get(key.toLowerCase()); } public static class RequestHead { private RequestLine requestLine; private BufferedReader reader; private HashMap<String, String> headers = new HashMap<String, String>(); private RequestHead(BufferedReader reader) { this.reader = reader; } static RequestHead parse(String head) throws IOException { RequestHead h = new RequestHead(new BufferedReader(new StringReader(head))); h.parseRequestLine(); h.parseHeaders(); return h; } private void parseRequestLine() throws IOException { requestLine = RequestLine.parse(reader.readLine()); } private void parseHeaders() throws IOException { String line; while (null != (line = reader.readLine())) {
// Path: src/main/java/io/openio/sds/common/OioConstants.java // public static final Charset OIO_CHARSET = Charset.forName("UTF-8"); // // Path: src/main/java/io/openio/sds/common/Strings.java // public static boolean nullOrEmpty(String string) { // return null == string || 0 == string.length(); // } // Path: src/main/java/io/openio/sds/http/OioHttpRequest.java import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.util.HashMap; import java.util.Map; import static io.openio.sds.common.OioConstants.OIO_CHARSET; import static io.openio.sds.common.Strings.nullOrEmpty; import static java.lang.String.format; public String header(String key) { return head.headers().get(key.toLowerCase()); } public static class RequestHead { private RequestLine requestLine; private BufferedReader reader; private HashMap<String, String> headers = new HashMap<String, String>(); private RequestHead(BufferedReader reader) { this.reader = reader; } static RequestHead parse(String head) throws IOException { RequestHead h = new RequestHead(new BufferedReader(new StringReader(head))); h.parseRequestLine(); h.parseHeaders(); return h; } private void parseRequestLine() throws IOException { requestLine = RequestLine.parse(reader.readLine()); } private void parseHeaders() throws IOException { String line; while (null != (line = reader.readLine())) {
if (nullOrEmpty(line))
open-io/oio-api-java
src/main/java/io/openio/sds/storage/Target.java
// Path: src/main/java/io/openio/sds/models/ChunkInfo.java // public class ChunkInfo { // // public ChunkInfo() { // } // // private String url; // private String real_url; // private Long size; // private String hash; // private Position pos; // // public String url() { // return url; // } // // public String hash() { // return hash; // } // // public Position pos() { // return pos; // } // // public Long size() { // return size; // } // // public ChunkInfo url(String url) { // this.url = url; // return this; // } // // public ChunkInfo real_url(String real_url) { // this.real_url = real_url; // return this; // } // // public ChunkInfo size(Long size) { // this.size = size; // return this; // } // // public ChunkInfo hash(String hash) { // this.hash = hash; // return this; // } // // public ChunkInfo pos(Position pos) { // this.pos = pos; // return this; // } // // public String id(){ // return url.substring(url.lastIndexOf("/") + 1); // } // // public String finalUrl() { // if (real_url != null && real_url.length() > 0) { // return real_url; // } // return url; // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .omitNullValues() // .add("url", url) // .add("real_url", real_url) // .add("size", size) // .add("hash", hash) // .add("pos", pos) // .toString(); // } // } // // Path: src/main/java/io/openio/sds/models/Range.java // public class Range { // // private static final Pattern RANGE_PATTERN = Pattern // .compile("^([\\d]+)?-([\\d]+)?$"); // // private long from = 0; // private long to = -1; // // private Range(long from, long to) { // this.from = from; // this.to = to; // } // // public static Range upTo(long to) { // checkArgument(0 < to); // return new Range(0, to); // } // // public static Range from(long from) { // checkArgument(0 <= from); // return new Range(from, -1); // } // // public static Range between(long from, long to) { // checkArgument(from >= 0 && to > 0 && to >= from, // "Invalid range"); // return new Range(from, to); // } // // public static Range parse(String str) { // Matcher m = RANGE_PATTERN.matcher(str); // checkArgument(m.matches()); // if (null == m.group(1)) { // checkArgument(null != m.group(2), "useless range"); // return upTo(parseInt(m.group(2))); // } // return (null == m.group(2)) ? from(parseInt(m.group(1))) // : between(parseInt(m.group(1)), parseInt(m.group(2))); // } // // public long from() { // return from; // } // // public long to() { // return to; // } // // public String headerValue() { // return to < 0 // ? format("bytes=%d-", from) // : format("bytes=%d-%d", from, to); // } // // public String rangeValue() { // return to < 0 // ? format("%d-", from) // : format("%d-%d", from, to); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("from", from) // .add("to", to) // .toString(); // } // }
import java.util.List; import io.openio.sds.models.ChunkInfo; import io.openio.sds.models.Range;
package io.openio.sds.storage; /** * * @author Christopher Dedeurwaerder * */ public class Target { private List<ChunkInfo> ci;
// Path: src/main/java/io/openio/sds/models/ChunkInfo.java // public class ChunkInfo { // // public ChunkInfo() { // } // // private String url; // private String real_url; // private Long size; // private String hash; // private Position pos; // // public String url() { // return url; // } // // public String hash() { // return hash; // } // // public Position pos() { // return pos; // } // // public Long size() { // return size; // } // // public ChunkInfo url(String url) { // this.url = url; // return this; // } // // public ChunkInfo real_url(String real_url) { // this.real_url = real_url; // return this; // } // // public ChunkInfo size(Long size) { // this.size = size; // return this; // } // // public ChunkInfo hash(String hash) { // this.hash = hash; // return this; // } // // public ChunkInfo pos(Position pos) { // this.pos = pos; // return this; // } // // public String id(){ // return url.substring(url.lastIndexOf("/") + 1); // } // // public String finalUrl() { // if (real_url != null && real_url.length() > 0) { // return real_url; // } // return url; // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .omitNullValues() // .add("url", url) // .add("real_url", real_url) // .add("size", size) // .add("hash", hash) // .add("pos", pos) // .toString(); // } // } // // Path: src/main/java/io/openio/sds/models/Range.java // public class Range { // // private static final Pattern RANGE_PATTERN = Pattern // .compile("^([\\d]+)?-([\\d]+)?$"); // // private long from = 0; // private long to = -1; // // private Range(long from, long to) { // this.from = from; // this.to = to; // } // // public static Range upTo(long to) { // checkArgument(0 < to); // return new Range(0, to); // } // // public static Range from(long from) { // checkArgument(0 <= from); // return new Range(from, -1); // } // // public static Range between(long from, long to) { // checkArgument(from >= 0 && to > 0 && to >= from, // "Invalid range"); // return new Range(from, to); // } // // public static Range parse(String str) { // Matcher m = RANGE_PATTERN.matcher(str); // checkArgument(m.matches()); // if (null == m.group(1)) { // checkArgument(null != m.group(2), "useless range"); // return upTo(parseInt(m.group(2))); // } // return (null == m.group(2)) ? from(parseInt(m.group(1))) // : between(parseInt(m.group(1)), parseInt(m.group(2))); // } // // public long from() { // return from; // } // // public long to() { // return to; // } // // public String headerValue() { // return to < 0 // ? format("bytes=%d-", from) // : format("bytes=%d-%d", from, to); // } // // public String rangeValue() { // return to < 0 // ? format("%d-", from) // : format("%d-%d", from, to); // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .add("from", from) // .add("to", to) // .toString(); // } // } // Path: src/main/java/io/openio/sds/storage/Target.java import java.util.List; import io.openio.sds.models.ChunkInfo; import io.openio.sds.models.Range; package io.openio.sds.storage; /** * * @author Christopher Dedeurwaerder * */ public class Target { private List<ChunkInfo> ci;
private Range range;
open-io/oio-api-java
src/main/java/io/openio/sds/models/ListOptions.java
// Path: src/main/java/io/openio/sds/common/MoreObjects.java // public class MoreObjects { // // public static ToStringHelper toStringHelper(String name) { // return new ToStringHelper(name); // } // // public static ToStringHelper toStringHelper(Object o) { // return new ToStringHelper(o.getClass().getSimpleName()); // } // // public static class ToStringHelper { // // private String name; // private HashMap<String, Object> fields = new HashMap<String, Object>(); // private boolean skipNulls = false; // // private ToStringHelper(String name) { // this.name = name; // } // // public ToStringHelper add(String key, Object value) { // if (null != key && (null != value || !skipNulls)) // fields.put(key, value); // return this; // } // // public ToStringHelper omitNullValues(){ // this.skipNulls = true; // return this; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(name) // .append("={"); // for (Entry<String, Object> e : fields.entrySet()) { // sb.append("\"") // .append(e.getKey()) // .append("\":\"") // .append(e.getValue()) // .append("\","); // } // // return sb.replace(sb.length() - 1, sb.length(), "}") // .toString(); // } // } // }
import io.openio.sds.common.MoreObjects;
public String delimiter() { return delimiter; } public ListOptions delimiter(String delimiter) { this.delimiter = delimiter; return this; } public String prefix() { return prefix; } public ListOptions prefix(String prefix) { this.prefix = prefix; return this; } public String marker() { return marker; } public ListOptions marker(String marker) { this.marker = marker; return this; } @Override public String toString() {
// Path: src/main/java/io/openio/sds/common/MoreObjects.java // public class MoreObjects { // // public static ToStringHelper toStringHelper(String name) { // return new ToStringHelper(name); // } // // public static ToStringHelper toStringHelper(Object o) { // return new ToStringHelper(o.getClass().getSimpleName()); // } // // public static class ToStringHelper { // // private String name; // private HashMap<String, Object> fields = new HashMap<String, Object>(); // private boolean skipNulls = false; // // private ToStringHelper(String name) { // this.name = name; // } // // public ToStringHelper add(String key, Object value) { // if (null != key && (null != value || !skipNulls)) // fields.put(key, value); // return this; // } // // public ToStringHelper omitNullValues(){ // this.skipNulls = true; // return this; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(name) // .append("={"); // for (Entry<String, Object> e : fields.entrySet()) { // sb.append("\"") // .append(e.getKey()) // .append("\":\"") // .append(e.getValue()) // .append("\","); // } // // return sb.replace(sb.length() - 1, sb.length(), "}") // .toString(); // } // } // } // Path: src/main/java/io/openio/sds/models/ListOptions.java import io.openio.sds.common.MoreObjects; public String delimiter() { return delimiter; } public ListOptions delimiter(String delimiter) { this.delimiter = delimiter; return this; } public String prefix() { return prefix; } public ListOptions prefix(String prefix) { this.prefix = prefix; return this; } public String marker() { return marker; } public ListOptions marker(String marker) { this.marker = marker; return this; } @Override public String toString() {
return MoreObjects.toStringHelper(this)
open-io/oio-api-java
src/main/java/io/openio/sds/models/Position.java
// Path: src/main/java/io/openio/sds/common/Check.java // public static void checkArgument(boolean condition, String msg) { // if (!condition) // throw new IllegalArgumentException(msg); // }
import static io.openio.sds.common.Check.checkArgument; import java.util.regex.Matcher; import java.util.regex.Pattern;
package io.openio.sds.models; /** * * * */ public class Position { private static final Pattern POSITION_PATTERN = Pattern .compile("^([\\d]+)(\\.([\\d]+))?$"); private int meta; private int sub; private Position(int meta, int sub) { this.meta = meta; this.sub = sub; } public static Position parse(String pos) { Matcher m = POSITION_PATTERN.matcher(pos);
// Path: src/main/java/io/openio/sds/common/Check.java // public static void checkArgument(boolean condition, String msg) { // if (!condition) // throw new IllegalArgumentException(msg); // } // Path: src/main/java/io/openio/sds/models/Position.java import static io.openio.sds.common.Check.checkArgument; import java.util.regex.Matcher; import java.util.regex.Pattern; package io.openio.sds.models; /** * * * */ public class Position { private static final Pattern POSITION_PATTERN = Pattern .compile("^([\\d]+)(\\.([\\d]+))?$"); private int meta; private int sub; private Position(int meta, int sub) { this.meta = meta; this.sub = sub; } public static Position parse(String pos) { Matcher m = POSITION_PATTERN.matcher(pos);
checkArgument(m.matches(),
open-io/oio-api-java
src/main/java/io/openio/sds/models/ContainerInfo.java
// Path: src/main/java/io/openio/sds/common/MoreObjects.java // public class MoreObjects { // // public static ToStringHelper toStringHelper(String name) { // return new ToStringHelper(name); // } // // public static ToStringHelper toStringHelper(Object o) { // return new ToStringHelper(o.getClass().getSimpleName()); // } // // public static class ToStringHelper { // // private String name; // private HashMap<String, Object> fields = new HashMap<String, Object>(); // private boolean skipNulls = false; // // private ToStringHelper(String name) { // this.name = name; // } // // public ToStringHelper add(String key, Object value) { // if (null != key && (null != value || !skipNulls)) // fields.put(key, value); // return this; // } // // public ToStringHelper omitNullValues(){ // this.skipNulls = true; // return this; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(name) // .append("={"); // for (Entry<String, Object> e : fields.entrySet()) { // sb.append("\"") // .append(e.getKey()) // .append("\":\"") // .append(e.getValue()) // .append("\","); // } // // return sb.replace(sb.length() - 1, sb.length(), "}") // .toString(); // } // } // }
import io.openio.sds.common.MoreObjects;
public String versionMainChunks() { return versionMainChunks; } public ContainerInfo versionMainChunks(String versionMainChunks) { this.versionMainChunks = versionMainChunks; return this; } public String versionMainContents() { return versionMainContents; } public ContainerInfo versionMainContents(String versionMainContents) { this.versionMainContents = versionMainContents; return this; } public String versionMainProperties() { return versionMainProperties; } public ContainerInfo versionMainProperties( String versionMainProperties) { this.versionMainProperties = versionMainProperties; return this; } @Override public String toString() {
// Path: src/main/java/io/openio/sds/common/MoreObjects.java // public class MoreObjects { // // public static ToStringHelper toStringHelper(String name) { // return new ToStringHelper(name); // } // // public static ToStringHelper toStringHelper(Object o) { // return new ToStringHelper(o.getClass().getSimpleName()); // } // // public static class ToStringHelper { // // private String name; // private HashMap<String, Object> fields = new HashMap<String, Object>(); // private boolean skipNulls = false; // // private ToStringHelper(String name) { // this.name = name; // } // // public ToStringHelper add(String key, Object value) { // if (null != key && (null != value || !skipNulls)) // fields.put(key, value); // return this; // } // // public ToStringHelper omitNullValues(){ // this.skipNulls = true; // return this; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(name) // .append("={"); // for (Entry<String, Object> e : fields.entrySet()) { // sb.append("\"") // .append(e.getKey()) // .append("\":\"") // .append(e.getValue()) // .append("\","); // } // // return sb.replace(sb.length() - 1, sb.length(), "}") // .toString(); // } // } // } // Path: src/main/java/io/openio/sds/models/ContainerInfo.java import io.openio.sds.common.MoreObjects; public String versionMainChunks() { return versionMainChunks; } public ContainerInfo versionMainChunks(String versionMainChunks) { this.versionMainChunks = versionMainChunks; return this; } public String versionMainContents() { return versionMainContents; } public ContainerInfo versionMainContents(String versionMainContents) { this.versionMainContents = versionMainContents; return this; } public String versionMainProperties() { return versionMainProperties; } public ContainerInfo versionMainProperties( String versionMainProperties) { this.versionMainProperties = versionMainProperties; return this; } @Override public String toString() {
return MoreObjects.toStringHelper(this)
open-io/oio-api-java
src/main/java/io/openio/sds/models/ServiceInfo.java
// Path: src/main/java/io/openio/sds/common/MoreObjects.java // public class MoreObjects { // // public static ToStringHelper toStringHelper(String name) { // return new ToStringHelper(name); // } // // public static ToStringHelper toStringHelper(Object o) { // return new ToStringHelper(o.getClass().getSimpleName()); // } // // public static class ToStringHelper { // // private String name; // private HashMap<String, Object> fields = new HashMap<String, Object>(); // private boolean skipNulls = false; // // private ToStringHelper(String name) { // this.name = name; // } // // public ToStringHelper add(String key, Object value) { // if (null != key && (null != value || !skipNulls)) // fields.put(key, value); // return this; // } // // public ToStringHelper omitNullValues(){ // this.skipNulls = true; // return this; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(name) // .append("={"); // for (Entry<String, Object> e : fields.entrySet()) { // sb.append("\"") // .append(e.getKey()) // .append("\":\"") // .append(e.getValue()) // .append("\","); // } // // return sb.replace(sb.length() - 1, sb.length(), "}") // .toString(); // } // } // }
import java.util.Map; import io.openio.sds.common.MoreObjects;
package io.openio.sds.models; /** * * @author Christopher Dedeurwaerder * */ public class ServiceInfo { private String addr; private Integer score; private Map<String, String> tags; public ServiceInfo() { } public String addr() { return addr; } public ServiceInfo addr(String addr) { this.addr = addr; return this; } public Integer score() { return score; } public ServiceInfo score(Integer score) { this.score = score; return this; } public Map<String, String> tags() { return tags; } public ServiceInfo tags(Map<String, String> tags) { this.tags = tags; return this; } @Override public String toString(){
// Path: src/main/java/io/openio/sds/common/MoreObjects.java // public class MoreObjects { // // public static ToStringHelper toStringHelper(String name) { // return new ToStringHelper(name); // } // // public static ToStringHelper toStringHelper(Object o) { // return new ToStringHelper(o.getClass().getSimpleName()); // } // // public static class ToStringHelper { // // private String name; // private HashMap<String, Object> fields = new HashMap<String, Object>(); // private boolean skipNulls = false; // // private ToStringHelper(String name) { // this.name = name; // } // // public ToStringHelper add(String key, Object value) { // if (null != key && (null != value || !skipNulls)) // fields.put(key, value); // return this; // } // // public ToStringHelper omitNullValues(){ // this.skipNulls = true; // return this; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(name) // .append("={"); // for (Entry<String, Object> e : fields.entrySet()) { // sb.append("\"") // .append(e.getKey()) // .append("\":\"") // .append(e.getValue()) // .append("\","); // } // // return sb.replace(sb.length() - 1, sb.length(), "}") // .toString(); // } // } // } // Path: src/main/java/io/openio/sds/models/ServiceInfo.java import java.util.Map; import io.openio.sds.common.MoreObjects; package io.openio.sds.models; /** * * @author Christopher Dedeurwaerder * */ public class ServiceInfo { private String addr; private Integer score; private Map<String, String> tags; public ServiceInfo() { } public String addr() { return addr; } public ServiceInfo addr(String addr) { this.addr = addr; return this; } public Integer score() { return score; } public ServiceInfo score(Integer score) { this.score = score; return this; } public Map<String, String> tags() { return tags; } public ServiceInfo tags(Map<String, String> tags) { this.tags = tags; return this; } @Override public String toString(){
return MoreObjects.toStringHelper(this)
open-io/oio-api-java
src/main/java/io/openio/sds/RequestContext.java
// Path: src/main/java/io/openio/sds/common/Check.java // public static void checkArgument(boolean condition, String msg) { // if (!condition) // throw new IllegalArgumentException(msg); // } // // Path: src/main/java/io/openio/sds/common/DeadlineManager.java // public class DeadlineManager { // // public interface ClockSource { // /** // * // * @return the current time in milliseconds // */ // int now(); // } // // private class SystemClockSource implements ClockSource { // // public SystemClockSource() { // } // // @Override // public int now() { // return (int) (System.nanoTime() / 1000000); // } // } // // // private static volatile DeadlineManager instance = null; // // private ClockSource clock; // // private DeadlineManager() { // useSystemClockSource(); // } // // /** // * Get the single instance of {@link DeadlineManager}. // * @return the single instance of {@link DeadlineManager} // */ // public static DeadlineManager instance() { // if (instance == null) { // synchronized (DeadlineManager.class) { // if (instance == null) { // instance = new DeadlineManager(); // } // } // } // return instance; // } // // /** // * Force the DeadlineManager to use a mocked {@link ClockSource} // * @param clockSource The new clock source to use // */ // public void useMockedClockSource(ClockSource clockSource) { // this.clock = clockSource; // } // // /** // * Force the DeadlineManager to use the system monotonic clock source. // */ // public void useSystemClockSource() { // this.clock = this.new SystemClockSource(); // } // // /** // * Raise an exception when a deadline has been reached. // * // * @param deadline the deadline, in milliseconds // * @throws DeadlineReachedException when the deadline has been reached // */ // public void checkDeadline(int deadline) throws DeadlineReachedException { // checkDeadline(deadline, now()); // } // // /** // * Raise an exception when a deadline has been reached. // * // * @param deadline the deadline, in milliseconds // * @param refTime the reference time for the deadline, in milliseconds // * @throws DeadlineReachedException when the deadline has been reached // */ // public void checkDeadline(int deadline, int refTime) throws DeadlineReachedException { // int diff = deadline - refTime; // if (diff <= 0) { // throw new DeadlineReachedException(-diff); // } // } // // /** // * Convert a deadline to a timeout. // * // * @param deadline the deadline to convert, in milliseconds // * @return a timeout in milliseconds // */ // public int deadlineToTimeout(int deadline) { // return deadline - now(); // } // // /** // * Convert a deadline to a timeout. // * // * @param deadline the deadline to convert, in milliseconds // * @param refTime the reference time for the deadline, in monotonic milliseconds // * @return a timeout in milliseconds // */ // public int deadlineToTimeout(int deadline, int refTime) { // return deadline - refTime; // } // // /** // * Get the current monotonic time in milliseconds. // * // * @return The current monotonic time in milliseconds // */ // public int now() { // return clock.now(); // } // // /** // * Convert a timeout to a deadline. // * // * @param timeout the timeout in milliseconds // * @return a deadline in monotonic milliseconds // */ // public int timeoutToDeadline(int timeout) { // return timeoutToDeadline(timeout, now()); // } // // /** // * Convert a timeout to a deadline. // * // * @param timeout the timeout in milliseconds // * @param refTime the reference time for the deadline, in milliseconds // * @return a deadline in monotonic milliseconds // */ // public int timeoutToDeadline(int timeout, int refTime) { // return refTime + timeout; // } // } // // Path: src/main/java/io/openio/sds/common/IdGen.java // public class IdGen { // // private static final int REQ_ID_LENGTH = 16; // // private static Random rand = new Random(); // // /** // * Generates a new random request id // * @return the generated id // */ // public static String requestId() { // return toHex(bytes(REQ_ID_LENGTH)); // } // // private static byte[] bytes(int size){ // byte[] b = new byte[size]; // rand.nextBytes(b); // return b; // } // }
import static io.openio.sds.common.Check.checkArgument; import io.openio.sds.common.DeadlineManager; import io.openio.sds.common.IdGen;
package io.openio.sds; /** * Generic parameters and context for all OpenIO SDS requests, * including a request ID, a timeout (or deadline), etc. * * @author Florent Vennetier * */ public class RequestContext { private DeadlineManager dm; private String reqId = null; private int reqStart = -1; private int rawTimeout = -1; private int deadline = -1; /** * Build a new {@link RequestContext} with a default 30s timeout. */ public RequestContext() { this.dm = DeadlineManager.instance(); } /** * Copy constructor. Build a new {@link RequestContext} from another one. * This will keep the request ID, the timeout and the deadline (if there is one). * * @param src The {@link RequestContext} to copy. */ public RequestContext(RequestContext src) { this.withRequestId(src.requestId()); this.deadline = src.deadline; this.rawTimeout = src.rawTimeout; } /* -- Request IDs ----------------------------------------------------- */ /** * Ensure this request has an ID and it is at least 8 characters. * * @return this */ public RequestContext ensureRequestId() { if (this.reqId == null)
// Path: src/main/java/io/openio/sds/common/Check.java // public static void checkArgument(boolean condition, String msg) { // if (!condition) // throw new IllegalArgumentException(msg); // } // // Path: src/main/java/io/openio/sds/common/DeadlineManager.java // public class DeadlineManager { // // public interface ClockSource { // /** // * // * @return the current time in milliseconds // */ // int now(); // } // // private class SystemClockSource implements ClockSource { // // public SystemClockSource() { // } // // @Override // public int now() { // return (int) (System.nanoTime() / 1000000); // } // } // // // private static volatile DeadlineManager instance = null; // // private ClockSource clock; // // private DeadlineManager() { // useSystemClockSource(); // } // // /** // * Get the single instance of {@link DeadlineManager}. // * @return the single instance of {@link DeadlineManager} // */ // public static DeadlineManager instance() { // if (instance == null) { // synchronized (DeadlineManager.class) { // if (instance == null) { // instance = new DeadlineManager(); // } // } // } // return instance; // } // // /** // * Force the DeadlineManager to use a mocked {@link ClockSource} // * @param clockSource The new clock source to use // */ // public void useMockedClockSource(ClockSource clockSource) { // this.clock = clockSource; // } // // /** // * Force the DeadlineManager to use the system monotonic clock source. // */ // public void useSystemClockSource() { // this.clock = this.new SystemClockSource(); // } // // /** // * Raise an exception when a deadline has been reached. // * // * @param deadline the deadline, in milliseconds // * @throws DeadlineReachedException when the deadline has been reached // */ // public void checkDeadline(int deadline) throws DeadlineReachedException { // checkDeadline(deadline, now()); // } // // /** // * Raise an exception when a deadline has been reached. // * // * @param deadline the deadline, in milliseconds // * @param refTime the reference time for the deadline, in milliseconds // * @throws DeadlineReachedException when the deadline has been reached // */ // public void checkDeadline(int deadline, int refTime) throws DeadlineReachedException { // int diff = deadline - refTime; // if (diff <= 0) { // throw new DeadlineReachedException(-diff); // } // } // // /** // * Convert a deadline to a timeout. // * // * @param deadline the deadline to convert, in milliseconds // * @return a timeout in milliseconds // */ // public int deadlineToTimeout(int deadline) { // return deadline - now(); // } // // /** // * Convert a deadline to a timeout. // * // * @param deadline the deadline to convert, in milliseconds // * @param refTime the reference time for the deadline, in monotonic milliseconds // * @return a timeout in milliseconds // */ // public int deadlineToTimeout(int deadline, int refTime) { // return deadline - refTime; // } // // /** // * Get the current monotonic time in milliseconds. // * // * @return The current monotonic time in milliseconds // */ // public int now() { // return clock.now(); // } // // /** // * Convert a timeout to a deadline. // * // * @param timeout the timeout in milliseconds // * @return a deadline in monotonic milliseconds // */ // public int timeoutToDeadline(int timeout) { // return timeoutToDeadline(timeout, now()); // } // // /** // * Convert a timeout to a deadline. // * // * @param timeout the timeout in milliseconds // * @param refTime the reference time for the deadline, in milliseconds // * @return a deadline in monotonic milliseconds // */ // public int timeoutToDeadline(int timeout, int refTime) { // return refTime + timeout; // } // } // // Path: src/main/java/io/openio/sds/common/IdGen.java // public class IdGen { // // private static final int REQ_ID_LENGTH = 16; // // private static Random rand = new Random(); // // /** // * Generates a new random request id // * @return the generated id // */ // public static String requestId() { // return toHex(bytes(REQ_ID_LENGTH)); // } // // private static byte[] bytes(int size){ // byte[] b = new byte[size]; // rand.nextBytes(b); // return b; // } // } // Path: src/main/java/io/openio/sds/RequestContext.java import static io.openio.sds.common.Check.checkArgument; import io.openio.sds.common.DeadlineManager; import io.openio.sds.common.IdGen; package io.openio.sds; /** * Generic parameters and context for all OpenIO SDS requests, * including a request ID, a timeout (or deadline), etc. * * @author Florent Vennetier * */ public class RequestContext { private DeadlineManager dm; private String reqId = null; private int reqStart = -1; private int rawTimeout = -1; private int deadline = -1; /** * Build a new {@link RequestContext} with a default 30s timeout. */ public RequestContext() { this.dm = DeadlineManager.instance(); } /** * Copy constructor. Build a new {@link RequestContext} from another one. * This will keep the request ID, the timeout and the deadline (if there is one). * * @param src The {@link RequestContext} to copy. */ public RequestContext(RequestContext src) { this.withRequestId(src.requestId()); this.deadline = src.deadline; this.rawTimeout = src.rawTimeout; } /* -- Request IDs ----------------------------------------------------- */ /** * Ensure this request has an ID and it is at least 8 characters. * * @return this */ public RequestContext ensureRequestId() { if (this.reqId == null)
this.reqId = IdGen.requestId();
open-io/oio-api-java
src/main/java/io/openio/sds/RequestContext.java
// Path: src/main/java/io/openio/sds/common/Check.java // public static void checkArgument(boolean condition, String msg) { // if (!condition) // throw new IllegalArgumentException(msg); // } // // Path: src/main/java/io/openio/sds/common/DeadlineManager.java // public class DeadlineManager { // // public interface ClockSource { // /** // * // * @return the current time in milliseconds // */ // int now(); // } // // private class SystemClockSource implements ClockSource { // // public SystemClockSource() { // } // // @Override // public int now() { // return (int) (System.nanoTime() / 1000000); // } // } // // // private static volatile DeadlineManager instance = null; // // private ClockSource clock; // // private DeadlineManager() { // useSystemClockSource(); // } // // /** // * Get the single instance of {@link DeadlineManager}. // * @return the single instance of {@link DeadlineManager} // */ // public static DeadlineManager instance() { // if (instance == null) { // synchronized (DeadlineManager.class) { // if (instance == null) { // instance = new DeadlineManager(); // } // } // } // return instance; // } // // /** // * Force the DeadlineManager to use a mocked {@link ClockSource} // * @param clockSource The new clock source to use // */ // public void useMockedClockSource(ClockSource clockSource) { // this.clock = clockSource; // } // // /** // * Force the DeadlineManager to use the system monotonic clock source. // */ // public void useSystemClockSource() { // this.clock = this.new SystemClockSource(); // } // // /** // * Raise an exception when a deadline has been reached. // * // * @param deadline the deadline, in milliseconds // * @throws DeadlineReachedException when the deadline has been reached // */ // public void checkDeadline(int deadline) throws DeadlineReachedException { // checkDeadline(deadline, now()); // } // // /** // * Raise an exception when a deadline has been reached. // * // * @param deadline the deadline, in milliseconds // * @param refTime the reference time for the deadline, in milliseconds // * @throws DeadlineReachedException when the deadline has been reached // */ // public void checkDeadline(int deadline, int refTime) throws DeadlineReachedException { // int diff = deadline - refTime; // if (diff <= 0) { // throw new DeadlineReachedException(-diff); // } // } // // /** // * Convert a deadline to a timeout. // * // * @param deadline the deadline to convert, in milliseconds // * @return a timeout in milliseconds // */ // public int deadlineToTimeout(int deadline) { // return deadline - now(); // } // // /** // * Convert a deadline to a timeout. // * // * @param deadline the deadline to convert, in milliseconds // * @param refTime the reference time for the deadline, in monotonic milliseconds // * @return a timeout in milliseconds // */ // public int deadlineToTimeout(int deadline, int refTime) { // return deadline - refTime; // } // // /** // * Get the current monotonic time in milliseconds. // * // * @return The current monotonic time in milliseconds // */ // public int now() { // return clock.now(); // } // // /** // * Convert a timeout to a deadline. // * // * @param timeout the timeout in milliseconds // * @return a deadline in monotonic milliseconds // */ // public int timeoutToDeadline(int timeout) { // return timeoutToDeadline(timeout, now()); // } // // /** // * Convert a timeout to a deadline. // * // * @param timeout the timeout in milliseconds // * @param refTime the reference time for the deadline, in milliseconds // * @return a deadline in monotonic milliseconds // */ // public int timeoutToDeadline(int timeout, int refTime) { // return refTime + timeout; // } // } // // Path: src/main/java/io/openio/sds/common/IdGen.java // public class IdGen { // // private static final int REQ_ID_LENGTH = 16; // // private static Random rand = new Random(); // // /** // * Generates a new random request id // * @return the generated id // */ // public static String requestId() { // return toHex(bytes(REQ_ID_LENGTH)); // } // // private static byte[] bytes(int size){ // byte[] b = new byte[size]; // rand.nextBytes(b); // return b; // } // }
import static io.openio.sds.common.Check.checkArgument; import io.openio.sds.common.DeadlineManager; import io.openio.sds.common.IdGen;
public RequestContext startTiming() { this.reqStart = dm.now(); return this; } /** * Get the timeout for the request. * * If {@link #hasDeadline()} returns {@code true}, successive calls to this * method will return decreasing values, and negative values when the * deadline has been exceeded. * * @return the timeout for this request, in milliseconds */ public int timeout() { if (this.hasDeadline()) return this.dm.deadlineToTimeout(this.deadline); return this.rawTimeout; } /** * Set a deadline on the whole request. * * This will reset any previous timeout set with {@link #withTimeout(int)} to the duration * from now to the deadline. * * @param deadline the deadline in milliseconds * @return this */ public RequestContext withDeadline(int deadline) {
// Path: src/main/java/io/openio/sds/common/Check.java // public static void checkArgument(boolean condition, String msg) { // if (!condition) // throw new IllegalArgumentException(msg); // } // // Path: src/main/java/io/openio/sds/common/DeadlineManager.java // public class DeadlineManager { // // public interface ClockSource { // /** // * // * @return the current time in milliseconds // */ // int now(); // } // // private class SystemClockSource implements ClockSource { // // public SystemClockSource() { // } // // @Override // public int now() { // return (int) (System.nanoTime() / 1000000); // } // } // // // private static volatile DeadlineManager instance = null; // // private ClockSource clock; // // private DeadlineManager() { // useSystemClockSource(); // } // // /** // * Get the single instance of {@link DeadlineManager}. // * @return the single instance of {@link DeadlineManager} // */ // public static DeadlineManager instance() { // if (instance == null) { // synchronized (DeadlineManager.class) { // if (instance == null) { // instance = new DeadlineManager(); // } // } // } // return instance; // } // // /** // * Force the DeadlineManager to use a mocked {@link ClockSource} // * @param clockSource The new clock source to use // */ // public void useMockedClockSource(ClockSource clockSource) { // this.clock = clockSource; // } // // /** // * Force the DeadlineManager to use the system monotonic clock source. // */ // public void useSystemClockSource() { // this.clock = this.new SystemClockSource(); // } // // /** // * Raise an exception when a deadline has been reached. // * // * @param deadline the deadline, in milliseconds // * @throws DeadlineReachedException when the deadline has been reached // */ // public void checkDeadline(int deadline) throws DeadlineReachedException { // checkDeadline(deadline, now()); // } // // /** // * Raise an exception when a deadline has been reached. // * // * @param deadline the deadline, in milliseconds // * @param refTime the reference time for the deadline, in milliseconds // * @throws DeadlineReachedException when the deadline has been reached // */ // public void checkDeadline(int deadline, int refTime) throws DeadlineReachedException { // int diff = deadline - refTime; // if (diff <= 0) { // throw new DeadlineReachedException(-diff); // } // } // // /** // * Convert a deadline to a timeout. // * // * @param deadline the deadline to convert, in milliseconds // * @return a timeout in milliseconds // */ // public int deadlineToTimeout(int deadline) { // return deadline - now(); // } // // /** // * Convert a deadline to a timeout. // * // * @param deadline the deadline to convert, in milliseconds // * @param refTime the reference time for the deadline, in monotonic milliseconds // * @return a timeout in milliseconds // */ // public int deadlineToTimeout(int deadline, int refTime) { // return deadline - refTime; // } // // /** // * Get the current monotonic time in milliseconds. // * // * @return The current monotonic time in milliseconds // */ // public int now() { // return clock.now(); // } // // /** // * Convert a timeout to a deadline. // * // * @param timeout the timeout in milliseconds // * @return a deadline in monotonic milliseconds // */ // public int timeoutToDeadline(int timeout) { // return timeoutToDeadline(timeout, now()); // } // // /** // * Convert a timeout to a deadline. // * // * @param timeout the timeout in milliseconds // * @param refTime the reference time for the deadline, in milliseconds // * @return a deadline in monotonic milliseconds // */ // public int timeoutToDeadline(int timeout, int refTime) { // return refTime + timeout; // } // } // // Path: src/main/java/io/openio/sds/common/IdGen.java // public class IdGen { // // private static final int REQ_ID_LENGTH = 16; // // private static Random rand = new Random(); // // /** // * Generates a new random request id // * @return the generated id // */ // public static String requestId() { // return toHex(bytes(REQ_ID_LENGTH)); // } // // private static byte[] bytes(int size){ // byte[] b = new byte[size]; // rand.nextBytes(b); // return b; // } // } // Path: src/main/java/io/openio/sds/RequestContext.java import static io.openio.sds.common.Check.checkArgument; import io.openio.sds.common.DeadlineManager; import io.openio.sds.common.IdGen; public RequestContext startTiming() { this.reqStart = dm.now(); return this; } /** * Get the timeout for the request. * * If {@link #hasDeadline()} returns {@code true}, successive calls to this * method will return decreasing values, and negative values when the * deadline has been exceeded. * * @return the timeout for this request, in milliseconds */ public int timeout() { if (this.hasDeadline()) return this.dm.deadlineToTimeout(this.deadline); return this.rawTimeout; } /** * Set a deadline on the whole request. * * This will reset any previous timeout set with {@link #withTimeout(int)} to the duration * from now to the deadline. * * @param deadline the deadline in milliseconds * @return this */ public RequestContext withDeadline(int deadline) {
checkArgument(deadline >= 0, "deadline cannot be negative");
open-io/oio-api-java
src/main/java/io/openio/sds/storage/rawx/UploadResult.java
// Path: src/main/java/io/openio/sds/exceptions/OioException.java // @SuppressWarnings("deprecation") // public class OioException extends SdsException { // // /** // * // */ // private static final long serialVersionUID = 3270900242235005338L; // // public OioException(String message) { // super(message); // } // // public OioException(String message, Throwable t) { // super(message, t); // } // } // // Path: src/main/java/io/openio/sds/models/ChunkInfo.java // public class ChunkInfo { // // public ChunkInfo() { // } // // private String url; // private String real_url; // private Long size; // private String hash; // private Position pos; // // public String url() { // return url; // } // // public String hash() { // return hash; // } // // public Position pos() { // return pos; // } // // public Long size() { // return size; // } // // public ChunkInfo url(String url) { // this.url = url; // return this; // } // // public ChunkInfo real_url(String real_url) { // this.real_url = real_url; // return this; // } // // public ChunkInfo size(Long size) { // this.size = size; // return this; // } // // public ChunkInfo hash(String hash) { // this.hash = hash; // return this; // } // // public ChunkInfo pos(Position pos) { // this.pos = pos; // return this; // } // // public String id(){ // return url.substring(url.lastIndexOf("/") + 1); // } // // public String finalUrl() { // if (real_url != null && real_url.length() > 0) { // return real_url; // } // return url; // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .omitNullValues() // .add("url", url) // .add("real_url", real_url) // .add("size", size) // .add("hash", hash) // .add("pos", pos) // .toString(); // } // }
import io.openio.sds.exceptions.OioException; import io.openio.sds.models.ChunkInfo;
package io.openio.sds.storage.rawx; public class UploadResult { ChunkInfo chunkInfo;
// Path: src/main/java/io/openio/sds/exceptions/OioException.java // @SuppressWarnings("deprecation") // public class OioException extends SdsException { // // /** // * // */ // private static final long serialVersionUID = 3270900242235005338L; // // public OioException(String message) { // super(message); // } // // public OioException(String message, Throwable t) { // super(message, t); // } // } // // Path: src/main/java/io/openio/sds/models/ChunkInfo.java // public class ChunkInfo { // // public ChunkInfo() { // } // // private String url; // private String real_url; // private Long size; // private String hash; // private Position pos; // // public String url() { // return url; // } // // public String hash() { // return hash; // } // // public Position pos() { // return pos; // } // // public Long size() { // return size; // } // // public ChunkInfo url(String url) { // this.url = url; // return this; // } // // public ChunkInfo real_url(String real_url) { // this.real_url = real_url; // return this; // } // // public ChunkInfo size(Long size) { // this.size = size; // return this; // } // // public ChunkInfo hash(String hash) { // this.hash = hash; // return this; // } // // public ChunkInfo pos(Position pos) { // this.pos = pos; // return this; // } // // public String id(){ // return url.substring(url.lastIndexOf("/") + 1); // } // // public String finalUrl() { // if (real_url != null && real_url.length() > 0) { // return real_url; // } // return url; // } // // @Override // public String toString() { // return MoreObjects.toStringHelper(this) // .omitNullValues() // .add("url", url) // .add("real_url", real_url) // .add("size", size) // .add("hash", hash) // .add("pos", pos) // .toString(); // } // } // Path: src/main/java/io/openio/sds/storage/rawx/UploadResult.java import io.openio.sds.exceptions.OioException; import io.openio.sds.models.ChunkInfo; package io.openio.sds.storage.rawx; public class UploadResult { ChunkInfo chunkInfo;
OioException exception;
open-io/oio-api-java
src/main/java/io/openio/sds/common/DeadlineManager.java
// Path: src/main/java/io/openio/sds/exceptions/DeadlineReachedException.java // public class DeadlineReachedException extends OioException { // // private static final long serialVersionUID = -3825904433261832246L; // // /** // * @param message A message for the exception // */ // public DeadlineReachedException(String message) { // super(message); // } // // /** // * // * @param excess by how much time the deadline has been exceeded (milliseconds) // */ // public DeadlineReachedException(int excess) { // super("Request deadline exceeded by " + excess + " milliseconds"); // } // // public DeadlineReachedException() { // super("Request deadline reached"); // } // }
import io.openio.sds.exceptions.DeadlineReachedException;
synchronized (DeadlineManager.class) { if (instance == null) { instance = new DeadlineManager(); } } } return instance; } /** * Force the DeadlineManager to use a mocked {@link ClockSource} * @param clockSource The new clock source to use */ public void useMockedClockSource(ClockSource clockSource) { this.clock = clockSource; } /** * Force the DeadlineManager to use the system monotonic clock source. */ public void useSystemClockSource() { this.clock = this.new SystemClockSource(); } /** * Raise an exception when a deadline has been reached. * * @param deadline the deadline, in milliseconds * @throws DeadlineReachedException when the deadline has been reached */
// Path: src/main/java/io/openio/sds/exceptions/DeadlineReachedException.java // public class DeadlineReachedException extends OioException { // // private static final long serialVersionUID = -3825904433261832246L; // // /** // * @param message A message for the exception // */ // public DeadlineReachedException(String message) { // super(message); // } // // /** // * // * @param excess by how much time the deadline has been exceeded (milliseconds) // */ // public DeadlineReachedException(int excess) { // super("Request deadline exceeded by " + excess + " milliseconds"); // } // // public DeadlineReachedException() { // super("Request deadline reached"); // } // } // Path: src/main/java/io/openio/sds/common/DeadlineManager.java import io.openio.sds.exceptions.DeadlineReachedException; synchronized (DeadlineManager.class) { if (instance == null) { instance = new DeadlineManager(); } } } return instance; } /** * Force the DeadlineManager to use a mocked {@link ClockSource} * @param clockSource The new clock source to use */ public void useMockedClockSource(ClockSource clockSource) { this.clock = clockSource; } /** * Force the DeadlineManager to use the system monotonic clock source. */ public void useSystemClockSource() { this.clock = this.new SystemClockSource(); } /** * Raise an exception when a deadline has been reached. * * @param deadline the deadline, in milliseconds * @throws DeadlineReachedException when the deadline has been reached */
public void checkDeadline(int deadline) throws DeadlineReachedException {
open-io/oio-api-java
src/main/java/io/openio/sds/pool/Pool.java
// Path: src/main/java/io/openio/sds/exceptions/OioException.java // @SuppressWarnings("deprecation") // public class OioException extends SdsException { // // /** // * // */ // private static final long serialVersionUID = 3270900242235005338L; // // public OioException(String message) { // super(message); // } // // public OioException(String message, Throwable t) { // super(message, t); // } // } // // Path: src/main/java/io/openio/sds/logging/SdsLogger.java // public interface SdsLogger { // // /** // * Logs a message at {@link Level#FINEST}. // * // * @param message // * the message to log. // */ // public void trace(String message); // // /** // * Logs a throwable at {@link Level#FINEST}. The message of the Throwable // * will be the message. // * // * @param thrown // * the Throwable to log. // */ // public void trace(Throwable thrown); // // /** // * Logs message with associated throwable information at // * {@link Level#FINEST}. // * // * @param message // * the message to log // * @param thrown // * the Throwable associated to the message. // */ // public void trace(String message, Throwable thrown); // // /** // * Checks if the {@link Level#FINEST} is enabled. // * // * @return true if enabled, false otherwise. // */ // public boolean isTraceEnabled(); // // /** // * Logs a message at {@link Level#FINE}. // * // * @param message // * the message to log. // */ // public void debug(String message); // // /** // * Logs message with associated throwable information at // * {@link Level#FINE}. // * // * @param message // * the message to log // * @param thrown // * the Throwable associated to the message. // */ // public void debug(String message, Throwable thrown); // // /** // * Checks if the {@link Level#FINE} is enabled. // * // * @return true if enabled, false otherwise. // */ // public boolean isDebugEnabled(); // // /** // * Logs a message at {@link Level#INFO}. // * // * @param message // * the message to log. // */ // public void info(String message); // // /** // * Logs a message at {@link Level#WARNING}. // * // * @param message // * the message to log. // */ // public void warn(String message); // // /** // * Logs a throwable at {@link Level#WARNING}. The message of the Throwable // * will be the message. // * // * @param thrown // * the Throwable to log. // */ // public void warn(Throwable thrown); // // /** // * Logs message with associated throwable information at // * {@link Level#WARNING}. // * // * @param message // * the message to log // * @param thrown // * the Throwable associated to the message. // */ // public void warn(String message, Throwable thrown); // // /** // * Logs a message at {@link Level#SEVERE}. // * // * @param message // * the message to log. // */ // public void error(String message); // // /** // * Logs a throwable at {@link Level#SEVERE}. The message of the Throwable // * will be the message. // * // * @param thrown // * the Throwable to log. // */ // public void error(Throwable thrown); // // /** // * Logs message with associated throwable information at // * {@link Level#SEVERE}. // * // * @param message // * the message to log // * @param thrown // * the Throwable associated to the message. // */ // public void error(String message, Throwable thrown); // } // // Path: src/main/java/io/openio/sds/logging/SdsLoggerFactory.java // public class SdsLoggerFactory { // // private static int loaded = -1; // // public static SdsLogger getLogger(Class<?> c) { // ensureLoaded(); // switch (loaded) { // case 1: // return new Log4jLogger(c); // case 0: // default: // return new BaseLogger(c); // } // } // // private static void ensureLoaded() { // if (-1 == loaded) { // try { // Class.forName("org.apache.log4j.LogManager"); // loaded = 1; // } catch (ClassNotFoundException e) { // loaded = 0; // } // } // } // // }
import java.util.Iterator; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import io.openio.sds.exceptions.OioException; import io.openio.sds.logging.SdsLogger; import io.openio.sds.logging.SdsLoggerFactory;
} protected boolean timedOut(T item, long now) { return now >= item.lastUsage() + settings.idleTimeout(); } /** * @return the first item of the queue that has not timed out. */ protected T leaseLoop() { long now = monotonicMillis(); T item = q.poll(); while (item != null && this.timedOut(item, now)) { destroy(item); item = q.poll(); } return item; } public T lease() { T item = leaseLoop(); if (item == null) { item = tryCreate(); if (item == null) { try { item = q.poll(settings.maxWait(), TimeUnit.MILLISECONDS); } catch (InterruptedException e) { logger.debug("connection wait interrrupted"); } if (item == null)
// Path: src/main/java/io/openio/sds/exceptions/OioException.java // @SuppressWarnings("deprecation") // public class OioException extends SdsException { // // /** // * // */ // private static final long serialVersionUID = 3270900242235005338L; // // public OioException(String message) { // super(message); // } // // public OioException(String message, Throwable t) { // super(message, t); // } // } // // Path: src/main/java/io/openio/sds/logging/SdsLogger.java // public interface SdsLogger { // // /** // * Logs a message at {@link Level#FINEST}. // * // * @param message // * the message to log. // */ // public void trace(String message); // // /** // * Logs a throwable at {@link Level#FINEST}. The message of the Throwable // * will be the message. // * // * @param thrown // * the Throwable to log. // */ // public void trace(Throwable thrown); // // /** // * Logs message with associated throwable information at // * {@link Level#FINEST}. // * // * @param message // * the message to log // * @param thrown // * the Throwable associated to the message. // */ // public void trace(String message, Throwable thrown); // // /** // * Checks if the {@link Level#FINEST} is enabled. // * // * @return true if enabled, false otherwise. // */ // public boolean isTraceEnabled(); // // /** // * Logs a message at {@link Level#FINE}. // * // * @param message // * the message to log. // */ // public void debug(String message); // // /** // * Logs message with associated throwable information at // * {@link Level#FINE}. // * // * @param message // * the message to log // * @param thrown // * the Throwable associated to the message. // */ // public void debug(String message, Throwable thrown); // // /** // * Checks if the {@link Level#FINE} is enabled. // * // * @return true if enabled, false otherwise. // */ // public boolean isDebugEnabled(); // // /** // * Logs a message at {@link Level#INFO}. // * // * @param message // * the message to log. // */ // public void info(String message); // // /** // * Logs a message at {@link Level#WARNING}. // * // * @param message // * the message to log. // */ // public void warn(String message); // // /** // * Logs a throwable at {@link Level#WARNING}. The message of the Throwable // * will be the message. // * // * @param thrown // * the Throwable to log. // */ // public void warn(Throwable thrown); // // /** // * Logs message with associated throwable information at // * {@link Level#WARNING}. // * // * @param message // * the message to log // * @param thrown // * the Throwable associated to the message. // */ // public void warn(String message, Throwable thrown); // // /** // * Logs a message at {@link Level#SEVERE}. // * // * @param message // * the message to log. // */ // public void error(String message); // // /** // * Logs a throwable at {@link Level#SEVERE}. The message of the Throwable // * will be the message. // * // * @param thrown // * the Throwable to log. // */ // public void error(Throwable thrown); // // /** // * Logs message with associated throwable information at // * {@link Level#SEVERE}. // * // * @param message // * the message to log // * @param thrown // * the Throwable associated to the message. // */ // public void error(String message, Throwable thrown); // } // // Path: src/main/java/io/openio/sds/logging/SdsLoggerFactory.java // public class SdsLoggerFactory { // // private static int loaded = -1; // // public static SdsLogger getLogger(Class<?> c) { // ensureLoaded(); // switch (loaded) { // case 1: // return new Log4jLogger(c); // case 0: // default: // return new BaseLogger(c); // } // } // // private static void ensureLoaded() { // if (-1 == loaded) { // try { // Class.forName("org.apache.log4j.LogManager"); // loaded = 1; // } catch (ClassNotFoundException e) { // loaded = 0; // } // } // } // // } // Path: src/main/java/io/openio/sds/pool/Pool.java import java.util.Iterator; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import io.openio.sds.exceptions.OioException; import io.openio.sds.logging.SdsLogger; import io.openio.sds.logging.SdsLoggerFactory; } protected boolean timedOut(T item, long now) { return now >= item.lastUsage() + settings.idleTimeout(); } /** * @return the first item of the queue that has not timed out. */ protected T leaseLoop() { long now = monotonicMillis(); T item = q.poll(); while (item != null && this.timedOut(item, now)) { destroy(item); item = q.poll(); } return item; } public T lease() { T item = leaseLoop(); if (item == null) { item = tryCreate(); if (item == null) { try { item = q.poll(settings.maxWait(), TimeUnit.MILLISECONDS); } catch (InterruptedException e) { logger.debug("connection wait interrrupted"); } if (item == null)
throw new OioException(String.format("Unable to get pooled element"));
open-io/oio-api-java
src/test/java/io/openio/sds/proxy/ProxySettingsTest.java
// Path: src/main/java/io/openio/sds/exceptions/OioException.java // @SuppressWarnings("deprecation") // public class OioException extends SdsException { // // /** // * // */ // private static final long serialVersionUID = 3270900242235005338L; // // public OioException(String message) { // super(message); // } // // public OioException(String message, Throwable t) { // super(message, t); // } // }
import io.openio.sds.exceptions.OioException; import org.junit.Test; import java.net.InetSocketAddress; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail;
package io.openio.sds.proxy; public class ProxySettingsTest { @Test public void noURLset() { ProxySettings settings = new ProxySettings(); try { settings.url(); fail("Expected OioException");
// Path: src/main/java/io/openio/sds/exceptions/OioException.java // @SuppressWarnings("deprecation") // public class OioException extends SdsException { // // /** // * // */ // private static final long serialVersionUID = 3270900242235005338L; // // public OioException(String message) { // super(message); // } // // public OioException(String message, Throwable t) { // super(message, t); // } // } // Path: src/test/java/io/openio/sds/proxy/ProxySettingsTest.java import io.openio.sds.exceptions.OioException; import org.junit.Test; import java.net.InetSocketAddress; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; package io.openio.sds.proxy; public class ProxySettingsTest { @Test public void noURLset() { ProxySettings settings = new ProxySettings(); try { settings.url(); fail("Expected OioException");
} catch (OioException e) {
open-io/oio-api-java
src/main/java/io/openio/sds/models/Range.java
// Path: src/main/java/io/openio/sds/common/Check.java // public static void checkArgument(boolean condition, String msg) { // if (!condition) // throw new IllegalArgumentException(msg); // } // // Path: src/main/java/io/openio/sds/common/MoreObjects.java // public class MoreObjects { // // public static ToStringHelper toStringHelper(String name) { // return new ToStringHelper(name); // } // // public static ToStringHelper toStringHelper(Object o) { // return new ToStringHelper(o.getClass().getSimpleName()); // } // // public static class ToStringHelper { // // private String name; // private HashMap<String, Object> fields = new HashMap<String, Object>(); // private boolean skipNulls = false; // // private ToStringHelper(String name) { // this.name = name; // } // // public ToStringHelper add(String key, Object value) { // if (null != key && (null != value || !skipNulls)) // fields.put(key, value); // return this; // } // // public ToStringHelper omitNullValues(){ // this.skipNulls = true; // return this; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(name) // .append("={"); // for (Entry<String, Object> e : fields.entrySet()) { // sb.append("\"") // .append(e.getKey()) // .append("\":\"") // .append(e.getValue()) // .append("\","); // } // // return sb.replace(sb.length() - 1, sb.length(), "}") // .toString(); // } // } // }
import static io.openio.sds.common.Check.checkArgument; import static java.lang.Integer.parseInt; import static java.lang.String.format; import java.util.regex.Matcher; import java.util.regex.Pattern; import io.openio.sds.common.MoreObjects;
package io.openio.sds.models; public class Range { private static final Pattern RANGE_PATTERN = Pattern .compile("^([\\d]+)?-([\\d]+)?$"); private long from = 0; private long to = -1; private Range(long from, long to) { this.from = from; this.to = to; } public static Range upTo(long to) {
// Path: src/main/java/io/openio/sds/common/Check.java // public static void checkArgument(boolean condition, String msg) { // if (!condition) // throw new IllegalArgumentException(msg); // } // // Path: src/main/java/io/openio/sds/common/MoreObjects.java // public class MoreObjects { // // public static ToStringHelper toStringHelper(String name) { // return new ToStringHelper(name); // } // // public static ToStringHelper toStringHelper(Object o) { // return new ToStringHelper(o.getClass().getSimpleName()); // } // // public static class ToStringHelper { // // private String name; // private HashMap<String, Object> fields = new HashMap<String, Object>(); // private boolean skipNulls = false; // // private ToStringHelper(String name) { // this.name = name; // } // // public ToStringHelper add(String key, Object value) { // if (null != key && (null != value || !skipNulls)) // fields.put(key, value); // return this; // } // // public ToStringHelper omitNullValues(){ // this.skipNulls = true; // return this; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(name) // .append("={"); // for (Entry<String, Object> e : fields.entrySet()) { // sb.append("\"") // .append(e.getKey()) // .append("\":\"") // .append(e.getValue()) // .append("\","); // } // // return sb.replace(sb.length() - 1, sb.length(), "}") // .toString(); // } // } // } // Path: src/main/java/io/openio/sds/models/Range.java import static io.openio.sds.common.Check.checkArgument; import static java.lang.Integer.parseInt; import static java.lang.String.format; import java.util.regex.Matcher; import java.util.regex.Pattern; import io.openio.sds.common.MoreObjects; package io.openio.sds.models; public class Range { private static final Pattern RANGE_PATTERN = Pattern .compile("^([\\d]+)?-([\\d]+)?$"); private long from = 0; private long to = -1; private Range(long from, long to) { this.from = from; this.to = to; } public static Range upTo(long to) {
checkArgument(0 < to);
open-io/oio-api-java
src/main/java/io/openio/sds/models/Range.java
// Path: src/main/java/io/openio/sds/common/Check.java // public static void checkArgument(boolean condition, String msg) { // if (!condition) // throw new IllegalArgumentException(msg); // } // // Path: src/main/java/io/openio/sds/common/MoreObjects.java // public class MoreObjects { // // public static ToStringHelper toStringHelper(String name) { // return new ToStringHelper(name); // } // // public static ToStringHelper toStringHelper(Object o) { // return new ToStringHelper(o.getClass().getSimpleName()); // } // // public static class ToStringHelper { // // private String name; // private HashMap<String, Object> fields = new HashMap<String, Object>(); // private boolean skipNulls = false; // // private ToStringHelper(String name) { // this.name = name; // } // // public ToStringHelper add(String key, Object value) { // if (null != key && (null != value || !skipNulls)) // fields.put(key, value); // return this; // } // // public ToStringHelper omitNullValues(){ // this.skipNulls = true; // return this; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(name) // .append("={"); // for (Entry<String, Object> e : fields.entrySet()) { // sb.append("\"") // .append(e.getKey()) // .append("\":\"") // .append(e.getValue()) // .append("\","); // } // // return sb.replace(sb.length() - 1, sb.length(), "}") // .toString(); // } // } // }
import static io.openio.sds.common.Check.checkArgument; import static java.lang.Integer.parseInt; import static java.lang.String.format; import java.util.regex.Matcher; import java.util.regex.Pattern; import io.openio.sds.common.MoreObjects;
if (null == m.group(1)) { checkArgument(null != m.group(2), "useless range"); return upTo(parseInt(m.group(2))); } return (null == m.group(2)) ? from(parseInt(m.group(1))) : between(parseInt(m.group(1)), parseInt(m.group(2))); } public long from() { return from; } public long to() { return to; } public String headerValue() { return to < 0 ? format("bytes=%d-", from) : format("bytes=%d-%d", from, to); } public String rangeValue() { return to < 0 ? format("%d-", from) : format("%d-%d", from, to); } @Override public String toString() {
// Path: src/main/java/io/openio/sds/common/Check.java // public static void checkArgument(boolean condition, String msg) { // if (!condition) // throw new IllegalArgumentException(msg); // } // // Path: src/main/java/io/openio/sds/common/MoreObjects.java // public class MoreObjects { // // public static ToStringHelper toStringHelper(String name) { // return new ToStringHelper(name); // } // // public static ToStringHelper toStringHelper(Object o) { // return new ToStringHelper(o.getClass().getSimpleName()); // } // // public static class ToStringHelper { // // private String name; // private HashMap<String, Object> fields = new HashMap<String, Object>(); // private boolean skipNulls = false; // // private ToStringHelper(String name) { // this.name = name; // } // // public ToStringHelper add(String key, Object value) { // if (null != key && (null != value || !skipNulls)) // fields.put(key, value); // return this; // } // // public ToStringHelper omitNullValues(){ // this.skipNulls = true; // return this; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(name) // .append("={"); // for (Entry<String, Object> e : fields.entrySet()) { // sb.append("\"") // .append(e.getKey()) // .append("\":\"") // .append(e.getValue()) // .append("\","); // } // // return sb.replace(sb.length() - 1, sb.length(), "}") // .toString(); // } // } // } // Path: src/main/java/io/openio/sds/models/Range.java import static io.openio.sds.common.Check.checkArgument; import static java.lang.Integer.parseInt; import static java.lang.String.format; import java.util.regex.Matcher; import java.util.regex.Pattern; import io.openio.sds.common.MoreObjects; if (null == m.group(1)) { checkArgument(null != m.group(2), "useless range"); return upTo(parseInt(m.group(2))); } return (null == m.group(2)) ? from(parseInt(m.group(1))) : between(parseInt(m.group(1)), parseInt(m.group(2))); } public long from() { return from; } public long to() { return to; } public String headerValue() { return to < 0 ? format("bytes=%d-", from) : format("bytes=%d-%d", from, to); } public String rangeValue() { return to < 0 ? format("%d-", from) : format("%d-%d", from, to); } @Override public String toString() {
return MoreObjects.toStringHelper(this)
open-io/oio-api-java
src/main/java/io/openio/sds/models/ReferenceInfo.java
// Path: src/main/java/io/openio/sds/common/MoreObjects.java // public class MoreObjects { // // public static ToStringHelper toStringHelper(String name) { // return new ToStringHelper(name); // } // // public static ToStringHelper toStringHelper(Object o) { // return new ToStringHelper(o.getClass().getSimpleName()); // } // // public static class ToStringHelper { // // private String name; // private HashMap<String, Object> fields = new HashMap<String, Object>(); // private boolean skipNulls = false; // // private ToStringHelper(String name) { // this.name = name; // } // // public ToStringHelper add(String key, Object value) { // if (null != key && (null != value || !skipNulls)) // fields.put(key, value); // return this; // } // // public ToStringHelper omitNullValues(){ // this.skipNulls = true; // return this; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(name) // .append("={"); // for (Entry<String, Object> e : fields.entrySet()) { // sb.append("\"") // .append(e.getKey()) // .append("\":\"") // .append(e.getValue()) // .append("\","); // } // // return sb.replace(sb.length() - 1, sb.length(), "}") // .toString(); // } // } // }
import java.util.List; import io.openio.sds.common.MoreObjects;
package io.openio.sds.models; /** * * @author Christopher Dedeurwaerder * */ public class ReferenceInfo { private List<LinkedServiceInfo> dir; private List<LinkedServiceInfo> srv; public ReferenceInfo() { } public List<LinkedServiceInfo> dir() { return dir; } public ReferenceInfo dir(List<LinkedServiceInfo> dir) { this.dir = dir; return this; } public List<LinkedServiceInfo> srv() { return srv; } public ReferenceInfo srv(List<LinkedServiceInfo> srv) { this.srv = srv; return this; } @Override public String toString(){
// Path: src/main/java/io/openio/sds/common/MoreObjects.java // public class MoreObjects { // // public static ToStringHelper toStringHelper(String name) { // return new ToStringHelper(name); // } // // public static ToStringHelper toStringHelper(Object o) { // return new ToStringHelper(o.getClass().getSimpleName()); // } // // public static class ToStringHelper { // // private String name; // private HashMap<String, Object> fields = new HashMap<String, Object>(); // private boolean skipNulls = false; // // private ToStringHelper(String name) { // this.name = name; // } // // public ToStringHelper add(String key, Object value) { // if (null != key && (null != value || !skipNulls)) // fields.put(key, value); // return this; // } // // public ToStringHelper omitNullValues(){ // this.skipNulls = true; // return this; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(name) // .append("={"); // for (Entry<String, Object> e : fields.entrySet()) { // sb.append("\"") // .append(e.getKey()) // .append("\":\"") // .append(e.getValue()) // .append("\","); // } // // return sb.replace(sb.length() - 1, sb.length(), "}") // .toString(); // } // } // } // Path: src/main/java/io/openio/sds/models/ReferenceInfo.java import java.util.List; import io.openio.sds.common.MoreObjects; package io.openio.sds.models; /** * * @author Christopher Dedeurwaerder * */ public class ReferenceInfo { private List<LinkedServiceInfo> dir; private List<LinkedServiceInfo> srv; public ReferenceInfo() { } public List<LinkedServiceInfo> dir() { return dir; } public ReferenceInfo dir(List<LinkedServiceInfo> dir) { this.dir = dir; return this; } public List<LinkedServiceInfo> srv() { return srv; } public ReferenceInfo srv(List<LinkedServiceInfo> srv) { this.srv = srv; return this; } @Override public String toString(){
return MoreObjects.toStringHelper(this)
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/dimreduction/PCA.java
// Path: src/main/java/gr/iti/mklab/visual/utilities/Normalization.java // public class Normalization { // // /** // * This method applies L2 normalization on a given array of doubles. The passed vector is modified by the // * method. // * // * @param vector // * the original vector // * @return the L2 normalized vector // */ // public static double[] normalizeL2(double[] vector) { // // compute vector 2-norm // double norm2 = 0; // for (int i = 0; i < vector.length; i++) { // norm2 += vector[i] * vector[i]; // } // norm2 = (double) Math.sqrt(norm2); // // if (norm2 == 0) { // Arrays.fill(vector, 1); // } else { // for (int i = 0; i < vector.length; i++) { // vector[i] = vector[i] / norm2; // } // } // return vector; // } // // /** // * This method applies L1 normalization on a given array of doubles. The passed vector is modified by the // * method. // * // * @param vector // * the original vector // * @return the L1 normalized vector // */ // public static double[] normalizeL1(double[] vector) { // // compute vector 1-norm // double norm1 = 0; // for (int i = 0; i < vector.length; i++) { // norm1 += Math.abs(vector[i]); // } // // if (norm1 == 0) { // Arrays.fill(vector, 1.0 / vector.length); // } else { // for (int i = 0; i < vector.length; i++) { // vector[i] = vector[i] / norm1; // } // } // return vector; // } // // /** // * This method applies power normalization on a given array of doubles. The passed vector is modified by // * the method. // * // * @param vector // * the original vector // * @param aParameter // * the a parameter used // * @return the power normalized vector // */ // public static double[] normalizePower(double[] vector, double aParameter) { // for (int i = 0; i < vector.length; i++) { // vector[i] = Math.signum(vector[i]) * Math.pow(Math.abs(vector[i]), aParameter); // } // return vector; // } // // /** // * This method applies Signed Square Root (SSR) normalization (component-wise square rooting followed be // * L2 normalization) on a given array of doubles. The passed vector is modified by the method. // * // * @param vector // * the original vector // * @return the SSR normalized vector // */ // public static double[] normalizeSSR(double[] vector) { // normalizePower(vector, 0.5); // normalizeL2(vector); // return vector; // } // }
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import org.ejml.data.DenseMatrix64F; import org.ejml.factory.DecompositionFactory; import org.ejml.factory.SingularValueDecomposition; import org.ejml.ops.CommonOps; import org.ejml.ops.SingularOps; import gr.iti.mklab.visual.utilities.Normalization;
// strip off unneeded components and find the basis V_t.reshape(numComponents, sampleSize, true); } /** * Converts a vector from sample space into eigen space. If {@link #doWhitening} is true, then the vector * is also L2 normalized after projection. * * @param sampleData * Sample space vector * @return Eigen space projected vector * @throws Exception */ public double[] sampleToEigenSpace(double[] sampleData) throws Exception { if (!isPcaInitialized) { // initiallize PCA correctly! throw new Exception("PCA is not correctly initiallized!"); } if (sampleData.length != sampleSize) { throw new IllegalArgumentException("Unexpected vector length!"); } DenseMatrix64F sample = new DenseMatrix64F(sampleSize, 1, true, sampleData); DenseMatrix64F projectedSample = new DenseMatrix64F(numComponents, 1); // mean subtraction CommonOps.sub(sample, means, sample); // projection CommonOps.mult(V_t, sample, projectedSample); // whitening if (doWhitening) { // always perform this normalization step when whitening is used
// Path: src/main/java/gr/iti/mklab/visual/utilities/Normalization.java // public class Normalization { // // /** // * This method applies L2 normalization on a given array of doubles. The passed vector is modified by the // * method. // * // * @param vector // * the original vector // * @return the L2 normalized vector // */ // public static double[] normalizeL2(double[] vector) { // // compute vector 2-norm // double norm2 = 0; // for (int i = 0; i < vector.length; i++) { // norm2 += vector[i] * vector[i]; // } // norm2 = (double) Math.sqrt(norm2); // // if (norm2 == 0) { // Arrays.fill(vector, 1); // } else { // for (int i = 0; i < vector.length; i++) { // vector[i] = vector[i] / norm2; // } // } // return vector; // } // // /** // * This method applies L1 normalization on a given array of doubles. The passed vector is modified by the // * method. // * // * @param vector // * the original vector // * @return the L1 normalized vector // */ // public static double[] normalizeL1(double[] vector) { // // compute vector 1-norm // double norm1 = 0; // for (int i = 0; i < vector.length; i++) { // norm1 += Math.abs(vector[i]); // } // // if (norm1 == 0) { // Arrays.fill(vector, 1.0 / vector.length); // } else { // for (int i = 0; i < vector.length; i++) { // vector[i] = vector[i] / norm1; // } // } // return vector; // } // // /** // * This method applies power normalization on a given array of doubles. The passed vector is modified by // * the method. // * // * @param vector // * the original vector // * @param aParameter // * the a parameter used // * @return the power normalized vector // */ // public static double[] normalizePower(double[] vector, double aParameter) { // for (int i = 0; i < vector.length; i++) { // vector[i] = Math.signum(vector[i]) * Math.pow(Math.abs(vector[i]), aParameter); // } // return vector; // } // // /** // * This method applies Signed Square Root (SSR) normalization (component-wise square rooting followed be // * L2 normalization) on a given array of doubles. The passed vector is modified by the method. // * // * @param vector // * the original vector // * @return the SSR normalized vector // */ // public static double[] normalizeSSR(double[] vector) { // normalizePower(vector, 0.5); // normalizeL2(vector); // return vector; // } // } // Path: src/main/java/gr/iti/mklab/visual/dimreduction/PCA.java import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import org.ejml.data.DenseMatrix64F; import org.ejml.factory.DecompositionFactory; import org.ejml.factory.SingularValueDecomposition; import org.ejml.ops.CommonOps; import org.ejml.ops.SingularOps; import gr.iti.mklab.visual.utilities.Normalization; // strip off unneeded components and find the basis V_t.reshape(numComponents, sampleSize, true); } /** * Converts a vector from sample space into eigen space. If {@link #doWhitening} is true, then the vector * is also L2 normalized after projection. * * @param sampleData * Sample space vector * @return Eigen space projected vector * @throws Exception */ public double[] sampleToEigenSpace(double[] sampleData) throws Exception { if (!isPcaInitialized) { // initiallize PCA correctly! throw new Exception("PCA is not correctly initiallized!"); } if (sampleData.length != sampleSize) { throw new IllegalArgumentException("Unexpected vector length!"); } DenseMatrix64F sample = new DenseMatrix64F(sampleSize, 1, true, sampleData); DenseMatrix64F projectedSample = new DenseMatrix64F(numComponents, 1); // mean subtraction CommonOps.sub(sample, means, sample); // projection CommonOps.mult(V_t, sample, projectedSample); // whitening if (doWhitening) { // always perform this normalization step when whitening is used
return Normalization.normalizeL2(projectedSample.data);
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/extraction/RootSIFTExtractor.java
// Path: src/main/java/gr/iti/mklab/visual/utilities/Normalization.java // public class Normalization { // // /** // * This method applies L2 normalization on a given array of doubles. The passed vector is modified by the // * method. // * // * @param vector // * the original vector // * @return the L2 normalized vector // */ // public static double[] normalizeL2(double[] vector) { // // compute vector 2-norm // double norm2 = 0; // for (int i = 0; i < vector.length; i++) { // norm2 += vector[i] * vector[i]; // } // norm2 = (double) Math.sqrt(norm2); // // if (norm2 == 0) { // Arrays.fill(vector, 1); // } else { // for (int i = 0; i < vector.length; i++) { // vector[i] = vector[i] / norm2; // } // } // return vector; // } // // /** // * This method applies L1 normalization on a given array of doubles. The passed vector is modified by the // * method. // * // * @param vector // * the original vector // * @return the L1 normalized vector // */ // public static double[] normalizeL1(double[] vector) { // // compute vector 1-norm // double norm1 = 0; // for (int i = 0; i < vector.length; i++) { // norm1 += Math.abs(vector[i]); // } // // if (norm1 == 0) { // Arrays.fill(vector, 1.0 / vector.length); // } else { // for (int i = 0; i < vector.length; i++) { // vector[i] = vector[i] / norm1; // } // } // return vector; // } // // /** // * This method applies power normalization on a given array of doubles. The passed vector is modified by // * the method. // * // * @param vector // * the original vector // * @param aParameter // * the a parameter used // * @return the power normalized vector // */ // public static double[] normalizePower(double[] vector, double aParameter) { // for (int i = 0; i < vector.length; i++) { // vector[i] = Math.signum(vector[i]) * Math.pow(Math.abs(vector[i]), aParameter); // } // return vector; // } // // /** // * This method applies Signed Square Root (SSR) normalization (component-wise square rooting followed be // * L2 normalization) on a given array of doubles. The passed vector is modified by the method. // * // * @param vector // * the original vector // * @return the SSR normalized vector // */ // public static double[] normalizeSSR(double[] vector) { // normalizePower(vector, 0.5); // normalizeL2(vector); // return vector; // } // }
import gr.iti.mklab.visual.utilities.Normalization; import java.awt.image.BufferedImage;
package gr.iti.mklab.visual.extraction; /** * This class uses the BoofCV library for extracting RootSIFT features. * * @author Eleftherios Spyromitros-Xioufis * */ public class RootSIFTExtractor extends SIFTExtractor { /** * Constructor using default "good" settings for the detector. * * @throws Exception */ public RootSIFTExtractor() { super(-1, 1); } public RootSIFTExtractor(int maxFeaturesPerScale, float detectThreshold) { super(maxFeaturesPerScale, detectThreshold); } /** * Detects key points inside the image and computes descriptions at those points. */ protected double[][] extractFeaturesInternal(BufferedImage image) { double[][] features = super.extractFeaturesInternal(image); for (int i = 0; i < features.length; i++) {
// Path: src/main/java/gr/iti/mklab/visual/utilities/Normalization.java // public class Normalization { // // /** // * This method applies L2 normalization on a given array of doubles. The passed vector is modified by the // * method. // * // * @param vector // * the original vector // * @return the L2 normalized vector // */ // public static double[] normalizeL2(double[] vector) { // // compute vector 2-norm // double norm2 = 0; // for (int i = 0; i < vector.length; i++) { // norm2 += vector[i] * vector[i]; // } // norm2 = (double) Math.sqrt(norm2); // // if (norm2 == 0) { // Arrays.fill(vector, 1); // } else { // for (int i = 0; i < vector.length; i++) { // vector[i] = vector[i] / norm2; // } // } // return vector; // } // // /** // * This method applies L1 normalization on a given array of doubles. The passed vector is modified by the // * method. // * // * @param vector // * the original vector // * @return the L1 normalized vector // */ // public static double[] normalizeL1(double[] vector) { // // compute vector 1-norm // double norm1 = 0; // for (int i = 0; i < vector.length; i++) { // norm1 += Math.abs(vector[i]); // } // // if (norm1 == 0) { // Arrays.fill(vector, 1.0 / vector.length); // } else { // for (int i = 0; i < vector.length; i++) { // vector[i] = vector[i] / norm1; // } // } // return vector; // } // // /** // * This method applies power normalization on a given array of doubles. The passed vector is modified by // * the method. // * // * @param vector // * the original vector // * @param aParameter // * the a parameter used // * @return the power normalized vector // */ // public static double[] normalizePower(double[] vector, double aParameter) { // for (int i = 0; i < vector.length; i++) { // vector[i] = Math.signum(vector[i]) * Math.pow(Math.abs(vector[i]), aParameter); // } // return vector; // } // // /** // * This method applies Signed Square Root (SSR) normalization (component-wise square rooting followed be // * L2 normalization) on a given array of doubles. The passed vector is modified by the method. // * // * @param vector // * the original vector // * @return the SSR normalized vector // */ // public static double[] normalizeSSR(double[] vector) { // normalizePower(vector, 0.5); // normalizeL2(vector); // return vector; // } // } // Path: src/main/java/gr/iti/mklab/visual/extraction/RootSIFTExtractor.java import gr.iti.mklab.visual.utilities.Normalization; import java.awt.image.BufferedImage; package gr.iti.mklab.visual.extraction; /** * This class uses the BoofCV library for extracting RootSIFT features. * * @author Eleftherios Spyromitros-Xioufis * */ public class RootSIFTExtractor extends SIFTExtractor { /** * Constructor using default "good" settings for the detector. * * @throws Exception */ public RootSIFTExtractor() { super(-1, 1); } public RootSIFTExtractor(int maxFeaturesPerScale, float detectThreshold) { super(maxFeaturesPerScale, detectThreshold); } /** * Detects key points inside the image and computes descriptions at those points. */ protected double[][] extractFeaturesInternal(BufferedImage image) { double[][] features = super.extractFeaturesInternal(image); for (int i = 0; i < features.length; i++) {
Normalization.normalizePower(features[i], 0.5);
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/datastructures/PQ.java
// Path: src/main/java/gr/iti/mklab/visual/utilities/RandomPermutation.java // public class RandomPermutation { // // /** // * This array contains a random permutation of the indices. // */ // private int[] randomlyPermutatedIndices; // // /** // * Constructor that initializes a random permutation of the indices. // * // * @param seed // * The seed used for generating the permutation // * @param dim // * The dimensionality of the vectors that we want to randomly permute // */ // public RandomPermutation(int seed, int dim) { // Random rand = new Random(seed); // List<Integer> list = new ArrayList<Integer>(dim); // for (int i = 0; i < dim; i++) { // list.add(i); // } // java.util.Collections.shuffle(list, rand); // randomlyPermutatedIndices = new int[dim]; // for (int i = 0; i < dim; i++) { // randomlyPermutatedIndices[i] = list.get(i); // } // } // // /** // * Randomly permutes a vector using the random permutation of the indices that was created in the // * constructor. // * // * @param vector // * The initial vector // * @return The randomly permuted vector // */ // public double[] permute(double[] vector) { // double[] permuted = new double[vector.length]; // for (int i = 0; i < vector.length; i++) { // permuted[i] = vector[randomlyPermutatedIndices[i]]; // } // return permuted; // } // // public static void main(String args[]) { // RandomPermutation rp = new RandomPermutation(1, 3); // // double[] vector1 = { 1, 2, 3 }; // double[] vector2 = { 4, 5, 6 }; // // System.out.println(Arrays.toString(rp.permute(vector1))); // System.out.println(Arrays.toString(rp.permute(vector1))); // System.out.println(Arrays.toString(rp.permute(vector2))); // System.out.println(Arrays.toString(rp.permute(vector2))); // // } // } // // Path: src/main/java/gr/iti/mklab/visual/utilities/Result.java // public class Result implements Comparator<Result> { // // /** // * The distance associated with this result object. // */ // private double distance; // // /** // * The id associated with this result object. // */ // private int id; // // public Result() { // } // // /** // * Constructor // * // * @param internalId // * @param distance // */ // public Result(int internalId, double distance) { // this.id = internalId; // this.distance = distance; // } // // public int compare(Result o1, Result o2) { // if ((o1).getDistance() > (o2).getDistance()) // return -1; // else if ((o1).getDistance() < (o2).getDistance()) // return 1; // else // return 0; // } // // public double getDistance() { // return distance; // } // // public int getId() { // return id; // } // // }
import gnu.trove.list.array.TByteArrayList; import gnu.trove.list.array.TShortArrayList; import gr.iti.mklab.visual.utilities.RandomPermutation; import gr.iti.mklab.visual.utilities.RandomRotation; import gr.iti.mklab.visual.utilities.Result; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.Arrays; import com.aliasi.util.BoundedPriorityQueue; import com.sleepycat.bind.tuple.IntegerBinding; import com.sleepycat.bind.tuple.TupleBinding; import com.sleepycat.bind.tuple.TupleInput; import com.sleepycat.bind.tuple.TupleOutput; import com.sleepycat.je.Database; import com.sleepycat.je.DatabaseConfig; import com.sleepycat.je.DatabaseEntry; import com.sleepycat.je.DiskOrderedCursorConfig; import com.sleepycat.je.ForwardCursor; import com.sleepycat.je.LockMode; import com.sleepycat.je.OperationStatus;
vector = rp.permute(vector); } // transform the vector into a PQ code int[] pqCode = new int[numSubVectors]; for (int i = 0; i < numSubVectors; i++) { // take the appropriate sub-vector int fromIdex = i * subVectorLength; int toIndex = fromIdex + subVectorLength; double[] subvector = Arrays.copyOfRange(vector, fromIdex, toIndex); // assign the sub-vector to the nearest centroid of the respective sub-quantizer pqCode[i] = computeNearestProductIndex(subvector, i); } if (numProductCentroids <= 256) { byte[] pqByteCode = transformToByte(pqCode); if (loadIndexInMemory) { // append the ram-based index pqByteCodes.add(pqByteCode); } appendPersistentIndex(pqByteCode); // append the disk-based index } else { short[] pqShortCode = transformToShort(pqCode); if (loadIndexInMemory) { // append the ram-based index pqShortCodes.add(pqShortCode); } appendPersistentIndex(pqShortCode); // append the disk-based index } }
// Path: src/main/java/gr/iti/mklab/visual/utilities/RandomPermutation.java // public class RandomPermutation { // // /** // * This array contains a random permutation of the indices. // */ // private int[] randomlyPermutatedIndices; // // /** // * Constructor that initializes a random permutation of the indices. // * // * @param seed // * The seed used for generating the permutation // * @param dim // * The dimensionality of the vectors that we want to randomly permute // */ // public RandomPermutation(int seed, int dim) { // Random rand = new Random(seed); // List<Integer> list = new ArrayList<Integer>(dim); // for (int i = 0; i < dim; i++) { // list.add(i); // } // java.util.Collections.shuffle(list, rand); // randomlyPermutatedIndices = new int[dim]; // for (int i = 0; i < dim; i++) { // randomlyPermutatedIndices[i] = list.get(i); // } // } // // /** // * Randomly permutes a vector using the random permutation of the indices that was created in the // * constructor. // * // * @param vector // * The initial vector // * @return The randomly permuted vector // */ // public double[] permute(double[] vector) { // double[] permuted = new double[vector.length]; // for (int i = 0; i < vector.length; i++) { // permuted[i] = vector[randomlyPermutatedIndices[i]]; // } // return permuted; // } // // public static void main(String args[]) { // RandomPermutation rp = new RandomPermutation(1, 3); // // double[] vector1 = { 1, 2, 3 }; // double[] vector2 = { 4, 5, 6 }; // // System.out.println(Arrays.toString(rp.permute(vector1))); // System.out.println(Arrays.toString(rp.permute(vector1))); // System.out.println(Arrays.toString(rp.permute(vector2))); // System.out.println(Arrays.toString(rp.permute(vector2))); // // } // } // // Path: src/main/java/gr/iti/mklab/visual/utilities/Result.java // public class Result implements Comparator<Result> { // // /** // * The distance associated with this result object. // */ // private double distance; // // /** // * The id associated with this result object. // */ // private int id; // // public Result() { // } // // /** // * Constructor // * // * @param internalId // * @param distance // */ // public Result(int internalId, double distance) { // this.id = internalId; // this.distance = distance; // } // // public int compare(Result o1, Result o2) { // if ((o1).getDistance() > (o2).getDistance()) // return -1; // else if ((o1).getDistance() < (o2).getDistance()) // return 1; // else // return 0; // } // // public double getDistance() { // return distance; // } // // public int getId() { // return id; // } // // } // Path: src/main/java/gr/iti/mklab/visual/datastructures/PQ.java import gnu.trove.list.array.TByteArrayList; import gnu.trove.list.array.TShortArrayList; import gr.iti.mklab.visual.utilities.RandomPermutation; import gr.iti.mklab.visual.utilities.RandomRotation; import gr.iti.mklab.visual.utilities.Result; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.Arrays; import com.aliasi.util.BoundedPriorityQueue; import com.sleepycat.bind.tuple.IntegerBinding; import com.sleepycat.bind.tuple.TupleBinding; import com.sleepycat.bind.tuple.TupleInput; import com.sleepycat.bind.tuple.TupleOutput; import com.sleepycat.je.Database; import com.sleepycat.je.DatabaseConfig; import com.sleepycat.je.DatabaseEntry; import com.sleepycat.je.DiskOrderedCursorConfig; import com.sleepycat.je.ForwardCursor; import com.sleepycat.je.LockMode; import com.sleepycat.je.OperationStatus; vector = rp.permute(vector); } // transform the vector into a PQ code int[] pqCode = new int[numSubVectors]; for (int i = 0; i < numSubVectors; i++) { // take the appropriate sub-vector int fromIdex = i * subVectorLength; int toIndex = fromIdex + subVectorLength; double[] subvector = Arrays.copyOfRange(vector, fromIdex, toIndex); // assign the sub-vector to the nearest centroid of the respective sub-quantizer pqCode[i] = computeNearestProductIndex(subvector, i); } if (numProductCentroids <= 256) { byte[] pqByteCode = transformToByte(pqCode); if (loadIndexInMemory) { // append the ram-based index pqByteCodes.add(pqByteCode); } appendPersistentIndex(pqByteCode); // append the disk-based index } else { short[] pqShortCode = transformToShort(pqCode); if (loadIndexInMemory) { // append the ram-based index pqShortCodes.add(pqShortCode); } appendPersistentIndex(pqShortCode); // append the disk-based index } }
protected BoundedPriorityQueue<Result> computeNearestNeighborsInternal(int k, double[] query)
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/aggregation/AbstractFeatureAggregator.java
// Path: src/main/java/gr/iti/mklab/visual/utilities/Result.java // public class Result implements Comparator<Result> { // // /** // * The distance associated with this result object. // */ // private double distance; // // /** // * The id associated with this result object. // */ // private int id; // // public Result() { // } // // /** // * Constructor // * // * @param internalId // * @param distance // */ // public Result(int internalId, double distance) { // this.id = internalId; // this.distance = distance; // } // // public int compare(Result o1, Result o2) { // if ((o1).getDistance() > (o2).getDistance()) // return -1; // else if ((o1).getDistance() < (o2).getDistance()) // return 1; // else // return 0; // } // // public double getDistance() { // return distance; // } // // public int getId() { // return id; // } // // }
import gr.iti.mklab.visual.utilities.Result; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import com.aliasi.util.BoundedPriorityQueue;
protected double[] computeNearestCentroidIndexAndDistance(double[] descriptor) { int centroidIndex = -1; double minDistance = Double.MAX_VALUE; for (int i = 0; i < numCentroids; i++) { double distance = 0; for (int j = 0; j < descriptorLength; j++) { distance += (codebook[i][j] - descriptor[j]) * (codebook[i][j] - descriptor[j]); // when distance becomes greater than minDistance // break the inner loop and check the next centroid!!! if (distance >= minDistance) { break; } } if (distance < minDistance) { minDistance = distance; centroidIndex = i; } } return new double[] { centroidIndex, minDistance }; } /** * Returns the indices of the k centroids which are closer to the given descriptor. Can be used for soft * quantization. Fast implementation with a bounded priority queue. TO DO: early stopping! * * @param descriptor * @param k * @return */ protected int[] computeKNearestCentroids(double[] descriptor, int k) {
// Path: src/main/java/gr/iti/mklab/visual/utilities/Result.java // public class Result implements Comparator<Result> { // // /** // * The distance associated with this result object. // */ // private double distance; // // /** // * The id associated with this result object. // */ // private int id; // // public Result() { // } // // /** // * Constructor // * // * @param internalId // * @param distance // */ // public Result(int internalId, double distance) { // this.id = internalId; // this.distance = distance; // } // // public int compare(Result o1, Result o2) { // if ((o1).getDistance() > (o2).getDistance()) // return -1; // else if ((o1).getDistance() < (o2).getDistance()) // return 1; // else // return 0; // } // // public double getDistance() { // return distance; // } // // public int getId() { // return id; // } // // } // Path: src/main/java/gr/iti/mklab/visual/aggregation/AbstractFeatureAggregator.java import gr.iti.mklab.visual.utilities.Result; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import com.aliasi.util.BoundedPriorityQueue; protected double[] computeNearestCentroidIndexAndDistance(double[] descriptor) { int centroidIndex = -1; double minDistance = Double.MAX_VALUE; for (int i = 0; i < numCentroids; i++) { double distance = 0; for (int j = 0; j < descriptorLength; j++) { distance += (codebook[i][j] - descriptor[j]) * (codebook[i][j] - descriptor[j]); // when distance becomes greater than minDistance // break the inner loop and check the next centroid!!! if (distance >= minDistance) { break; } } if (distance < minDistance) { minDistance = distance; centroidIndex = i; } } return new double[] { centroidIndex, minDistance }; } /** * Returns the indices of the k centroids which are closer to the given descriptor. Can be used for soft * quantization. Fast implementation with a bounded priority queue. TO DO: early stopping! * * @param descriptor * @param k * @return */ protected int[] computeKNearestCentroids(double[] descriptor, int k) {
BoundedPriorityQueue<Result> bpq = new BoundedPriorityQueue<Result>(new Result(), k);
MKLab-ITI/multimedia-indexing
src/main/java/gr/iti/mklab/visual/datastructures/Linear.java
// Path: src/main/java/gr/iti/mklab/visual/utilities/Result.java // public class Result implements Comparator<Result> { // // /** // * The distance associated with this result object. // */ // private double distance; // // /** // * The id associated with this result object. // */ // private int id; // // public Result() { // } // // /** // * Constructor // * // * @param internalId // * @param distance // */ // public Result(int internalId, double distance) { // this.id = internalId; // this.distance = distance; // } // // public int compare(Result o1, Result o2) { // if ((o1).getDistance() > (o2).getDistance()) // return -1; // else if ((o1).getDistance() < (o2).getDistance()) // return 1; // else // return 0; // } // // public double getDistance() { // return distance; // } // // public int getId() { // return id; // } // // }
import gnu.trove.list.array.TDoubleArrayList; import gr.iti.mklab.visual.utilities.Result; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import com.aliasi.util.BoundedPriorityQueue; import com.sleepycat.bind.tuple.IntegerBinding; import com.sleepycat.bind.tuple.TupleBinding; import com.sleepycat.bind.tuple.TupleInput; import com.sleepycat.bind.tuple.TupleOutput; import com.sleepycat.je.Database; import com.sleepycat.je.DatabaseConfig; import com.sleepycat.je.DatabaseEntry; import com.sleepycat.je.DiskOrderedCursorConfig; import com.sleepycat.je.ForwardCursor; import com.sleepycat.je.OperationStatus;
* @throws Exception * If the vector's dimensionality is different from vectorLength */ protected void indexVectorInternal(double[] vector) throws Exception { if (vector.length != vectorLength) { throw new Exception("The dimensionality of the vector is wrong!"); } // append the persistent index appendPersistentIndex(vector); // append the ram-based index if (loadIndexInMemory) { vectorsList.add(vector); } } /** * Computes the k-nearest neighbors of the given query vector. The search is exhaustive but includes some * optimizations that make it faster, especially for high dimensional vectors. * * @param k * The number of nearest neighbors to be returned * @param queryVector * The query vector * * @return A bounded priority queue of Result objects, which contains the k nearest neighbors along with * their iids and distances from the query vector, ordered by lowest distance. * @throws Exception * If the index is not loaded in memory * */
// Path: src/main/java/gr/iti/mklab/visual/utilities/Result.java // public class Result implements Comparator<Result> { // // /** // * The distance associated with this result object. // */ // private double distance; // // /** // * The id associated with this result object. // */ // private int id; // // public Result() { // } // // /** // * Constructor // * // * @param internalId // * @param distance // */ // public Result(int internalId, double distance) { // this.id = internalId; // this.distance = distance; // } // // public int compare(Result o1, Result o2) { // if ((o1).getDistance() > (o2).getDistance()) // return -1; // else if ((o1).getDistance() < (o2).getDistance()) // return 1; // else // return 0; // } // // public double getDistance() { // return distance; // } // // public int getId() { // return id; // } // // } // Path: src/main/java/gr/iti/mklab/visual/datastructures/Linear.java import gnu.trove.list.array.TDoubleArrayList; import gr.iti.mklab.visual.utilities.Result; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import com.aliasi.util.BoundedPriorityQueue; import com.sleepycat.bind.tuple.IntegerBinding; import com.sleepycat.bind.tuple.TupleBinding; import com.sleepycat.bind.tuple.TupleInput; import com.sleepycat.bind.tuple.TupleOutput; import com.sleepycat.je.Database; import com.sleepycat.je.DatabaseConfig; import com.sleepycat.je.DatabaseEntry; import com.sleepycat.je.DiskOrderedCursorConfig; import com.sleepycat.je.ForwardCursor; import com.sleepycat.je.OperationStatus; * @throws Exception * If the vector's dimensionality is different from vectorLength */ protected void indexVectorInternal(double[] vector) throws Exception { if (vector.length != vectorLength) { throw new Exception("The dimensionality of the vector is wrong!"); } // append the persistent index appendPersistentIndex(vector); // append the ram-based index if (loadIndexInMemory) { vectorsList.add(vector); } } /** * Computes the k-nearest neighbors of the given query vector. The search is exhaustive but includes some * optimizations that make it faster, especially for high dimensional vectors. * * @param k * The number of nearest neighbors to be returned * @param queryVector * The query vector * * @return A bounded priority queue of Result objects, which contains the k nearest neighbors along with * their iids and distances from the query vector, ordered by lowest distance. * @throws Exception * If the index is not loaded in memory * */
protected BoundedPriorityQueue<Result> computeNearestNeighborsInternal(int k, double[] queryVector)
Leaking/WeGit
app/src/main/java/com/quinn/githubknife/presenter/RepoAndEventPreviewPresenterImpl.java
// Path: app/src/main/java/com/quinn/githubknife/interactor/RepoAndEventPreviewInteractor.java // public interface RepoAndEventPreviewInteractor { // // public void previewRepo(int page,String user); // public void previewEvent(int page,String user); // // // } // // Path: app/src/main/java/com/quinn/githubknife/interactor/RepoAndEventPreviewInteractorImpl.java // public class RepoAndEventPreviewInteractorImpl implements RepoAndEventPreviewInteractor { // // private Context context; // private OnLoadRepoAndEventPreviewListener listener; // private GithubService service; // private GitHubAccount gitHubAccount; // // // public RepoAndEventPreviewInteractorImpl(final Context context, final OnLoadRepoAndEventPreviewListener listener){ // this.context = context; // this.listener = listener; // this.service = RetrofitUtil.getJsonRetrofitInstance(context).create(GithubService.class); // this.gitHubAccount = GitHubAccount.getInstance(context); // } // // // @Override // public void previewRepo(final int page, final String user) { // Call<List<Repository>> call = service.userRepo(user, String.valueOf(page)); // call.enqueue(new Callback<List<Repository>>() { // @Override // public void onResponse(Response<List<Repository>> response, Retrofit retrofit) { // RetrofitUtil.printResponse(response); // if (response.code() == 401) { // gitHubAccount.invalidateToken(RetrofitUtil.token); // previewRepo(page, user); // } else if (response.isSuccess()) { // listener.repoItems(response.body()); // } else { // listener.loadRepoError(); // } // } // @Override // public void onFailure(Throwable t) { // listener.loadRepoError(); // } // }); // } // // @Override // public void previewEvent(int page, String user) { // // } // } // // Path: app/src/main/java/com/quinn/githubknife/listener/OnLoadRepoAndEventPreviewListener.java // public interface OnLoadRepoAndEventPreviewListener { // // public void repoItems(List items); // public void eventItems(List items); // // public void loadRepoError(); // public void loadEventError(); // // } // // Path: app/src/main/java/com/quinn/githubknife/view/RepoAndEventPreviewView.java // public interface RepoAndEventPreviewView { // // public void repoItems(List items); // public void eventItems(List items); // // public void loadRepoError(); // public void loadEventError(); // // // }
import android.content.Context; import com.quinn.githubknife.interactor.RepoAndEventPreviewInteractor; import com.quinn.githubknife.interactor.RepoAndEventPreviewInteractorImpl; import com.quinn.githubknife.listener.OnLoadRepoAndEventPreviewListener; import com.quinn.githubknife.view.RepoAndEventPreviewView; import java.util.List;
package com.quinn.githubknife.presenter; /** * Created by Quinn on 10/16/15. */ public class RepoAndEventPreviewPresenterImpl implements RepoAndEventPreviewPresenter,OnLoadRepoAndEventPreviewListener { private Context context;
// Path: app/src/main/java/com/quinn/githubknife/interactor/RepoAndEventPreviewInteractor.java // public interface RepoAndEventPreviewInteractor { // // public void previewRepo(int page,String user); // public void previewEvent(int page,String user); // // // } // // Path: app/src/main/java/com/quinn/githubknife/interactor/RepoAndEventPreviewInteractorImpl.java // public class RepoAndEventPreviewInteractorImpl implements RepoAndEventPreviewInteractor { // // private Context context; // private OnLoadRepoAndEventPreviewListener listener; // private GithubService service; // private GitHubAccount gitHubAccount; // // // public RepoAndEventPreviewInteractorImpl(final Context context, final OnLoadRepoAndEventPreviewListener listener){ // this.context = context; // this.listener = listener; // this.service = RetrofitUtil.getJsonRetrofitInstance(context).create(GithubService.class); // this.gitHubAccount = GitHubAccount.getInstance(context); // } // // // @Override // public void previewRepo(final int page, final String user) { // Call<List<Repository>> call = service.userRepo(user, String.valueOf(page)); // call.enqueue(new Callback<List<Repository>>() { // @Override // public void onResponse(Response<List<Repository>> response, Retrofit retrofit) { // RetrofitUtil.printResponse(response); // if (response.code() == 401) { // gitHubAccount.invalidateToken(RetrofitUtil.token); // previewRepo(page, user); // } else if (response.isSuccess()) { // listener.repoItems(response.body()); // } else { // listener.loadRepoError(); // } // } // @Override // public void onFailure(Throwable t) { // listener.loadRepoError(); // } // }); // } // // @Override // public void previewEvent(int page, String user) { // // } // } // // Path: app/src/main/java/com/quinn/githubknife/listener/OnLoadRepoAndEventPreviewListener.java // public interface OnLoadRepoAndEventPreviewListener { // // public void repoItems(List items); // public void eventItems(List items); // // public void loadRepoError(); // public void loadEventError(); // // } // // Path: app/src/main/java/com/quinn/githubknife/view/RepoAndEventPreviewView.java // public interface RepoAndEventPreviewView { // // public void repoItems(List items); // public void eventItems(List items); // // public void loadRepoError(); // public void loadEventError(); // // // } // Path: app/src/main/java/com/quinn/githubknife/presenter/RepoAndEventPreviewPresenterImpl.java import android.content.Context; import com.quinn.githubknife.interactor.RepoAndEventPreviewInteractor; import com.quinn.githubknife.interactor.RepoAndEventPreviewInteractorImpl; import com.quinn.githubknife.listener.OnLoadRepoAndEventPreviewListener; import com.quinn.githubknife.view.RepoAndEventPreviewView; import java.util.List; package com.quinn.githubknife.presenter; /** * Created by Quinn on 10/16/15. */ public class RepoAndEventPreviewPresenterImpl implements RepoAndEventPreviewPresenter,OnLoadRepoAndEventPreviewListener { private Context context;
private RepoAndEventPreviewView view;
Leaking/WeGit
app/src/main/java/com/quinn/githubknife/presenter/RepoAndEventPreviewPresenterImpl.java
// Path: app/src/main/java/com/quinn/githubknife/interactor/RepoAndEventPreviewInteractor.java // public interface RepoAndEventPreviewInteractor { // // public void previewRepo(int page,String user); // public void previewEvent(int page,String user); // // // } // // Path: app/src/main/java/com/quinn/githubknife/interactor/RepoAndEventPreviewInteractorImpl.java // public class RepoAndEventPreviewInteractorImpl implements RepoAndEventPreviewInteractor { // // private Context context; // private OnLoadRepoAndEventPreviewListener listener; // private GithubService service; // private GitHubAccount gitHubAccount; // // // public RepoAndEventPreviewInteractorImpl(final Context context, final OnLoadRepoAndEventPreviewListener listener){ // this.context = context; // this.listener = listener; // this.service = RetrofitUtil.getJsonRetrofitInstance(context).create(GithubService.class); // this.gitHubAccount = GitHubAccount.getInstance(context); // } // // // @Override // public void previewRepo(final int page, final String user) { // Call<List<Repository>> call = service.userRepo(user, String.valueOf(page)); // call.enqueue(new Callback<List<Repository>>() { // @Override // public void onResponse(Response<List<Repository>> response, Retrofit retrofit) { // RetrofitUtil.printResponse(response); // if (response.code() == 401) { // gitHubAccount.invalidateToken(RetrofitUtil.token); // previewRepo(page, user); // } else if (response.isSuccess()) { // listener.repoItems(response.body()); // } else { // listener.loadRepoError(); // } // } // @Override // public void onFailure(Throwable t) { // listener.loadRepoError(); // } // }); // } // // @Override // public void previewEvent(int page, String user) { // // } // } // // Path: app/src/main/java/com/quinn/githubknife/listener/OnLoadRepoAndEventPreviewListener.java // public interface OnLoadRepoAndEventPreviewListener { // // public void repoItems(List items); // public void eventItems(List items); // // public void loadRepoError(); // public void loadEventError(); // // } // // Path: app/src/main/java/com/quinn/githubknife/view/RepoAndEventPreviewView.java // public interface RepoAndEventPreviewView { // // public void repoItems(List items); // public void eventItems(List items); // // public void loadRepoError(); // public void loadEventError(); // // // }
import android.content.Context; import com.quinn.githubknife.interactor.RepoAndEventPreviewInteractor; import com.quinn.githubknife.interactor.RepoAndEventPreviewInteractorImpl; import com.quinn.githubknife.listener.OnLoadRepoAndEventPreviewListener; import com.quinn.githubknife.view.RepoAndEventPreviewView; import java.util.List;
package com.quinn.githubknife.presenter; /** * Created by Quinn on 10/16/15. */ public class RepoAndEventPreviewPresenterImpl implements RepoAndEventPreviewPresenter,OnLoadRepoAndEventPreviewListener { private Context context; private RepoAndEventPreviewView view;
// Path: app/src/main/java/com/quinn/githubknife/interactor/RepoAndEventPreviewInteractor.java // public interface RepoAndEventPreviewInteractor { // // public void previewRepo(int page,String user); // public void previewEvent(int page,String user); // // // } // // Path: app/src/main/java/com/quinn/githubknife/interactor/RepoAndEventPreviewInteractorImpl.java // public class RepoAndEventPreviewInteractorImpl implements RepoAndEventPreviewInteractor { // // private Context context; // private OnLoadRepoAndEventPreviewListener listener; // private GithubService service; // private GitHubAccount gitHubAccount; // // // public RepoAndEventPreviewInteractorImpl(final Context context, final OnLoadRepoAndEventPreviewListener listener){ // this.context = context; // this.listener = listener; // this.service = RetrofitUtil.getJsonRetrofitInstance(context).create(GithubService.class); // this.gitHubAccount = GitHubAccount.getInstance(context); // } // // // @Override // public void previewRepo(final int page, final String user) { // Call<List<Repository>> call = service.userRepo(user, String.valueOf(page)); // call.enqueue(new Callback<List<Repository>>() { // @Override // public void onResponse(Response<List<Repository>> response, Retrofit retrofit) { // RetrofitUtil.printResponse(response); // if (response.code() == 401) { // gitHubAccount.invalidateToken(RetrofitUtil.token); // previewRepo(page, user); // } else if (response.isSuccess()) { // listener.repoItems(response.body()); // } else { // listener.loadRepoError(); // } // } // @Override // public void onFailure(Throwable t) { // listener.loadRepoError(); // } // }); // } // // @Override // public void previewEvent(int page, String user) { // // } // } // // Path: app/src/main/java/com/quinn/githubknife/listener/OnLoadRepoAndEventPreviewListener.java // public interface OnLoadRepoAndEventPreviewListener { // // public void repoItems(List items); // public void eventItems(List items); // // public void loadRepoError(); // public void loadEventError(); // // } // // Path: app/src/main/java/com/quinn/githubknife/view/RepoAndEventPreviewView.java // public interface RepoAndEventPreviewView { // // public void repoItems(List items); // public void eventItems(List items); // // public void loadRepoError(); // public void loadEventError(); // // // } // Path: app/src/main/java/com/quinn/githubknife/presenter/RepoAndEventPreviewPresenterImpl.java import android.content.Context; import com.quinn.githubknife.interactor.RepoAndEventPreviewInteractor; import com.quinn.githubknife.interactor.RepoAndEventPreviewInteractorImpl; import com.quinn.githubknife.listener.OnLoadRepoAndEventPreviewListener; import com.quinn.githubknife.view.RepoAndEventPreviewView; import java.util.List; package com.quinn.githubknife.presenter; /** * Created by Quinn on 10/16/15. */ public class RepoAndEventPreviewPresenterImpl implements RepoAndEventPreviewPresenter,OnLoadRepoAndEventPreviewListener { private Context context; private RepoAndEventPreviewView view;
private RepoAndEventPreviewInteractor interactor;
Leaking/WeGit
app/src/main/java/com/quinn/githubknife/presenter/RepoAndEventPreviewPresenterImpl.java
// Path: app/src/main/java/com/quinn/githubknife/interactor/RepoAndEventPreviewInteractor.java // public interface RepoAndEventPreviewInteractor { // // public void previewRepo(int page,String user); // public void previewEvent(int page,String user); // // // } // // Path: app/src/main/java/com/quinn/githubknife/interactor/RepoAndEventPreviewInteractorImpl.java // public class RepoAndEventPreviewInteractorImpl implements RepoAndEventPreviewInteractor { // // private Context context; // private OnLoadRepoAndEventPreviewListener listener; // private GithubService service; // private GitHubAccount gitHubAccount; // // // public RepoAndEventPreviewInteractorImpl(final Context context, final OnLoadRepoAndEventPreviewListener listener){ // this.context = context; // this.listener = listener; // this.service = RetrofitUtil.getJsonRetrofitInstance(context).create(GithubService.class); // this.gitHubAccount = GitHubAccount.getInstance(context); // } // // // @Override // public void previewRepo(final int page, final String user) { // Call<List<Repository>> call = service.userRepo(user, String.valueOf(page)); // call.enqueue(new Callback<List<Repository>>() { // @Override // public void onResponse(Response<List<Repository>> response, Retrofit retrofit) { // RetrofitUtil.printResponse(response); // if (response.code() == 401) { // gitHubAccount.invalidateToken(RetrofitUtil.token); // previewRepo(page, user); // } else if (response.isSuccess()) { // listener.repoItems(response.body()); // } else { // listener.loadRepoError(); // } // } // @Override // public void onFailure(Throwable t) { // listener.loadRepoError(); // } // }); // } // // @Override // public void previewEvent(int page, String user) { // // } // } // // Path: app/src/main/java/com/quinn/githubknife/listener/OnLoadRepoAndEventPreviewListener.java // public interface OnLoadRepoAndEventPreviewListener { // // public void repoItems(List items); // public void eventItems(List items); // // public void loadRepoError(); // public void loadEventError(); // // } // // Path: app/src/main/java/com/quinn/githubknife/view/RepoAndEventPreviewView.java // public interface RepoAndEventPreviewView { // // public void repoItems(List items); // public void eventItems(List items); // // public void loadRepoError(); // public void loadEventError(); // // // }
import android.content.Context; import com.quinn.githubknife.interactor.RepoAndEventPreviewInteractor; import com.quinn.githubknife.interactor.RepoAndEventPreviewInteractorImpl; import com.quinn.githubknife.listener.OnLoadRepoAndEventPreviewListener; import com.quinn.githubknife.view.RepoAndEventPreviewView; import java.util.List;
package com.quinn.githubknife.presenter; /** * Created by Quinn on 10/16/15. */ public class RepoAndEventPreviewPresenterImpl implements RepoAndEventPreviewPresenter,OnLoadRepoAndEventPreviewListener { private Context context; private RepoAndEventPreviewView view; private RepoAndEventPreviewInteractor interactor; public RepoAndEventPreviewPresenterImpl(Context context, RepoAndEventPreviewView view){ this.view = view; this.context = context;
// Path: app/src/main/java/com/quinn/githubknife/interactor/RepoAndEventPreviewInteractor.java // public interface RepoAndEventPreviewInteractor { // // public void previewRepo(int page,String user); // public void previewEvent(int page,String user); // // // } // // Path: app/src/main/java/com/quinn/githubknife/interactor/RepoAndEventPreviewInteractorImpl.java // public class RepoAndEventPreviewInteractorImpl implements RepoAndEventPreviewInteractor { // // private Context context; // private OnLoadRepoAndEventPreviewListener listener; // private GithubService service; // private GitHubAccount gitHubAccount; // // // public RepoAndEventPreviewInteractorImpl(final Context context, final OnLoadRepoAndEventPreviewListener listener){ // this.context = context; // this.listener = listener; // this.service = RetrofitUtil.getJsonRetrofitInstance(context).create(GithubService.class); // this.gitHubAccount = GitHubAccount.getInstance(context); // } // // // @Override // public void previewRepo(final int page, final String user) { // Call<List<Repository>> call = service.userRepo(user, String.valueOf(page)); // call.enqueue(new Callback<List<Repository>>() { // @Override // public void onResponse(Response<List<Repository>> response, Retrofit retrofit) { // RetrofitUtil.printResponse(response); // if (response.code() == 401) { // gitHubAccount.invalidateToken(RetrofitUtil.token); // previewRepo(page, user); // } else if (response.isSuccess()) { // listener.repoItems(response.body()); // } else { // listener.loadRepoError(); // } // } // @Override // public void onFailure(Throwable t) { // listener.loadRepoError(); // } // }); // } // // @Override // public void previewEvent(int page, String user) { // // } // } // // Path: app/src/main/java/com/quinn/githubknife/listener/OnLoadRepoAndEventPreviewListener.java // public interface OnLoadRepoAndEventPreviewListener { // // public void repoItems(List items); // public void eventItems(List items); // // public void loadRepoError(); // public void loadEventError(); // // } // // Path: app/src/main/java/com/quinn/githubknife/view/RepoAndEventPreviewView.java // public interface RepoAndEventPreviewView { // // public void repoItems(List items); // public void eventItems(List items); // // public void loadRepoError(); // public void loadEventError(); // // // } // Path: app/src/main/java/com/quinn/githubknife/presenter/RepoAndEventPreviewPresenterImpl.java import android.content.Context; import com.quinn.githubknife.interactor.RepoAndEventPreviewInteractor; import com.quinn.githubknife.interactor.RepoAndEventPreviewInteractorImpl; import com.quinn.githubknife.listener.OnLoadRepoAndEventPreviewListener; import com.quinn.githubknife.view.RepoAndEventPreviewView; import java.util.List; package com.quinn.githubknife.presenter; /** * Created by Quinn on 10/16/15. */ public class RepoAndEventPreviewPresenterImpl implements RepoAndEventPreviewPresenter,OnLoadRepoAndEventPreviewListener { private Context context; private RepoAndEventPreviewView view; private RepoAndEventPreviewInteractor interactor; public RepoAndEventPreviewPresenterImpl(Context context, RepoAndEventPreviewView view){ this.view = view; this.context = context;
this.interactor = new RepoAndEventPreviewInteractorImpl(context,this);
Leaking/WeGit
httpknife/src/main/java/com/quinn/httpknife/payload/IssuePayload.java
// Path: httpknife/src/main/java/com/quinn/httpknife/github/Issue.java // public class Issue implements Serializable { // // private static final long serialVersionUID = 6736401806450165758L; // // private long id; // private Date closedAt; // private Date createdAt; // private Date updatedAt; // private int comments; // private int number; // private List<Label> labels; // private String body; // private String bodyHtml; // private String bodyText; // private String htmlUrl; // private String state; // private String title; // private String url; // private User assignee; // private User user; // // public Issue() { // } // // public Date getClosedAt() { // return this.closedAt; // } // // public Issue setClosedAt(Date closedAt) { // this.closedAt = closedAt; // return this; // } // // public Date getCreatedAt() { // return this.createdAt; // } // // public Issue setCreatedAt(Date createdAt) { // this.createdAt = createdAt; // return this; // } // // public Date getUpdatedAt() { // return this.updatedAt; // } // // public Issue setUpdatedAt(Date updatedAt) { // this.updatedAt = updatedAt; // return this; // } // // public int getComments() { // return this.comments; // } // // public Issue setComments(int comments) { // this.comments = comments; // return this; // } // // public int getNumber() { // return this.number; // } // // public Issue setNumber(int number) { // this.number = number; // return this; // } // // public List<Label> getLabels() { // return this.labels; // } // // public Issue setLabels(List<Label> labels) { // this.labels = labels != null?new ArrayList(labels):null; // return this; // } // // public String getBody() { // return this.body; // } // // public Issue setBody(String body) { // this.body = body; // return this; // } // // public String getBodyHtml() { // return this.bodyHtml; // } // // public Issue setBodyHtml(String bodyHtml) { // this.bodyHtml = bodyHtml; // return this; // } // // public String getBodyText() { // return this.bodyText; // } // // public Issue setBodyText(String bodyText) { // this.bodyText = bodyText; // return this; // } // // public String getHtmlUrl() { // return this.htmlUrl; // } // // public Issue setHtmlUrl(String htmlUrl) { // this.htmlUrl = htmlUrl; // return this; // } // // public String getState() { // return this.state; // } // // public Issue setState(String state) { // this.state = state; // return this; // } // // public String getTitle() { // return this.title; // } // // public Issue setTitle(String title) { // this.title = title; // return this; // } // // public String getUrl() { // return this.url; // } // // public Issue setUrl(String url) { // this.url = url; // return this; // } // // public User getAssignee() { // return this.assignee; // } // // public Issue setAssignee(User assignee) { // this.assignee = assignee; // return this; // } // // public User getUser() { // return this.user; // } // // public Issue setUser(User user) { // this.user = user; // return this; // } // // public long getId() { // return this.id; // } // // public Issue setId(long id) { // this.id = id; // return this; // } // // public String toString() { // return "Issue " + this.number; // } // }
import com.quinn.httpknife.github.Issue;
package com.quinn.httpknife.payload; /** * Created by Quinn on 10/4/15. */ public class IssuePayload extends Payload { private static final long serialVersionUID = 4412536275423825042L; private String action;
// Path: httpknife/src/main/java/com/quinn/httpknife/github/Issue.java // public class Issue implements Serializable { // // private static final long serialVersionUID = 6736401806450165758L; // // private long id; // private Date closedAt; // private Date createdAt; // private Date updatedAt; // private int comments; // private int number; // private List<Label> labels; // private String body; // private String bodyHtml; // private String bodyText; // private String htmlUrl; // private String state; // private String title; // private String url; // private User assignee; // private User user; // // public Issue() { // } // // public Date getClosedAt() { // return this.closedAt; // } // // public Issue setClosedAt(Date closedAt) { // this.closedAt = closedAt; // return this; // } // // public Date getCreatedAt() { // return this.createdAt; // } // // public Issue setCreatedAt(Date createdAt) { // this.createdAt = createdAt; // return this; // } // // public Date getUpdatedAt() { // return this.updatedAt; // } // // public Issue setUpdatedAt(Date updatedAt) { // this.updatedAt = updatedAt; // return this; // } // // public int getComments() { // return this.comments; // } // // public Issue setComments(int comments) { // this.comments = comments; // return this; // } // // public int getNumber() { // return this.number; // } // // public Issue setNumber(int number) { // this.number = number; // return this; // } // // public List<Label> getLabels() { // return this.labels; // } // // public Issue setLabels(List<Label> labels) { // this.labels = labels != null?new ArrayList(labels):null; // return this; // } // // public String getBody() { // return this.body; // } // // public Issue setBody(String body) { // this.body = body; // return this; // } // // public String getBodyHtml() { // return this.bodyHtml; // } // // public Issue setBodyHtml(String bodyHtml) { // this.bodyHtml = bodyHtml; // return this; // } // // public String getBodyText() { // return this.bodyText; // } // // public Issue setBodyText(String bodyText) { // this.bodyText = bodyText; // return this; // } // // public String getHtmlUrl() { // return this.htmlUrl; // } // // public Issue setHtmlUrl(String htmlUrl) { // this.htmlUrl = htmlUrl; // return this; // } // // public String getState() { // return this.state; // } // // public Issue setState(String state) { // this.state = state; // return this; // } // // public String getTitle() { // return this.title; // } // // public Issue setTitle(String title) { // this.title = title; // return this; // } // // public String getUrl() { // return this.url; // } // // public Issue setUrl(String url) { // this.url = url; // return this; // } // // public User getAssignee() { // return this.assignee; // } // // public Issue setAssignee(User assignee) { // this.assignee = assignee; // return this; // } // // public User getUser() { // return this.user; // } // // public Issue setUser(User user) { // this.user = user; // return this; // } // // public long getId() { // return this.id; // } // // public Issue setId(long id) { // this.id = id; // return this; // } // // public String toString() { // return "Issue " + this.number; // } // } // Path: httpknife/src/main/java/com/quinn/httpknife/payload/IssuePayload.java import com.quinn.httpknife.github.Issue; package com.quinn.httpknife.payload; /** * Created by Quinn on 10/4/15. */ public class IssuePayload extends Payload { private static final long serialVersionUID = 4412536275423825042L; private String action;
private Issue issue;
Leaking/WeGit
app/src/main/java/com/quinn/githubknife/utils/TDUtils.java
// Path: app/src/main/java/com/quinn/githubknife/GithubApplication.java // public class GithubApplication extends Application { // // private final static String TD_APP_ID = "C7208C73204D6DDF67AA2227D9C06174"; // // public static Context instance; // // /** // * @// TODO: 9/6/16 // * 暂时默认100,后续打多渠道此处得动态获取 // */ // private String channel = "100"; // // private User user; // // private String token = ""; // // // @Override // public void onCreate() { // super.onCreate(); // instance = this; // /** // * 初始化Talking-data // */ // new Thread(new Runnable() { // @Override // public void run() { // TCAgent.LOG_ON = false; // channel = ChannelUtils.getChannel(GithubApplication.this); // TCAgent.init(GithubApplication.this, TD_APP_ID, channel); // TCAgent.setReportUncaughtExceptions(true); // } // }).start(); // // Initialize ImageLoader with configuration. // ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder( // getApplicationContext()) // .threadPriority(Thread.NORM_PRIORITY - 2) // .denyCacheImageMultipleSizesInMemory() // .diskCacheFileNameGenerator(new Md5FileNameGenerator()) // .diskCacheSize(50 * 1024 * 1024) // // 50 Mb // .tasksProcessingOrder(QueueProcessingType.LIFO) // .writeDebugLogs() // Remove for release app // .build(); // // ImageLoader.getInstance().init(config); // } // // // public APKVersion getAPKVersion(){ // APKVersion version = new APKVersion(); // try { // PackageInfo info = getPackageManager().getPackageInfo( // getPackageName(), 0); // version.setVersionCode(info.versionCode); // version.setVersionName(info.versionName); // } catch (PackageManager.NameNotFoundException e) { // e.printStackTrace(); // } // // return version; // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // }
import com.quinn.githubknife.GithubApplication; import com.tendcloud.tenddata.TCAgent;
package com.quinn.githubknife.utils; /** * Created by Quinn on 9/6/16. */ public class TDUtils { public static void event(String eventID) {
// Path: app/src/main/java/com/quinn/githubknife/GithubApplication.java // public class GithubApplication extends Application { // // private final static String TD_APP_ID = "C7208C73204D6DDF67AA2227D9C06174"; // // public static Context instance; // // /** // * @// TODO: 9/6/16 // * 暂时默认100,后续打多渠道此处得动态获取 // */ // private String channel = "100"; // // private User user; // // private String token = ""; // // // @Override // public void onCreate() { // super.onCreate(); // instance = this; // /** // * 初始化Talking-data // */ // new Thread(new Runnable() { // @Override // public void run() { // TCAgent.LOG_ON = false; // channel = ChannelUtils.getChannel(GithubApplication.this); // TCAgent.init(GithubApplication.this, TD_APP_ID, channel); // TCAgent.setReportUncaughtExceptions(true); // } // }).start(); // // Initialize ImageLoader with configuration. // ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder( // getApplicationContext()) // .threadPriority(Thread.NORM_PRIORITY - 2) // .denyCacheImageMultipleSizesInMemory() // .diskCacheFileNameGenerator(new Md5FileNameGenerator()) // .diskCacheSize(50 * 1024 * 1024) // // 50 Mb // .tasksProcessingOrder(QueueProcessingType.LIFO) // .writeDebugLogs() // Remove for release app // .build(); // // ImageLoader.getInstance().init(config); // } // // // public APKVersion getAPKVersion(){ // APKVersion version = new APKVersion(); // try { // PackageInfo info = getPackageManager().getPackageInfo( // getPackageName(), 0); // version.setVersionCode(info.versionCode); // version.setVersionName(info.versionName); // } catch (PackageManager.NameNotFoundException e) { // e.printStackTrace(); // } // // return version; // } // // public User getUser() { // return user; // } // // public void setUser(User user) { // this.user = user; // } // // public String getToken() { // return token; // } // // public void setToken(String token) { // this.token = token; // } // } // Path: app/src/main/java/com/quinn/githubknife/utils/TDUtils.java import com.quinn.githubknife.GithubApplication; import com.tendcloud.tenddata.TCAgent; package com.quinn.githubknife.utils; /** * Created by Quinn on 9/6/16. */ public class TDUtils { public static void event(String eventID) {
TCAgent.onEvent(GithubApplication.instance, eventID);
Leaking/WeGit
httpknife/src/main/java/com/quinn/httpknife/payload/EventFormatter.java
// Path: httpknife/src/main/java/com/quinn/httpknife/github/GithubConstants.java // public interface GithubConstants { // // public final static String WATCH_EVENT = "WatchEvent"; // public final static String ForkEvent = "ForkEvent"; // public final static String CreateEvent = "CreateEvent"; // public final static String PullRequestEvent = "PullRequestEvent"; // public final static String MemberEvent = "MemberEvent"; // public final static String IssuesEvent = "IssuesEvent"; // public final static String PublicEvent = "PublicEvent"; // // // // } // // Path: httpknife/src/main/java/com/quinn/httpknife/github/Event.java // public class Event { // // // private String id; // private String type; // private User actor; // private Repository repo; // private Date created_at; // private Payload payload; // private User org; // // // // public User getActor() { // return actor; // } // // public void setActor(User actor) { // this.actor = actor; // } // // public Date getCreated_at() { // return created_at; // } // // public void setCreated_at(Date created_at) { // this.created_at = created_at; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public Repository getRepo() { // return repo; // } // // public void setRepo(Repository repo) { // this.repo = repo; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public Payload getPayload() { // return payload; // } // // public void setPayload(Payload payload) { // this.payload = payload; // } // // public User getOrg() { // return org; // } // // public void setOrg(User org) { // this.org = org; // } // // @Override // public String toString() { // return "Event{" + // "actor=" + actor + // ", id='" + id + '\'' + // ", type='" + type + '\'' + // ", repo=" + repo + // ", created_at=" + created_at + // ", payload=" + payload + // ", org=" + org + // '}'; // } // }
import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import com.quinn.httpknife.github.GithubConstants; import com.quinn.httpknife.github.Event; import java.lang.reflect.Type;
package com.quinn.httpknife.payload; /** * Created by Quinn on 15/10/2. */ public class EventFormatter implements JsonDeserializer<Event> { private final Gson gson; public EventFormatter() { this.gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create(); } public Event deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { Event event = (Event)this.gson.fromJson(json, Event.class); if(event != null && json.isJsonObject()) { JsonElement rawPayload = json.getAsJsonObject().get("payload"); if(rawPayload != null && rawPayload.isJsonObject()) { String type = event.getType(); if(type != null && type.length() != 0) { Class payloadClass;
// Path: httpknife/src/main/java/com/quinn/httpknife/github/GithubConstants.java // public interface GithubConstants { // // public final static String WATCH_EVENT = "WatchEvent"; // public final static String ForkEvent = "ForkEvent"; // public final static String CreateEvent = "CreateEvent"; // public final static String PullRequestEvent = "PullRequestEvent"; // public final static String MemberEvent = "MemberEvent"; // public final static String IssuesEvent = "IssuesEvent"; // public final static String PublicEvent = "PublicEvent"; // // // // } // // Path: httpknife/src/main/java/com/quinn/httpknife/github/Event.java // public class Event { // // // private String id; // private String type; // private User actor; // private Repository repo; // private Date created_at; // private Payload payload; // private User org; // // // // public User getActor() { // return actor; // } // // public void setActor(User actor) { // this.actor = actor; // } // // public Date getCreated_at() { // return created_at; // } // // public void setCreated_at(Date created_at) { // this.created_at = created_at; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public Repository getRepo() { // return repo; // } // // public void setRepo(Repository repo) { // this.repo = repo; // } // // public String getType() { // return type; // } // // public void setType(String type) { // this.type = type; // } // // public Payload getPayload() { // return payload; // } // // public void setPayload(Payload payload) { // this.payload = payload; // } // // public User getOrg() { // return org; // } // // public void setOrg(User org) { // this.org = org; // } // // @Override // public String toString() { // return "Event{" + // "actor=" + actor + // ", id='" + id + '\'' + // ", type='" + type + '\'' + // ", repo=" + repo + // ", created_at=" + created_at + // ", payload=" + payload + // ", org=" + org + // '}'; // } // } // Path: httpknife/src/main/java/com/quinn/httpknife/payload/EventFormatter.java import com.google.gson.FieldNamingPolicy; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonParseException; import com.quinn.httpknife.github.GithubConstants; import com.quinn.httpknife.github.Event; import java.lang.reflect.Type; package com.quinn.httpknife.payload; /** * Created by Quinn on 15/10/2. */ public class EventFormatter implements JsonDeserializer<Event> { private final Gson gson; public EventFormatter() { this.gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create(); } public Event deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { Event event = (Event)this.gson.fromJson(json, Event.class); if(event != null && json.isJsonObject()) { JsonElement rawPayload = json.getAsJsonObject().get("payload"); if(rawPayload != null && rawPayload.isJsonObject()) { String type = event.getType(); if(type != null && type.length() != 0) { Class payloadClass;
if(GithubConstants.MemberEvent.equals(type)) {
Leaking/WeGit
app/src/main/java/com/quinn/githubknife/interactor/FindItemsInteractor.java
// Path: httpknife/src/main/java/com/quinn/httpknife/github/TrendingRepo.java // public class TrendingRepo extends Repository { // // /** // * 新增的star数量 // */ // private int addStars; // // private SINCE_TYPE since_type; // // public SINCE_TYPE getSince_type() { // return since_type; // } // // public void setSince_type(SINCE_TYPE since_type) { // this.since_type = since_type; // } // // public int getAddStars() { // return addStars; // } // // public void setAddStars(int addStars) { // this.addStars = addStars; // } // // public enum SINCE_TYPE { // SINCE_DAY, // SINCE_WEEK, // SINCE_MONTH // } // }
import com.quinn.httpknife.github.TrendingRepo; import java.util.List;
package com.quinn.githubknife.interactor; /** * Created by Quinn on 7/20/15. */ public interface FindItemsInteractor { public void loadFollowerings(String account,int page); public void loadFollwers(String account,int page); public void loadAuthUser(); public void loadAuthRepos(); public void loadRepo(String account,int page); public void loadStarredRepo(String user,int page); public void loadReceivedEvents(String user, int page); public void loadUserEvents(String user, int page); public void loadRepoEvents(String user, String repo, int page); public void loadStargazers(String owner,String repo, int page); public void loadForkers(String owner,String repo, int page); public void loadCollaborators(String owner,String repo, int page); public void loadTree(String owner,String repo,String sha); public void loadBranches(String owner,String repo); public void searchUsers(List<String> keywords,int page); public void searchRepos(List<String> keywords,int page);
// Path: httpknife/src/main/java/com/quinn/httpknife/github/TrendingRepo.java // public class TrendingRepo extends Repository { // // /** // * 新增的star数量 // */ // private int addStars; // // private SINCE_TYPE since_type; // // public SINCE_TYPE getSince_type() { // return since_type; // } // // public void setSince_type(SINCE_TYPE since_type) { // this.since_type = since_type; // } // // public int getAddStars() { // return addStars; // } // // public void setAddStars(int addStars) { // this.addStars = addStars; // } // // public enum SINCE_TYPE { // SINCE_DAY, // SINCE_WEEK, // SINCE_MONTH // } // } // Path: app/src/main/java/com/quinn/githubknife/interactor/FindItemsInteractor.java import com.quinn.httpknife.github.TrendingRepo; import java.util.List; package com.quinn.githubknife.interactor; /** * Created by Quinn on 7/20/15. */ public interface FindItemsInteractor { public void loadFollowerings(String account,int page); public void loadFollwers(String account,int page); public void loadAuthUser(); public void loadAuthRepos(); public void loadRepo(String account,int page); public void loadStarredRepo(String user,int page); public void loadReceivedEvents(String user, int page); public void loadUserEvents(String user, int page); public void loadRepoEvents(String user, String repo, int page); public void loadStargazers(String owner,String repo, int page); public void loadForkers(String owner,String repo, int page); public void loadCollaborators(String owner,String repo, int page); public void loadTree(String owner,String repo,String sha); public void loadBranches(String owner,String repo); public void searchUsers(List<String> keywords,int page); public void searchRepos(List<String> keywords,int page);
public void trendingRepos(String url, TrendingRepo.SINCE_TYPE sinceType);
Leaking/WeGit
app/src/main/java/com/quinn/githubknife/ui/widget/UserLabel.java
// Path: app/src/main/java/com/quinn/githubknife/utils/UIUtils.java // public class UIUtils { // // public static void crossfade(final View currView, final View nextView) { // // // Set the content view to 0% opacity but visible, so that it is visible // // (but fully transparent) during the animation. // if (nextView != null) { // nextView.setAlpha(0f); // nextView.setVisibility(View.VISIBLE); // nextView.animate().alpha(1f).setDuration(200).setListener(new AnimatorListenerAdapter() { // @Override // public void onAnimationEnd(Animator animation) { // nextView.setVisibility(View.VISIBLE); // } // }); // } // // // Animate the loading view to 0% opacity. After the animation ends, // // set its visibility to GONE as an optimization step (it won't // // participate in layout passes, etc.) // if (currView != null) { // currView.setVisibility(View.GONE); // currView.animate().alpha(0f).setDuration(200) // .setListener(new AnimatorListenerAdapter() { // @Override // public void onAnimationEnd(Animator animation) { // currView.setVisibility(View.GONE); // } // }); // } // } // // /** // * 关闭输入法 // * @param context // */ // public static void closeInputMethod(Context context) { // InputMethodManager inputMethodManager = (InputMethodManager) context // .getSystemService(Context.INPUT_METHOD_SERVICE); // inputMethodManager.hideSoftInputFromWindow(((Activity) context) // .getCurrentFocus().getWindowToken(), // InputMethodManager.HIDE_NOT_ALWAYS); // } // // /** // * 将px值转换为sp值,保证文字大小不变 // * @return // */ // public static int px2sp(Context context, float pxValue) { // final float fontScale = context.getResources().getDisplayMetrics().scaledDensity; // return (int) (pxValue / fontScale + 0.5f); // } // // /** // * 将sp值转换为px值,保证文字大小不变 // * @return // */ // public static int sp2px(Context context, float spValue) { // final float fontScale = context.getResources().getDisplayMetrics().scaledDensity; // return (int) (spValue * fontScale + 0.5f); // } // // // public static int getColorWrap(Context context, int colorRsid) { // if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // return ActivityCompat.getColor(context, colorRsid); // }else{ // return context.getResources().getColor(colorRsid); // } // } // }
import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.util.AttributeSet; import android.util.Log; import android.view.View; import com.quinn.githubknife.R; import com.quinn.githubknife.utils.L; import com.quinn.githubknife.utils.UIUtils;
package com.quinn.githubknife.ui.widget; /** * Created by Quinn on 9/21/15. * * 一个绘制KEY-VALUE的组件,上方绘制VAUE,下方绘制NAME */ public class UserLabel extends View{ private final static String TAG = UserLabel.class.getSimpleName(); //两个画笔 private Paint namePaint; private Paint valuePaint; private Rect nameRect; private Rect valueRect; private String label_name; private String label_value; public UserLabel(Context context) { this(context, null); } public UserLabel(Context context, AttributeSet attrs) { this(context, attrs, 0); } public UserLabel(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); //Init attr TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.user_verical_label); label_name = a.getString(R.styleable.user_verical_label_name); label_value = a.getString(R.styleable.user_verical_label_value); a.recycle(); nameRect = new Rect(); namePaint = new Paint();
// Path: app/src/main/java/com/quinn/githubknife/utils/UIUtils.java // public class UIUtils { // // public static void crossfade(final View currView, final View nextView) { // // // Set the content view to 0% opacity but visible, so that it is visible // // (but fully transparent) during the animation. // if (nextView != null) { // nextView.setAlpha(0f); // nextView.setVisibility(View.VISIBLE); // nextView.animate().alpha(1f).setDuration(200).setListener(new AnimatorListenerAdapter() { // @Override // public void onAnimationEnd(Animator animation) { // nextView.setVisibility(View.VISIBLE); // } // }); // } // // // Animate the loading view to 0% opacity. After the animation ends, // // set its visibility to GONE as an optimization step (it won't // // participate in layout passes, etc.) // if (currView != null) { // currView.setVisibility(View.GONE); // currView.animate().alpha(0f).setDuration(200) // .setListener(new AnimatorListenerAdapter() { // @Override // public void onAnimationEnd(Animator animation) { // currView.setVisibility(View.GONE); // } // }); // } // } // // /** // * 关闭输入法 // * @param context // */ // public static void closeInputMethod(Context context) { // InputMethodManager inputMethodManager = (InputMethodManager) context // .getSystemService(Context.INPUT_METHOD_SERVICE); // inputMethodManager.hideSoftInputFromWindow(((Activity) context) // .getCurrentFocus().getWindowToken(), // InputMethodManager.HIDE_NOT_ALWAYS); // } // // /** // * 将px值转换为sp值,保证文字大小不变 // * @return // */ // public static int px2sp(Context context, float pxValue) { // final float fontScale = context.getResources().getDisplayMetrics().scaledDensity; // return (int) (pxValue / fontScale + 0.5f); // } // // /** // * 将sp值转换为px值,保证文字大小不变 // * @return // */ // public static int sp2px(Context context, float spValue) { // final float fontScale = context.getResources().getDisplayMetrics().scaledDensity; // return (int) (spValue * fontScale + 0.5f); // } // // // public static int getColorWrap(Context context, int colorRsid) { // if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // return ActivityCompat.getColor(context, colorRsid); // }else{ // return context.getResources().getColor(colorRsid); // } // } // } // Path: app/src/main/java/com/quinn/githubknife/ui/widget/UserLabel.java import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.util.AttributeSet; import android.util.Log; import android.view.View; import com.quinn.githubknife.R; import com.quinn.githubknife.utils.L; import com.quinn.githubknife.utils.UIUtils; package com.quinn.githubknife.ui.widget; /** * Created by Quinn on 9/21/15. * * 一个绘制KEY-VALUE的组件,上方绘制VAUE,下方绘制NAME */ public class UserLabel extends View{ private final static String TAG = UserLabel.class.getSimpleName(); //两个画笔 private Paint namePaint; private Paint valuePaint; private Rect nameRect; private Rect valueRect; private String label_name; private String label_value; public UserLabel(Context context) { this(context, null); } public UserLabel(Context context, AttributeSet attrs) { this(context, attrs, 0); } public UserLabel(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); //Init attr TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.user_verical_label); label_name = a.getString(R.styleable.user_verical_label_name); label_value = a.getString(R.styleable.user_verical_label_value); a.recycle(); nameRect = new Rect(); namePaint = new Paint();
namePaint.setTextSize(UIUtils.sp2px(this.getContext(), 15));
Leaking/WeGit
app/src/main/java/com/quinn/githubknife/ui/adapter/TrendingRepoAdapter.java
// Path: httpknife/src/main/java/com/quinn/httpknife/github/TrendingRepo.java // public class TrendingRepo extends Repository { // // /** // * 新增的star数量 // */ // private int addStars; // // private SINCE_TYPE since_type; // // public SINCE_TYPE getSince_type() { // return since_type; // } // // public void setSince_type(SINCE_TYPE since_type) { // this.since_type = since_type; // } // // public int getAddStars() { // return addStars; // } // // public void setAddStars(int addStars) { // this.addStars = addStars; // } // // public enum SINCE_TYPE { // SINCE_DAY, // SINCE_WEEK, // SINCE_MONTH // } // }
import android.graphics.Typeface; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.quinn.githubknife.R; import com.quinn.githubknife.ui.widget.RecycleItemClickListener; import com.quinn.httpknife.github.Repository; import com.quinn.httpknife.github.TrendingRepo; import java.util.List;
package com.quinn.githubknife.ui.adapter; /** * Created by Quinn on 9/10/16. */ public class TrendingRepoAdapter extends RecyclerView.Adapter<TrendingRepoAdapter.ViewHolder>{
// Path: httpknife/src/main/java/com/quinn/httpknife/github/TrendingRepo.java // public class TrendingRepo extends Repository { // // /** // * 新增的star数量 // */ // private int addStars; // // private SINCE_TYPE since_type; // // public SINCE_TYPE getSince_type() { // return since_type; // } // // public void setSince_type(SINCE_TYPE since_type) { // this.since_type = since_type; // } // // public int getAddStars() { // return addStars; // } // // public void setAddStars(int addStars) { // this.addStars = addStars; // } // // public enum SINCE_TYPE { // SINCE_DAY, // SINCE_WEEK, // SINCE_MONTH // } // } // Path: app/src/main/java/com/quinn/githubknife/ui/adapter/TrendingRepoAdapter.java import android.graphics.Typeface; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.quinn.githubknife.R; import com.quinn.githubknife.ui.widget.RecycleItemClickListener; import com.quinn.httpknife.github.Repository; import com.quinn.httpknife.github.TrendingRepo; import java.util.List; package com.quinn.githubknife.ui.adapter; /** * Created by Quinn on 9/10/16. */ public class TrendingRepoAdapter extends RecyclerView.Adapter<TrendingRepoAdapter.ViewHolder>{
private List<TrendingRepo> dataItems;
Leaking/WeGit
httpknife/src/main/java/com/quinn/httpknife/github/Event.java
// Path: httpknife/src/main/java/com/quinn/httpknife/payload/Payload.java // public class Payload implements Serializable { // private static final long serialVersionUID = 1022083387039340606L; // // public Payload() { // } // }
import com.quinn.httpknife.payload.Payload; import java.util.Date;
package com.quinn.httpknife.github; public class Event { private String id; private String type; private User actor; private Repository repo; private Date created_at;
// Path: httpknife/src/main/java/com/quinn/httpknife/payload/Payload.java // public class Payload implements Serializable { // private static final long serialVersionUID = 1022083387039340606L; // // public Payload() { // } // } // Path: httpknife/src/main/java/com/quinn/httpknife/github/Event.java import com.quinn.httpknife.payload.Payload; import java.util.Date; package com.quinn.httpknife.github; public class Event { private String id; private String type; private User actor; private Repository repo; private Date created_at;
private Payload payload;
mit-dig/punya
appinventor/appengine/src/com/google/appinventor/client/editor/simple/components/MockVisibleComponent.java
// Path: appinventor/appengine/src/com/google/appinventor/client/Ode.java // public static final OdeMessages MESSAGES = GWT.create(OdeMessages.class);
import static com.google.appinventor.client.Ode.MESSAGES; import com.google.appinventor.client.editor.simple.SimpleEditor; import com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidLengthPropertyEditor; import com.google.appinventor.client.widgets.properties.TextPropertyEditor; import com.google.appinventor.components.common.ComponentConstants; import com.google.gwt.resources.client.ImageResource; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.Widget;
// get the length is percent of Screen1 public static final int LENGTH_PERCENT_TAG = -1000; // Useful colors protected static final String COLOR_NONE = "00FFFFFF"; protected static final String COLOR_DEFAULT = "00000000"; /** * Creates a new instance of a visible component. * * @param editor editor of source file the component belongs to */ MockVisibleComponent(SimpleEditor editor, String type, ImageResource icon) { super(editor, type, new Image(icon)); } @Override public final void initComponent(Widget widget) { super.initComponent(widget); // Add standard per-child layout properties // NOTE: Not all layouts use these properties addProperty(PROPERTY_NAME_COLUMN, "" + ComponentConstants.DEFAULT_ROW_COLUMN, null, null, "Appearance", new TextPropertyEditor()); addProperty(PROPERTY_NAME_ROW, "" + ComponentConstants.DEFAULT_ROW_COLUMN, null, null, "Appearance", new TextPropertyEditor()); addWidthHeightProperties(); } protected void addWidthHeightProperties() {
// Path: appinventor/appengine/src/com/google/appinventor/client/Ode.java // public static final OdeMessages MESSAGES = GWT.create(OdeMessages.class); // Path: appinventor/appengine/src/com/google/appinventor/client/editor/simple/components/MockVisibleComponent.java import static com.google.appinventor.client.Ode.MESSAGES; import com.google.appinventor.client.editor.simple.SimpleEditor; import com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidLengthPropertyEditor; import com.google.appinventor.client.widgets.properties.TextPropertyEditor; import com.google.appinventor.components.common.ComponentConstants; import com.google.gwt.resources.client.ImageResource; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.Widget; // get the length is percent of Screen1 public static final int LENGTH_PERCENT_TAG = -1000; // Useful colors protected static final String COLOR_NONE = "00FFFFFF"; protected static final String COLOR_DEFAULT = "00000000"; /** * Creates a new instance of a visible component. * * @param editor editor of source file the component belongs to */ MockVisibleComponent(SimpleEditor editor, String type, ImageResource icon) { super(editor, type, new Image(icon)); } @Override public final void initComponent(Widget widget) { super.initComponent(widget); // Add standard per-child layout properties // NOTE: Not all layouts use these properties addProperty(PROPERTY_NAME_COLUMN, "" + ComponentConstants.DEFAULT_ROW_COLUMN, null, null, "Appearance", new TextPropertyEditor()); addProperty(PROPERTY_NAME_ROW, "" + ComponentConstants.DEFAULT_ROW_COLUMN, null, null, "Appearance", new TextPropertyEditor()); addWidthHeightProperties(); } protected void addWidthHeightProperties() {
addProperty(PROPERTY_NAME_WIDTH, "" + LENGTH_PREFERRED, MESSAGES.widthPropertyCaption(),
mit-dig/punya
appinventor/components/src/com/google/appinventor/components/scripts/ComponentProcessor.java
// Path: appinventor/components/src/com/google/appinventor/components/annotations/PropertyCategory.java // public enum PropertyCategory { // // TODO(user): i18n category names // BEHAVIOR("Behavior"), // APPEARANCE("Appearance"), // LINKED_DATA("Linked Data"), // DEPRECATED("Deprecated"), // UNSET("Unspecified"); // // private String name; // // PropertyCategory(String categoryName) { // name = categoryName; // } // // public String getName() { // return name; // } // }
import com.google.appinventor.components.annotations.DesignerComponent; import com.google.appinventor.components.annotations.DesignerProperty; import com.google.appinventor.components.annotations.PropertyCategory; import com.google.appinventor.components.annotations.SimpleEvent; import com.google.appinventor.components.annotations.SimpleFunction; import com.google.appinventor.components.annotations.SimpleObject; import com.google.appinventor.components.annotations.SimpleProperty; import com.google.appinventor.components.annotations.UsesAssets; import com.google.appinventor.components.annotations.UsesLibraries; import com.google.appinventor.components.annotations.UsesNativeLibraries; import com.google.appinventor.components.annotations.UsesPermissions; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import java.io.IOException; import java.io.Writer; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedMap; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.Messager; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.RoundEnvironment; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.ExecutableType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; import javax.tools.Diagnostic; import javax.tools.FileObject; import javax.tools.StandardLocation;
// returnType defaults to null } protected String getReturnType() { return returnType; } @Override public Method clone() { Method that = new Method(name, description, userVisible, deprecated); for (Parameter p : parameters) { that.addParameter(p.name, p.type); } that.returnType = returnType; return that; } @Override public int compareTo(Method f) { return name.compareTo(f.name); } } /** * Represents an App Inventor component property (annotated with * {@link SimpleProperty}). */ protected static final class Property implements Cloneable { protected final String name; private String description;
// Path: appinventor/components/src/com/google/appinventor/components/annotations/PropertyCategory.java // public enum PropertyCategory { // // TODO(user): i18n category names // BEHAVIOR("Behavior"), // APPEARANCE("Appearance"), // LINKED_DATA("Linked Data"), // DEPRECATED("Deprecated"), // UNSET("Unspecified"); // // private String name; // // PropertyCategory(String categoryName) { // name = categoryName; // } // // public String getName() { // return name; // } // } // Path: appinventor/components/src/com/google/appinventor/components/scripts/ComponentProcessor.java import com.google.appinventor.components.annotations.DesignerComponent; import com.google.appinventor.components.annotations.DesignerProperty; import com.google.appinventor.components.annotations.PropertyCategory; import com.google.appinventor.components.annotations.SimpleEvent; import com.google.appinventor.components.annotations.SimpleFunction; import com.google.appinventor.components.annotations.SimpleObject; import com.google.appinventor.components.annotations.SimpleProperty; import com.google.appinventor.components.annotations.UsesAssets; import com.google.appinventor.components.annotations.UsesLibraries; import com.google.appinventor.components.annotations.UsesNativeLibraries; import com.google.appinventor.components.annotations.UsesPermissions; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import java.io.IOException; import java.io.Writer; import java.util.List; import java.util.Map; import java.util.Set; import java.util.SortedMap; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.Messager; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.RoundEnvironment; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.type.DeclaredType; import javax.lang.model.type.ExecutableType; import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; import javax.tools.Diagnostic; import javax.tools.FileObject; import javax.tools.StandardLocation; // returnType defaults to null } protected String getReturnType() { return returnType; } @Override public Method clone() { Method that = new Method(name, description, userVisible, deprecated); for (Parameter p : parameters) { that.addParameter(p.name, p.type); } that.returnType = returnType; return that; } @Override public int compareTo(Method f) { return name.compareTo(f.name); } } /** * Represents an App Inventor component property (annotated with * {@link SimpleProperty}). */ protected static final class Property implements Cloneable { protected final String name; private String description;
private PropertyCategory propertyCategory;
mit-dig/punya
appinventor/appengine/src/com/google/appinventor/client/editor/simple/components/MockForm.java
// Path: appinventor/appengine/src/com/google/appinventor/client/Ode.java // public static final OdeMessages MESSAGES = GWT.create(OdeMessages.class); // // Path: appinventor/appengine/src/com/google/appinventor/shared/settings/SettingsConstants.java // public class SettingsConstants { // // private SettingsConstants() { // } // // /** // * General settings. // */ // public static final String USER_GENERAL_SETTINGS = "GeneralSettings"; // public static final String GENERAL_SETTINGS_CURRENT_PROJECT_ID = "CurrentProjectId"; // public static final String USER_TEMPLATE_URLS = "TemplateUrls"; // // If DISABLED_USER_URL is non-empty, then it is the URL to display in a frame // // inside of a modal dialog, displayed at login, with no exit. This is used to // // disable someone's account. The URL can be user specific in order to deliver // // a particular message to a particular user. // public static final String DISABLED_USER_URL = "DisabledUserUrl"; // // public static final String SPLASH_SETTINGS = "SplashSettings"; // // public static final String SPLASH_SETTINGS_SHOWSURVEY = "ShowSurvey"; // public static final String SPLASH_SETTINGS_DECLINED = "DeclinedSurvey"; // public static final String SPLASH_SETTINGS_VERSION = "SplashVersion"; // // /** // * YoungAndroid settings. // */ // // TODO(markf): There are some things which assume "SimpleSettings" which were hard to duplicate // public static final String USER_YOUNG_ANDROID_SETTINGS = "SimpleSettings"; // public static final String PROJECT_YOUNG_ANDROID_SETTINGS = "SimpleSettings"; // // // Project settings // public static final String YOUNG_ANDROID_SETTINGS_ICON = "Icon"; // public static final String YOUNG_ANDROID_SETTINGS_SHOW_HIDDEN_COMPONENTS = "ShowHiddenComponents"; // public static final String YOUNG_ANDROID_SETTINGS_PHONE_TABLET = "PhoneTablet"; // public static final String YOUNG_ANDROID_SETTINGS_VERSION_CODE = "VersionCode"; // public static final String YOUNG_ANDROID_SETTINGS_VERSION_NAME = "VersionName"; // public static final String YOUNG_ANDROID_SETTINGS_USES_LOCATION = "UsesLocation"; // public static final String YOUNG_ANDROID_SETTINGS_MAPS_KEY = "MapsKey"; // public static final String YOUNG_ANDROID_SETTINGS_SIZING = "Sizing"; // public static final String YOUNG_ANDROID_SETTINGS_APP_NAME = "AppName"; // }
import static com.google.appinventor.client.Ode.MESSAGES; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import com.google.appinventor.client.editor.simple.SimpleEditor; import com.google.appinventor.client.editor.simple.components.utils.PropertiesUtil; import com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidLengthPropertyEditor; import com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidVerticalAlignmentChoicePropertyEditor; import com.google.appinventor.client.output.OdeLog; import com.google.appinventor.client.properties.BadPropertyEditorException; import com.google.appinventor.client.widgets.properties.EditableProperties; import com.google.appinventor.shared.settings.SettingsConstants; import com.google.gwt.dom.client.DivElement; import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.Style; import com.google.gwt.user.client.ui.AbsolutePanel; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.DockPanel; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.ScrollPanel; import com.google.gwt.user.client.ui.TreeItem;
// super(editor, type, icon, myLayout); // but Java won't let me do that. super(editor, TYPE, images.form(), MockFormHelper.makeLayout()); // Note(hal): There better not be any calls to MockFormHelper before the // next instruction. Note that the Helper methods are synchronized to avoid possible // future problems if we ever have threads creating forms in parallel. myLayout = MockFormHelper.getLayout(); formWidget = new AbsolutePanel(); formWidget.setStylePrimaryName("ode-SimpleMockForm"); // Initialize mock form UI by adding the phone bar and title bar. formWidget.add(new PhoneBar()); titleBar = new TitleBar(); formWidget.add(titleBar); // Put a ScrollPanel around the rootPanel. scrollPanel = new ScrollPanel(rootPanel); formWidget.add(scrollPanel); //Add navigation bar at the bottom of the viewer. formWidget.add(new NavigationBar()); initComponent(formWidget); // Set up the initial state of the vertical alignment property editor and its dropdowns try { myVAlignmentPropertyEditor = PropertiesUtil.getVAlignmentEditor(properties); } catch (BadPropertyEditorException e) {
// Path: appinventor/appengine/src/com/google/appinventor/client/Ode.java // public static final OdeMessages MESSAGES = GWT.create(OdeMessages.class); // // Path: appinventor/appengine/src/com/google/appinventor/shared/settings/SettingsConstants.java // public class SettingsConstants { // // private SettingsConstants() { // } // // /** // * General settings. // */ // public static final String USER_GENERAL_SETTINGS = "GeneralSettings"; // public static final String GENERAL_SETTINGS_CURRENT_PROJECT_ID = "CurrentProjectId"; // public static final String USER_TEMPLATE_URLS = "TemplateUrls"; // // If DISABLED_USER_URL is non-empty, then it is the URL to display in a frame // // inside of a modal dialog, displayed at login, with no exit. This is used to // // disable someone's account. The URL can be user specific in order to deliver // // a particular message to a particular user. // public static final String DISABLED_USER_URL = "DisabledUserUrl"; // // public static final String SPLASH_SETTINGS = "SplashSettings"; // // public static final String SPLASH_SETTINGS_SHOWSURVEY = "ShowSurvey"; // public static final String SPLASH_SETTINGS_DECLINED = "DeclinedSurvey"; // public static final String SPLASH_SETTINGS_VERSION = "SplashVersion"; // // /** // * YoungAndroid settings. // */ // // TODO(markf): There are some things which assume "SimpleSettings" which were hard to duplicate // public static final String USER_YOUNG_ANDROID_SETTINGS = "SimpleSettings"; // public static final String PROJECT_YOUNG_ANDROID_SETTINGS = "SimpleSettings"; // // // Project settings // public static final String YOUNG_ANDROID_SETTINGS_ICON = "Icon"; // public static final String YOUNG_ANDROID_SETTINGS_SHOW_HIDDEN_COMPONENTS = "ShowHiddenComponents"; // public static final String YOUNG_ANDROID_SETTINGS_PHONE_TABLET = "PhoneTablet"; // public static final String YOUNG_ANDROID_SETTINGS_VERSION_CODE = "VersionCode"; // public static final String YOUNG_ANDROID_SETTINGS_VERSION_NAME = "VersionName"; // public static final String YOUNG_ANDROID_SETTINGS_USES_LOCATION = "UsesLocation"; // public static final String YOUNG_ANDROID_SETTINGS_MAPS_KEY = "MapsKey"; // public static final String YOUNG_ANDROID_SETTINGS_SIZING = "Sizing"; // public static final String YOUNG_ANDROID_SETTINGS_APP_NAME = "AppName"; // } // Path: appinventor/appengine/src/com/google/appinventor/client/editor/simple/components/MockForm.java import static com.google.appinventor.client.Ode.MESSAGES; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import com.google.appinventor.client.editor.simple.SimpleEditor; import com.google.appinventor.client.editor.simple.components.utils.PropertiesUtil; import com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidLengthPropertyEditor; import com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidVerticalAlignmentChoicePropertyEditor; import com.google.appinventor.client.output.OdeLog; import com.google.appinventor.client.properties.BadPropertyEditorException; import com.google.appinventor.client.widgets.properties.EditableProperties; import com.google.appinventor.shared.settings.SettingsConstants; import com.google.gwt.dom.client.DivElement; import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.Style; import com.google.gwt.user.client.ui.AbsolutePanel; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.DockPanel; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.ScrollPanel; import com.google.gwt.user.client.ui.TreeItem; // super(editor, type, icon, myLayout); // but Java won't let me do that. super(editor, TYPE, images.form(), MockFormHelper.makeLayout()); // Note(hal): There better not be any calls to MockFormHelper before the // next instruction. Note that the Helper methods are synchronized to avoid possible // future problems if we ever have threads creating forms in parallel. myLayout = MockFormHelper.getLayout(); formWidget = new AbsolutePanel(); formWidget.setStylePrimaryName("ode-SimpleMockForm"); // Initialize mock form UI by adding the phone bar and title bar. formWidget.add(new PhoneBar()); titleBar = new TitleBar(); formWidget.add(titleBar); // Put a ScrollPanel around the rootPanel. scrollPanel = new ScrollPanel(rootPanel); formWidget.add(scrollPanel); //Add navigation bar at the bottom of the viewer. formWidget.add(new NavigationBar()); initComponent(formWidget); // Set up the initial state of the vertical alignment property editor and its dropdowns try { myVAlignmentPropertyEditor = PropertiesUtil.getVAlignmentEditor(properties); } catch (BadPropertyEditorException e) {
OdeLog.log(MESSAGES.badAlignmentPropertyEditorForArrangement());
mit-dig/punya
appinventor/appengine/src/com/google/appinventor/client/editor/simple/components/MockForm.java
// Path: appinventor/appengine/src/com/google/appinventor/client/Ode.java // public static final OdeMessages MESSAGES = GWT.create(OdeMessages.class); // // Path: appinventor/appengine/src/com/google/appinventor/shared/settings/SettingsConstants.java // public class SettingsConstants { // // private SettingsConstants() { // } // // /** // * General settings. // */ // public static final String USER_GENERAL_SETTINGS = "GeneralSettings"; // public static final String GENERAL_SETTINGS_CURRENT_PROJECT_ID = "CurrentProjectId"; // public static final String USER_TEMPLATE_URLS = "TemplateUrls"; // // If DISABLED_USER_URL is non-empty, then it is the URL to display in a frame // // inside of a modal dialog, displayed at login, with no exit. This is used to // // disable someone's account. The URL can be user specific in order to deliver // // a particular message to a particular user. // public static final String DISABLED_USER_URL = "DisabledUserUrl"; // // public static final String SPLASH_SETTINGS = "SplashSettings"; // // public static final String SPLASH_SETTINGS_SHOWSURVEY = "ShowSurvey"; // public static final String SPLASH_SETTINGS_DECLINED = "DeclinedSurvey"; // public static final String SPLASH_SETTINGS_VERSION = "SplashVersion"; // // /** // * YoungAndroid settings. // */ // // TODO(markf): There are some things which assume "SimpleSettings" which were hard to duplicate // public static final String USER_YOUNG_ANDROID_SETTINGS = "SimpleSettings"; // public static final String PROJECT_YOUNG_ANDROID_SETTINGS = "SimpleSettings"; // // // Project settings // public static final String YOUNG_ANDROID_SETTINGS_ICON = "Icon"; // public static final String YOUNG_ANDROID_SETTINGS_SHOW_HIDDEN_COMPONENTS = "ShowHiddenComponents"; // public static final String YOUNG_ANDROID_SETTINGS_PHONE_TABLET = "PhoneTablet"; // public static final String YOUNG_ANDROID_SETTINGS_VERSION_CODE = "VersionCode"; // public static final String YOUNG_ANDROID_SETTINGS_VERSION_NAME = "VersionName"; // public static final String YOUNG_ANDROID_SETTINGS_USES_LOCATION = "UsesLocation"; // public static final String YOUNG_ANDROID_SETTINGS_MAPS_KEY = "MapsKey"; // public static final String YOUNG_ANDROID_SETTINGS_SIZING = "Sizing"; // public static final String YOUNG_ANDROID_SETTINGS_APP_NAME = "AppName"; // }
import static com.google.appinventor.client.Ode.MESSAGES; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import com.google.appinventor.client.editor.simple.SimpleEditor; import com.google.appinventor.client.editor.simple.components.utils.PropertiesUtil; import com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidLengthPropertyEditor; import com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidVerticalAlignmentChoicePropertyEditor; import com.google.appinventor.client.output.OdeLog; import com.google.appinventor.client.properties.BadPropertyEditorException; import com.google.appinventor.client.widgets.properties.EditableProperties; import com.google.appinventor.shared.settings.SettingsConstants; import com.google.gwt.dom.client.DivElement; import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.Style; import com.google.gwt.user.client.ui.AbsolutePanel; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.DockPanel; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.ScrollPanel; import com.google.gwt.user.client.ui.TreeItem;
} else { screenWidth = PORTRAIT_WIDTH; screenHeight = PORTRAIT_HEIGHT; landscape = false; } usableScreenHeight = screenHeight - PhoneBar.HEIGHT - TitleBar.HEIGHT - NavigationBar.HEIGHT; resizePanel(screenWidth, screenHeight); changeProperty(PROPERTY_NAME_WIDTH, "" + screenWidth); boolean scrollable = Boolean.parseBoolean(getPropertyValue(PROPERTY_NAME_SCROLLABLE)); if (!scrollable) { changeProperty(PROPERTY_NAME_HEIGHT, "" + usableScreenHeight); } } } private void setScrollableProperty(String text) { if (hasProperty(PROPERTY_NAME_HEIGHT)) { final boolean scrollable = Boolean.parseBoolean(text); int heightHint = scrollable ? LENGTH_PREFERRED : usableScreenHeight; changeProperty(PROPERTY_NAME_HEIGHT, "" + heightHint); } } private void setIconProperty(String icon) { // The Icon property actually applies to the application and is only visible on Screen1. // When we load a form that is not Screen1, this method will be called with the default value // for icon (empty string). We need to ignore that. if (editor.isScreen1()) { editor.getProjectEditor().changeProjectSettingsProperty(
// Path: appinventor/appengine/src/com/google/appinventor/client/Ode.java // public static final OdeMessages MESSAGES = GWT.create(OdeMessages.class); // // Path: appinventor/appengine/src/com/google/appinventor/shared/settings/SettingsConstants.java // public class SettingsConstants { // // private SettingsConstants() { // } // // /** // * General settings. // */ // public static final String USER_GENERAL_SETTINGS = "GeneralSettings"; // public static final String GENERAL_SETTINGS_CURRENT_PROJECT_ID = "CurrentProjectId"; // public static final String USER_TEMPLATE_URLS = "TemplateUrls"; // // If DISABLED_USER_URL is non-empty, then it is the URL to display in a frame // // inside of a modal dialog, displayed at login, with no exit. This is used to // // disable someone's account. The URL can be user specific in order to deliver // // a particular message to a particular user. // public static final String DISABLED_USER_URL = "DisabledUserUrl"; // // public static final String SPLASH_SETTINGS = "SplashSettings"; // // public static final String SPLASH_SETTINGS_SHOWSURVEY = "ShowSurvey"; // public static final String SPLASH_SETTINGS_DECLINED = "DeclinedSurvey"; // public static final String SPLASH_SETTINGS_VERSION = "SplashVersion"; // // /** // * YoungAndroid settings. // */ // // TODO(markf): There are some things which assume "SimpleSettings" which were hard to duplicate // public static final String USER_YOUNG_ANDROID_SETTINGS = "SimpleSettings"; // public static final String PROJECT_YOUNG_ANDROID_SETTINGS = "SimpleSettings"; // // // Project settings // public static final String YOUNG_ANDROID_SETTINGS_ICON = "Icon"; // public static final String YOUNG_ANDROID_SETTINGS_SHOW_HIDDEN_COMPONENTS = "ShowHiddenComponents"; // public static final String YOUNG_ANDROID_SETTINGS_PHONE_TABLET = "PhoneTablet"; // public static final String YOUNG_ANDROID_SETTINGS_VERSION_CODE = "VersionCode"; // public static final String YOUNG_ANDROID_SETTINGS_VERSION_NAME = "VersionName"; // public static final String YOUNG_ANDROID_SETTINGS_USES_LOCATION = "UsesLocation"; // public static final String YOUNG_ANDROID_SETTINGS_MAPS_KEY = "MapsKey"; // public static final String YOUNG_ANDROID_SETTINGS_SIZING = "Sizing"; // public static final String YOUNG_ANDROID_SETTINGS_APP_NAME = "AppName"; // } // Path: appinventor/appengine/src/com/google/appinventor/client/editor/simple/components/MockForm.java import static com.google.appinventor.client.Ode.MESSAGES; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import com.google.appinventor.client.editor.simple.SimpleEditor; import com.google.appinventor.client.editor.simple.components.utils.PropertiesUtil; import com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidLengthPropertyEditor; import com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidVerticalAlignmentChoicePropertyEditor; import com.google.appinventor.client.output.OdeLog; import com.google.appinventor.client.properties.BadPropertyEditorException; import com.google.appinventor.client.widgets.properties.EditableProperties; import com.google.appinventor.shared.settings.SettingsConstants; import com.google.gwt.dom.client.DivElement; import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.Style; import com.google.gwt.user.client.ui.AbsolutePanel; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.DockPanel; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.Image; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.ScrollPanel; import com.google.gwt.user.client.ui.TreeItem; } else { screenWidth = PORTRAIT_WIDTH; screenHeight = PORTRAIT_HEIGHT; landscape = false; } usableScreenHeight = screenHeight - PhoneBar.HEIGHT - TitleBar.HEIGHT - NavigationBar.HEIGHT; resizePanel(screenWidth, screenHeight); changeProperty(PROPERTY_NAME_WIDTH, "" + screenWidth); boolean scrollable = Boolean.parseBoolean(getPropertyValue(PROPERTY_NAME_SCROLLABLE)); if (!scrollable) { changeProperty(PROPERTY_NAME_HEIGHT, "" + usableScreenHeight); } } } private void setScrollableProperty(String text) { if (hasProperty(PROPERTY_NAME_HEIGHT)) { final boolean scrollable = Boolean.parseBoolean(text); int heightHint = scrollable ? LENGTH_PREFERRED : usableScreenHeight; changeProperty(PROPERTY_NAME_HEIGHT, "" + heightHint); } } private void setIconProperty(String icon) { // The Icon property actually applies to the application and is only visible on Screen1. // When we load a form that is not Screen1, this method will be called with the default value // for icon (empty string). We need to ignore that. if (editor.isScreen1()) { editor.getProjectEditor().changeProjectSettingsProperty(
SettingsConstants.PROJECT_YOUNG_ANDROID_SETTINGS,
mit-dig/punya
appinventor/appengine/src/com/google/appinventor/client/editor/simple/components/MockImageSprite.java
// Path: appinventor/appengine/src/com/google/appinventor/client/Ode.java // public static final OdeMessages MESSAGES = GWT.create(OdeMessages.class);
import static com.google.appinventor.client.Ode.MESSAGES; import com.google.appinventor.client.editor.simple.SimpleEditor; import com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidLengthPropertyEditor;
// -*- mode: java; c-basic-offset: 2; -*- // Copyright 2009-2011 Google, All Rights reserved // Copyright 2011-2012 MIT, All rights reserved // Released under the Apache License, Version 2.0 // http://www.apache.org/licenses/LICENSE-2.0 package com.google.appinventor.client.editor.simple.components; /** * Mock ImageSprite component. * */ public final class MockImageSprite extends MockImageBase implements MockSprite { /** * Component type name. */ public static final String TYPE = "ImageSprite"; /** * Creates a new MockImageSprite component. * * @param editor editor of source file the component belongs to */ public MockImageSprite(SimpleEditor editor) { super(editor, TYPE, images.imageSprite()); } @Override protected void addWidthHeightProperties() { // Percent based size will scale images strangely, so remove percent based sizes
// Path: appinventor/appengine/src/com/google/appinventor/client/Ode.java // public static final OdeMessages MESSAGES = GWT.create(OdeMessages.class); // Path: appinventor/appengine/src/com/google/appinventor/client/editor/simple/components/MockImageSprite.java import static com.google.appinventor.client.Ode.MESSAGES; import com.google.appinventor.client.editor.simple.SimpleEditor; import com.google.appinventor.client.editor.youngandroid.properties.YoungAndroidLengthPropertyEditor; // -*- mode: java; c-basic-offset: 2; -*- // Copyright 2009-2011 Google, All Rights reserved // Copyright 2011-2012 MIT, All rights reserved // Released under the Apache License, Version 2.0 // http://www.apache.org/licenses/LICENSE-2.0 package com.google.appinventor.client.editor.simple.components; /** * Mock ImageSprite component. * */ public final class MockImageSprite extends MockImageBase implements MockSprite { /** * Component type name. */ public static final String TYPE = "ImageSprite"; /** * Creates a new MockImageSprite component. * * @param editor editor of source file the component belongs to */ public MockImageSprite(SimpleEditor editor) { super(editor, TYPE, images.imageSprite()); } @Override protected void addWidthHeightProperties() { // Percent based size will scale images strangely, so remove percent based sizes
addProperty(PROPERTY_NAME_WIDTH, "" + LENGTH_PREFERRED, MESSAGES.widthPropertyCaption(),
authlete/java-oauth-server
src/main/java/com/authlete/jaxrs/server/federation/FederationConfig.java
// Path: src/main/java/com/authlete/jaxrs/server/federation/ConfigValidationHelper.java // public static void ensureNotEmpty(String key, Object value) throws IllegalStateException // { // if (value == null) // { // throw lack(key); // } // }
import static com.authlete.jaxrs.server.federation.ConfigValidationHelper.ensureNotEmpty; import java.io.Serializable;
public ServerConfig getServer() { return server; } public FederationConfig setServer(ServerConfig server) { this.server = server; return this; } public ClientConfig getClient() { return client; } public FederationConfig setClient(ClientConfig client) { this.client = client; return this; } public void validate() throws IllegalStateException {
// Path: src/main/java/com/authlete/jaxrs/server/federation/ConfigValidationHelper.java // public static void ensureNotEmpty(String key, Object value) throws IllegalStateException // { // if (value == null) // { // throw lack(key); // } // } // Path: src/main/java/com/authlete/jaxrs/server/federation/FederationConfig.java import static com.authlete.jaxrs.server.federation.ConfigValidationHelper.ensureNotEmpty; import java.io.Serializable; public ServerConfig getServer() { return server; } public FederationConfig setServer(ServerConfig server) { this.server = server; return this; } public ClientConfig getClient() { return client; } public FederationConfig setClient(ClientConfig client) { this.client = client; return this; } public void validate() throws IllegalStateException {
ensureNotEmpty("id", id);
authlete/java-oauth-server
src/main/java/com/authlete/jaxrs/server/ServerConfig.java
// Path: src/main/java/com/authlete/jaxrs/server/ad/type/Mode.java // public enum Mode // { // /** // * The synchronous mode. // */ // SYNC, // // // /** // * The asynchronous mode. // */ // ASYNC, // // // /** // * The poll mode. // */ // POLL // ; // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ServerProperties.java // public class ServerProperties extends TypedSystemProperties // { // private static final ResourceBundle RESOURCE_BUNDLE; // // // static // { // ResourceBundle bundle = null; // // try // { // bundle = ResourceBundle.getBundle("java-oauth-server"); // } // catch (MissingResourceException mre) // { // // ignore // mre.printStackTrace(); // } // // RESOURCE_BUNDLE = bundle; // } // // // @Override // public String getString(String key, String defaultValue) // { // if (key == null) // { // return defaultValue; // } // // // If the parameter identified by the key exists in the system properties. // if (super.contains(key)) // { // // Use the value of the system property. // return super.getString(key, defaultValue); // } // // // If "java-oauth-server.properties" is not available. // if (RESOURCE_BUNDLE == null) // { // // Use the default value. // return defaultValue; // } // // try // { // // Search "java-oauth-server.properties" for the parameter. // return RESOURCE_BUNDLE.getString(key); // } // catch (MissingResourceException e) // { // // Return the default value. // return defaultValue; // } // } // }
import com.authlete.jaxrs.server.ad.type.Mode; import com.authlete.jaxrs.server.util.ServerProperties;
/* * Copyright (C) 2019 Authlete, 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.authlete.jaxrs.server; /** * A class for configuration of this server. * * @author Hideki Ikeda */ public class ServerConfig { /** * Properties. */
// Path: src/main/java/com/authlete/jaxrs/server/ad/type/Mode.java // public enum Mode // { // /** // * The synchronous mode. // */ // SYNC, // // // /** // * The asynchronous mode. // */ // ASYNC, // // // /** // * The poll mode. // */ // POLL // ; // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ServerProperties.java // public class ServerProperties extends TypedSystemProperties // { // private static final ResourceBundle RESOURCE_BUNDLE; // // // static // { // ResourceBundle bundle = null; // // try // { // bundle = ResourceBundle.getBundle("java-oauth-server"); // } // catch (MissingResourceException mre) // { // // ignore // mre.printStackTrace(); // } // // RESOURCE_BUNDLE = bundle; // } // // // @Override // public String getString(String key, String defaultValue) // { // if (key == null) // { // return defaultValue; // } // // // If the parameter identified by the key exists in the system properties. // if (super.contains(key)) // { // // Use the value of the system property. // return super.getString(key, defaultValue); // } // // // If "java-oauth-server.properties" is not available. // if (RESOURCE_BUNDLE == null) // { // // Use the default value. // return defaultValue; // } // // try // { // // Search "java-oauth-server.properties" for the parameter. // return RESOURCE_BUNDLE.getString(key); // } // catch (MissingResourceException e) // { // // Return the default value. // return defaultValue; // } // } // } // Path: src/main/java/com/authlete/jaxrs/server/ServerConfig.java import com.authlete.jaxrs.server.ad.type.Mode; import com.authlete.jaxrs.server.util.ServerProperties; /* * Copyright (C) 2019 Authlete, 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.authlete.jaxrs.server; /** * A class for configuration of this server. * * @author Hideki Ikeda */ public class ServerConfig { /** * Properties. */
private static final ServerProperties sProperties = new ServerProperties();
authlete/java-oauth-server
src/main/java/com/authlete/jaxrs/server/ServerConfig.java
// Path: src/main/java/com/authlete/jaxrs/server/ad/type/Mode.java // public enum Mode // { // /** // * The synchronous mode. // */ // SYNC, // // // /** // * The asynchronous mode. // */ // ASYNC, // // // /** // * The poll mode. // */ // POLL // ; // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ServerProperties.java // public class ServerProperties extends TypedSystemProperties // { // private static final ResourceBundle RESOURCE_BUNDLE; // // // static // { // ResourceBundle bundle = null; // // try // { // bundle = ResourceBundle.getBundle("java-oauth-server"); // } // catch (MissingResourceException mre) // { // // ignore // mre.printStackTrace(); // } // // RESOURCE_BUNDLE = bundle; // } // // // @Override // public String getString(String key, String defaultValue) // { // if (key == null) // { // return defaultValue; // } // // // If the parameter identified by the key exists in the system properties. // if (super.contains(key)) // { // // Use the value of the system property. // return super.getString(key, defaultValue); // } // // // If "java-oauth-server.properties" is not available. // if (RESOURCE_BUNDLE == null) // { // // Use the default value. // return defaultValue; // } // // try // { // // Search "java-oauth-server.properties" for the parameter. // return RESOURCE_BUNDLE.getString(key); // } // catch (MissingResourceException e) // { // // Return the default value. // return defaultValue; // } // } // }
import com.authlete.jaxrs.server.ad.type.Mode; import com.authlete.jaxrs.server.util.ServerProperties;
/* * Copyright (C) 2019 Authlete, 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.authlete.jaxrs.server; /** * A class for configuration of this server. * * @author Hideki Ikeda */ public class ServerConfig { /** * Properties. */ private static final ServerProperties sProperties = new ServerProperties(); /** * Property keys. */ private static final String AUTHLETE_AD_BASE_URL_KEY = "authlete.ad.base_url"; private static final String AUTHLETE_AD_WORKSPACE_KEY = "authlete.ad.workspace"; private static final String AUTHLETE_AD_MODE_KEY = "authlete.ad.mode"; private static final String AUTHLETE_AD_SYNC_CONNECT_TIMEOUT_KEY = "authlete.ad.sync.connect_timeout"; private static final String AUTHLETE_AD_SYNC_ADDITIONAL_READ_TIMEOUT_KEY = "authlete.ad.sync.additional_read_timeout"; private static final String AUTHLETE_AD_ASYNC_CONNECT_TIMEOUT_KEY = "authlete.ad.async.connect_timeout"; private static final String AUTHLETE_AD_ASYNC_READ_TIMEOUT_KEY = "authlete.ad.async.read_timeout"; private static final String AUTHLETE_AD_POLL_CONNECT_TIMEOUT_KEY = "authlete.ad.poll.connect_timeout"; private static final String AUTHLETE_AD_POLL_RESULT_READ_TIMEOUT_KEY = "authlete.ad.poll.read_timeout"; private static final String AUTHLETE_AD_POLL_RESULT_CONNECT_TIMEOUT_KEY = "authlete.ad.poll.result.connect_timeout"; private static final String AUTHLETE_AD_POLL_READ_TIMEOUT_KEY = "authlete.ad.poll.result.read_timeout"; private static final String AUTHLETE_AD_POLL_MAX_COUNT_KEY = "authlete.ad.poll.max_count"; private static final String AUTHLETE_AD_POLL_INTERVAL_KEY = "authlete.ad.poll.interval"; private static final String AUTHLETE_AD_AUTH_TIMEOUT_RATIO_KEY = "authlete.ad.auth_timeout_ratio"; /** * Default configuration values. */ private static final String DEFAULT_AUTHLETE_AD_BASE_URL = "https://cibasim.authlete.com";
// Path: src/main/java/com/authlete/jaxrs/server/ad/type/Mode.java // public enum Mode // { // /** // * The synchronous mode. // */ // SYNC, // // // /** // * The asynchronous mode. // */ // ASYNC, // // // /** // * The poll mode. // */ // POLL // ; // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ServerProperties.java // public class ServerProperties extends TypedSystemProperties // { // private static final ResourceBundle RESOURCE_BUNDLE; // // // static // { // ResourceBundle bundle = null; // // try // { // bundle = ResourceBundle.getBundle("java-oauth-server"); // } // catch (MissingResourceException mre) // { // // ignore // mre.printStackTrace(); // } // // RESOURCE_BUNDLE = bundle; // } // // // @Override // public String getString(String key, String defaultValue) // { // if (key == null) // { // return defaultValue; // } // // // If the parameter identified by the key exists in the system properties. // if (super.contains(key)) // { // // Use the value of the system property. // return super.getString(key, defaultValue); // } // // // If "java-oauth-server.properties" is not available. // if (RESOURCE_BUNDLE == null) // { // // Use the default value. // return defaultValue; // } // // try // { // // Search "java-oauth-server.properties" for the parameter. // return RESOURCE_BUNDLE.getString(key); // } // catch (MissingResourceException e) // { // // Return the default value. // return defaultValue; // } // } // } // Path: src/main/java/com/authlete/jaxrs/server/ServerConfig.java import com.authlete.jaxrs.server.ad.type.Mode; import com.authlete.jaxrs.server.util.ServerProperties; /* * Copyright (C) 2019 Authlete, 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.authlete.jaxrs.server; /** * A class for configuration of this server. * * @author Hideki Ikeda */ public class ServerConfig { /** * Properties. */ private static final ServerProperties sProperties = new ServerProperties(); /** * Property keys. */ private static final String AUTHLETE_AD_BASE_URL_KEY = "authlete.ad.base_url"; private static final String AUTHLETE_AD_WORKSPACE_KEY = "authlete.ad.workspace"; private static final String AUTHLETE_AD_MODE_KEY = "authlete.ad.mode"; private static final String AUTHLETE_AD_SYNC_CONNECT_TIMEOUT_KEY = "authlete.ad.sync.connect_timeout"; private static final String AUTHLETE_AD_SYNC_ADDITIONAL_READ_TIMEOUT_KEY = "authlete.ad.sync.additional_read_timeout"; private static final String AUTHLETE_AD_ASYNC_CONNECT_TIMEOUT_KEY = "authlete.ad.async.connect_timeout"; private static final String AUTHLETE_AD_ASYNC_READ_TIMEOUT_KEY = "authlete.ad.async.read_timeout"; private static final String AUTHLETE_AD_POLL_CONNECT_TIMEOUT_KEY = "authlete.ad.poll.connect_timeout"; private static final String AUTHLETE_AD_POLL_RESULT_READ_TIMEOUT_KEY = "authlete.ad.poll.read_timeout"; private static final String AUTHLETE_AD_POLL_RESULT_CONNECT_TIMEOUT_KEY = "authlete.ad.poll.result.connect_timeout"; private static final String AUTHLETE_AD_POLL_READ_TIMEOUT_KEY = "authlete.ad.poll.result.read_timeout"; private static final String AUTHLETE_AD_POLL_MAX_COUNT_KEY = "authlete.ad.poll.max_count"; private static final String AUTHLETE_AD_POLL_INTERVAL_KEY = "authlete.ad.poll.interval"; private static final String AUTHLETE_AD_AUTH_TIMEOUT_RATIO_KEY = "authlete.ad.auth_timeout_ratio"; /** * Default configuration values. */ private static final String DEFAULT_AUTHLETE_AD_BASE_URL = "https://cibasim.authlete.com";
private static final Mode DEFAULT_AUTHLETE_AD_MODE = Mode.SYNC;
authlete/java-oauth-server
src/main/java/com/authlete/jaxrs/server/util/ExceptionUtil.java
// Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response badRequest(String entity) // { // return builderForTextPlain(Status.BAD_REQUEST, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response unauthorized(String entity, String challenge) // { // return builderForTextPlain(Status.UNAUTHORIZED, entity) // .header(HttpHeaders.WWW_AUTHENTICATE, challenge) // .build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response notFound(String entity) // { // return builderForTextPlain(Status.NOT_FOUND, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response internalServerError(String entity) // { // return builderForTextPlain(Status.INTERNAL_SERVER_ERROR, entity).build(); // }
import static com.authlete.jaxrs.server.util.ResponseUtil.badRequest; import static com.authlete.jaxrs.server.util.ResponseUtil.unauthorized; import static com.authlete.jaxrs.server.util.ResponseUtil.notFound; import static com.authlete.jaxrs.server.util.ResponseUtil.internalServerError; import javax.ws.rs.WebApplicationException; import org.glassfish.jersey.server.mvc.Viewable;
/* * Copyright (C) 2019 Authlete, 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.authlete.jaxrs.server.util; /** * Utility class for exceptions. * * @author Hideki Ikeda */ public class ExceptionUtil { /** * Create an exception indicating "400 Bad Request". * * @param entity * An entity to contain in the response of the exception. * * @return * An exception indicating "400 Bad Request". */ public static WebApplicationException badRequestException(String entity) {
// Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response badRequest(String entity) // { // return builderForTextPlain(Status.BAD_REQUEST, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response unauthorized(String entity, String challenge) // { // return builderForTextPlain(Status.UNAUTHORIZED, entity) // .header(HttpHeaders.WWW_AUTHENTICATE, challenge) // .build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response notFound(String entity) // { // return builderForTextPlain(Status.NOT_FOUND, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response internalServerError(String entity) // { // return builderForTextPlain(Status.INTERNAL_SERVER_ERROR, entity).build(); // } // Path: src/main/java/com/authlete/jaxrs/server/util/ExceptionUtil.java import static com.authlete.jaxrs.server.util.ResponseUtil.badRequest; import static com.authlete.jaxrs.server.util.ResponseUtil.unauthorized; import static com.authlete.jaxrs.server.util.ResponseUtil.notFound; import static com.authlete.jaxrs.server.util.ResponseUtil.internalServerError; import javax.ws.rs.WebApplicationException; import org.glassfish.jersey.server.mvc.Viewable; /* * Copyright (C) 2019 Authlete, 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.authlete.jaxrs.server.util; /** * Utility class for exceptions. * * @author Hideki Ikeda */ public class ExceptionUtil { /** * Create an exception indicating "400 Bad Request". * * @param entity * An entity to contain in the response of the exception. * * @return * An exception indicating "400 Bad Request". */ public static WebApplicationException badRequestException(String entity) {
return new WebApplicationException(entity, badRequest(entity));
authlete/java-oauth-server
src/main/java/com/authlete/jaxrs/server/util/ExceptionUtil.java
// Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response badRequest(String entity) // { // return builderForTextPlain(Status.BAD_REQUEST, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response unauthorized(String entity, String challenge) // { // return builderForTextPlain(Status.UNAUTHORIZED, entity) // .header(HttpHeaders.WWW_AUTHENTICATE, challenge) // .build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response notFound(String entity) // { // return builderForTextPlain(Status.NOT_FOUND, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response internalServerError(String entity) // { // return builderForTextPlain(Status.INTERNAL_SERVER_ERROR, entity).build(); // }
import static com.authlete.jaxrs.server.util.ResponseUtil.badRequest; import static com.authlete.jaxrs.server.util.ResponseUtil.unauthorized; import static com.authlete.jaxrs.server.util.ResponseUtil.notFound; import static com.authlete.jaxrs.server.util.ResponseUtil.internalServerError; import javax.ws.rs.WebApplicationException; import org.glassfish.jersey.server.mvc.Viewable;
/* * Copyright (C) 2019 Authlete, 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.authlete.jaxrs.server.util; /** * Utility class for exceptions. * * @author Hideki Ikeda */ public class ExceptionUtil { /** * Create an exception indicating "400 Bad Request". * * @param entity * An entity to contain in the response of the exception. * * @return * An exception indicating "400 Bad Request". */ public static WebApplicationException badRequestException(String entity) { return new WebApplicationException(entity, badRequest(entity)); } /** * Create an exception indicating "400 Bad Request". * * @param entity * An entity to contain in the response of the exception. * * @return * An exception indicating "400 Bad Request". */ public static WebApplicationException badRequestException(Viewable entity) { return new WebApplicationException(badRequest(entity)); } /** * Create an exception indicating "401 Unauthorized". * * @param entity * An entity to contain in the response of the exception. * * @param challenge * The value of the "WWW-Authenticate" header of the response of the * exception. * * @return * An exception indicating "401 Unauthorized". */ public static WebApplicationException unauthorizedException(String entity, String challenge) {
// Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response badRequest(String entity) // { // return builderForTextPlain(Status.BAD_REQUEST, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response unauthorized(String entity, String challenge) // { // return builderForTextPlain(Status.UNAUTHORIZED, entity) // .header(HttpHeaders.WWW_AUTHENTICATE, challenge) // .build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response notFound(String entity) // { // return builderForTextPlain(Status.NOT_FOUND, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response internalServerError(String entity) // { // return builderForTextPlain(Status.INTERNAL_SERVER_ERROR, entity).build(); // } // Path: src/main/java/com/authlete/jaxrs/server/util/ExceptionUtil.java import static com.authlete.jaxrs.server.util.ResponseUtil.badRequest; import static com.authlete.jaxrs.server.util.ResponseUtil.unauthorized; import static com.authlete.jaxrs.server.util.ResponseUtil.notFound; import static com.authlete.jaxrs.server.util.ResponseUtil.internalServerError; import javax.ws.rs.WebApplicationException; import org.glassfish.jersey.server.mvc.Viewable; /* * Copyright (C) 2019 Authlete, 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.authlete.jaxrs.server.util; /** * Utility class for exceptions. * * @author Hideki Ikeda */ public class ExceptionUtil { /** * Create an exception indicating "400 Bad Request". * * @param entity * An entity to contain in the response of the exception. * * @return * An exception indicating "400 Bad Request". */ public static WebApplicationException badRequestException(String entity) { return new WebApplicationException(entity, badRequest(entity)); } /** * Create an exception indicating "400 Bad Request". * * @param entity * An entity to contain in the response of the exception. * * @return * An exception indicating "400 Bad Request". */ public static WebApplicationException badRequestException(Viewable entity) { return new WebApplicationException(badRequest(entity)); } /** * Create an exception indicating "401 Unauthorized". * * @param entity * An entity to contain in the response of the exception. * * @param challenge * The value of the "WWW-Authenticate" header of the response of the * exception. * * @return * An exception indicating "401 Unauthorized". */ public static WebApplicationException unauthorizedException(String entity, String challenge) {
return new WebApplicationException(entity, unauthorized(entity, challenge));
authlete/java-oauth-server
src/main/java/com/authlete/jaxrs/server/util/ExceptionUtil.java
// Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response badRequest(String entity) // { // return builderForTextPlain(Status.BAD_REQUEST, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response unauthorized(String entity, String challenge) // { // return builderForTextPlain(Status.UNAUTHORIZED, entity) // .header(HttpHeaders.WWW_AUTHENTICATE, challenge) // .build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response notFound(String entity) // { // return builderForTextPlain(Status.NOT_FOUND, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response internalServerError(String entity) // { // return builderForTextPlain(Status.INTERNAL_SERVER_ERROR, entity).build(); // }
import static com.authlete.jaxrs.server.util.ResponseUtil.badRequest; import static com.authlete.jaxrs.server.util.ResponseUtil.unauthorized; import static com.authlete.jaxrs.server.util.ResponseUtil.notFound; import static com.authlete.jaxrs.server.util.ResponseUtil.internalServerError; import javax.ws.rs.WebApplicationException; import org.glassfish.jersey.server.mvc.Viewable;
/* * Copyright (C) 2019 Authlete, 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.authlete.jaxrs.server.util; /** * Utility class for exceptions. * * @author Hideki Ikeda */ public class ExceptionUtil { /** * Create an exception indicating "400 Bad Request". * * @param entity * An entity to contain in the response of the exception. * * @return * An exception indicating "400 Bad Request". */ public static WebApplicationException badRequestException(String entity) { return new WebApplicationException(entity, badRequest(entity)); } /** * Create an exception indicating "400 Bad Request". * * @param entity * An entity to contain in the response of the exception. * * @return * An exception indicating "400 Bad Request". */ public static WebApplicationException badRequestException(Viewable entity) { return new WebApplicationException(badRequest(entity)); } /** * Create an exception indicating "401 Unauthorized". * * @param entity * An entity to contain in the response of the exception. * * @param challenge * The value of the "WWW-Authenticate" header of the response of the * exception. * * @return * An exception indicating "401 Unauthorized". */ public static WebApplicationException unauthorizedException(String entity, String challenge) { return new WebApplicationException(entity, unauthorized(entity, challenge)); } /** * Create an exception indicating "401 Unauthorized". * * @param entity * An entity to contain in the response of the exception. * * @param challenge * The value of the "WWW-Authenticate" header of the response of the * exception. * * @return * An exception indicating "401 Unauthorized". */ public static WebApplicationException unauthorizedException(Viewable entity, String challenge) { return new WebApplicationException(unauthorized(entity, challenge)); } /** * Create an exception indicating "404 Not Found". * * @param entity * An entity to contain in the response of the exception. * * @return * An exception indicating "404 Not Found". */ public static WebApplicationException notFoundException(String entity) {
// Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response badRequest(String entity) // { // return builderForTextPlain(Status.BAD_REQUEST, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response unauthorized(String entity, String challenge) // { // return builderForTextPlain(Status.UNAUTHORIZED, entity) // .header(HttpHeaders.WWW_AUTHENTICATE, challenge) // .build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response notFound(String entity) // { // return builderForTextPlain(Status.NOT_FOUND, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response internalServerError(String entity) // { // return builderForTextPlain(Status.INTERNAL_SERVER_ERROR, entity).build(); // } // Path: src/main/java/com/authlete/jaxrs/server/util/ExceptionUtil.java import static com.authlete.jaxrs.server.util.ResponseUtil.badRequest; import static com.authlete.jaxrs.server.util.ResponseUtil.unauthorized; import static com.authlete.jaxrs.server.util.ResponseUtil.notFound; import static com.authlete.jaxrs.server.util.ResponseUtil.internalServerError; import javax.ws.rs.WebApplicationException; import org.glassfish.jersey.server.mvc.Viewable; /* * Copyright (C) 2019 Authlete, 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.authlete.jaxrs.server.util; /** * Utility class for exceptions. * * @author Hideki Ikeda */ public class ExceptionUtil { /** * Create an exception indicating "400 Bad Request". * * @param entity * An entity to contain in the response of the exception. * * @return * An exception indicating "400 Bad Request". */ public static WebApplicationException badRequestException(String entity) { return new WebApplicationException(entity, badRequest(entity)); } /** * Create an exception indicating "400 Bad Request". * * @param entity * An entity to contain in the response of the exception. * * @return * An exception indicating "400 Bad Request". */ public static WebApplicationException badRequestException(Viewable entity) { return new WebApplicationException(badRequest(entity)); } /** * Create an exception indicating "401 Unauthorized". * * @param entity * An entity to contain in the response of the exception. * * @param challenge * The value of the "WWW-Authenticate" header of the response of the * exception. * * @return * An exception indicating "401 Unauthorized". */ public static WebApplicationException unauthorizedException(String entity, String challenge) { return new WebApplicationException(entity, unauthorized(entity, challenge)); } /** * Create an exception indicating "401 Unauthorized". * * @param entity * An entity to contain in the response of the exception. * * @param challenge * The value of the "WWW-Authenticate" header of the response of the * exception. * * @return * An exception indicating "401 Unauthorized". */ public static WebApplicationException unauthorizedException(Viewable entity, String challenge) { return new WebApplicationException(unauthorized(entity, challenge)); } /** * Create an exception indicating "404 Not Found". * * @param entity * An entity to contain in the response of the exception. * * @return * An exception indicating "404 Not Found". */ public static WebApplicationException notFoundException(String entity) {
return new WebApplicationException(entity, notFound(entity));
authlete/java-oauth-server
src/main/java/com/authlete/jaxrs/server/util/ExceptionUtil.java
// Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response badRequest(String entity) // { // return builderForTextPlain(Status.BAD_REQUEST, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response unauthorized(String entity, String challenge) // { // return builderForTextPlain(Status.UNAUTHORIZED, entity) // .header(HttpHeaders.WWW_AUTHENTICATE, challenge) // .build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response notFound(String entity) // { // return builderForTextPlain(Status.NOT_FOUND, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response internalServerError(String entity) // { // return builderForTextPlain(Status.INTERNAL_SERVER_ERROR, entity).build(); // }
import static com.authlete.jaxrs.server.util.ResponseUtil.badRequest; import static com.authlete.jaxrs.server.util.ResponseUtil.unauthorized; import static com.authlete.jaxrs.server.util.ResponseUtil.notFound; import static com.authlete.jaxrs.server.util.ResponseUtil.internalServerError; import javax.ws.rs.WebApplicationException; import org.glassfish.jersey.server.mvc.Viewable;
/* * Copyright (C) 2019 Authlete, 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.authlete.jaxrs.server.util; /** * Utility class for exceptions. * * @author Hideki Ikeda */ public class ExceptionUtil { /** * Create an exception indicating "400 Bad Request". * * @param entity * An entity to contain in the response of the exception. * * @return * An exception indicating "400 Bad Request". */ public static WebApplicationException badRequestException(String entity) { return new WebApplicationException(entity, badRequest(entity)); } /** * Create an exception indicating "400 Bad Request". * * @param entity * An entity to contain in the response of the exception. * * @return * An exception indicating "400 Bad Request". */ public static WebApplicationException badRequestException(Viewable entity) { return new WebApplicationException(badRequest(entity)); } /** * Create an exception indicating "401 Unauthorized". * * @param entity * An entity to contain in the response of the exception. * * @param challenge * The value of the "WWW-Authenticate" header of the response of the * exception. * * @return * An exception indicating "401 Unauthorized". */ public static WebApplicationException unauthorizedException(String entity, String challenge) { return new WebApplicationException(entity, unauthorized(entity, challenge)); } /** * Create an exception indicating "401 Unauthorized". * * @param entity * An entity to contain in the response of the exception. * * @param challenge * The value of the "WWW-Authenticate" header of the response of the * exception. * * @return * An exception indicating "401 Unauthorized". */ public static WebApplicationException unauthorizedException(Viewable entity, String challenge) { return new WebApplicationException(unauthorized(entity, challenge)); } /** * Create an exception indicating "404 Not Found". * * @param entity * An entity to contain in the response of the exception. * * @return * An exception indicating "404 Not Found". */ public static WebApplicationException notFoundException(String entity) { return new WebApplicationException(entity, notFound(entity)); } /** * Create an exception indicating "404 Not Found". * * @param entity * An entity to contain in the response of the exception. * * @return * An exception indicating "404 Not Found". */ public static WebApplicationException notFoundException(Viewable entity) { return new WebApplicationException(notFound(entity)); } /** * Create an exception indicating "500 Internal Server Error". * * @param entity * An entity to contain in the response of the exception. * * @return * An exception indicating "500 Internal Server Error". */ public static WebApplicationException internalServerErrorException(String entity) {
// Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response badRequest(String entity) // { // return builderForTextPlain(Status.BAD_REQUEST, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response unauthorized(String entity, String challenge) // { // return builderForTextPlain(Status.UNAUTHORIZED, entity) // .header(HttpHeaders.WWW_AUTHENTICATE, challenge) // .build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response notFound(String entity) // { // return builderForTextPlain(Status.NOT_FOUND, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response internalServerError(String entity) // { // return builderForTextPlain(Status.INTERNAL_SERVER_ERROR, entity).build(); // } // Path: src/main/java/com/authlete/jaxrs/server/util/ExceptionUtil.java import static com.authlete.jaxrs.server.util.ResponseUtil.badRequest; import static com.authlete.jaxrs.server.util.ResponseUtil.unauthorized; import static com.authlete.jaxrs.server.util.ResponseUtil.notFound; import static com.authlete.jaxrs.server.util.ResponseUtil.internalServerError; import javax.ws.rs.WebApplicationException; import org.glassfish.jersey.server.mvc.Viewable; /* * Copyright (C) 2019 Authlete, 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.authlete.jaxrs.server.util; /** * Utility class for exceptions. * * @author Hideki Ikeda */ public class ExceptionUtil { /** * Create an exception indicating "400 Bad Request". * * @param entity * An entity to contain in the response of the exception. * * @return * An exception indicating "400 Bad Request". */ public static WebApplicationException badRequestException(String entity) { return new WebApplicationException(entity, badRequest(entity)); } /** * Create an exception indicating "400 Bad Request". * * @param entity * An entity to contain in the response of the exception. * * @return * An exception indicating "400 Bad Request". */ public static WebApplicationException badRequestException(Viewable entity) { return new WebApplicationException(badRequest(entity)); } /** * Create an exception indicating "401 Unauthorized". * * @param entity * An entity to contain in the response of the exception. * * @param challenge * The value of the "WWW-Authenticate" header of the response of the * exception. * * @return * An exception indicating "401 Unauthorized". */ public static WebApplicationException unauthorizedException(String entity, String challenge) { return new WebApplicationException(entity, unauthorized(entity, challenge)); } /** * Create an exception indicating "401 Unauthorized". * * @param entity * An entity to contain in the response of the exception. * * @param challenge * The value of the "WWW-Authenticate" header of the response of the * exception. * * @return * An exception indicating "401 Unauthorized". */ public static WebApplicationException unauthorizedException(Viewable entity, String challenge) { return new WebApplicationException(unauthorized(entity, challenge)); } /** * Create an exception indicating "404 Not Found". * * @param entity * An entity to contain in the response of the exception. * * @return * An exception indicating "404 Not Found". */ public static WebApplicationException notFoundException(String entity) { return new WebApplicationException(entity, notFound(entity)); } /** * Create an exception indicating "404 Not Found". * * @param entity * An entity to contain in the response of the exception. * * @return * An exception indicating "404 Not Found". */ public static WebApplicationException notFoundException(Viewable entity) { return new WebApplicationException(notFound(entity)); } /** * Create an exception indicating "500 Internal Server Error". * * @param entity * An entity to contain in the response of the exception. * * @return * An exception indicating "500 Internal Server Error". */ public static WebApplicationException internalServerErrorException(String entity) {
return new WebApplicationException(entity, internalServerError(entity));
authlete/java-oauth-server
src/main/java/com/authlete/jaxrs/server/federation/ServerConfig.java
// Path: src/main/java/com/authlete/jaxrs/server/federation/ConfigValidationHelper.java // public static void ensureNotEmpty(String key, Object value) throws IllegalStateException // { // if (value == null) // { // throw lack(key); // } // } // // Path: src/main/java/com/authlete/jaxrs/server/federation/ConfigValidationHelper.java // public static void ensureUri(String key, String value) throws IllegalStateException // { // try // { // new URI(value); // } // catch (URISyntaxException e) // { // throw illegalState("The value of ''{0}'' in the ID federation configuration is malformed: {1}", key, value); // } // }
import static com.authlete.jaxrs.server.federation.ConfigValidationHelper.ensureNotEmpty; import static com.authlete.jaxrs.server.federation.ConfigValidationHelper.ensureUri; import java.io.Serializable;
/* * Copyright (C) 2022 Authlete, 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.authlete.jaxrs.server.federation; /** * Server configuration for ID federation. * * <pre> * { * "name": "(display name of the OpenID Provider)", * "issuer": "(issuer identifier of the OpenID Provider)" * } * </pre> * * <p> * The value of {@code "issuer"} must match the value of {@code "issuer"} * in the discovery document of the OpenID Provider. The OpenID Provider * must expose its discovery document at * <code><i>{issuer}</i>/.well-known/openid-configuration</code>. * </p> * * @see FederationConfig */ public class ServerConfig implements Serializable { private static final long serialVersionUID = 1L; private String name; private String issuer; public String getName() { return name; } public ServerConfig setName(String name) { this.name = name; return this; } public String getIssuer() { return issuer; } public ServerConfig setIssuer(String issuer) { this.issuer = issuer; return this; } public void validate() throws IllegalStateException {
// Path: src/main/java/com/authlete/jaxrs/server/federation/ConfigValidationHelper.java // public static void ensureNotEmpty(String key, Object value) throws IllegalStateException // { // if (value == null) // { // throw lack(key); // } // } // // Path: src/main/java/com/authlete/jaxrs/server/federation/ConfigValidationHelper.java // public static void ensureUri(String key, String value) throws IllegalStateException // { // try // { // new URI(value); // } // catch (URISyntaxException e) // { // throw illegalState("The value of ''{0}'' in the ID federation configuration is malformed: {1}", key, value); // } // } // Path: src/main/java/com/authlete/jaxrs/server/federation/ServerConfig.java import static com.authlete.jaxrs.server.federation.ConfigValidationHelper.ensureNotEmpty; import static com.authlete.jaxrs.server.federation.ConfigValidationHelper.ensureUri; import java.io.Serializable; /* * Copyright (C) 2022 Authlete, 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.authlete.jaxrs.server.federation; /** * Server configuration for ID federation. * * <pre> * { * "name": "(display name of the OpenID Provider)", * "issuer": "(issuer identifier of the OpenID Provider)" * } * </pre> * * <p> * The value of {@code "issuer"} must match the value of {@code "issuer"} * in the discovery document of the OpenID Provider. The OpenID Provider * must expose its discovery document at * <code><i>{issuer}</i>/.well-known/openid-configuration</code>. * </p> * * @see FederationConfig */ public class ServerConfig implements Serializable { private static final long serialVersionUID = 1L; private String name; private String issuer; public String getName() { return name; } public ServerConfig setName(String name) { this.name = name; return this; } public String getIssuer() { return issuer; } public ServerConfig setIssuer(String issuer) { this.issuer = issuer; return this; } public void validate() throws IllegalStateException {
ensureNotEmpty("server/name", name);
authlete/java-oauth-server
src/main/java/com/authlete/jaxrs/server/federation/ServerConfig.java
// Path: src/main/java/com/authlete/jaxrs/server/federation/ConfigValidationHelper.java // public static void ensureNotEmpty(String key, Object value) throws IllegalStateException // { // if (value == null) // { // throw lack(key); // } // } // // Path: src/main/java/com/authlete/jaxrs/server/federation/ConfigValidationHelper.java // public static void ensureUri(String key, String value) throws IllegalStateException // { // try // { // new URI(value); // } // catch (URISyntaxException e) // { // throw illegalState("The value of ''{0}'' in the ID federation configuration is malformed: {1}", key, value); // } // }
import static com.authlete.jaxrs.server.federation.ConfigValidationHelper.ensureNotEmpty; import static com.authlete.jaxrs.server.federation.ConfigValidationHelper.ensureUri; import java.io.Serializable;
/* * Copyright (C) 2022 Authlete, 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.authlete.jaxrs.server.federation; /** * Server configuration for ID federation. * * <pre> * { * "name": "(display name of the OpenID Provider)", * "issuer": "(issuer identifier of the OpenID Provider)" * } * </pre> * * <p> * The value of {@code "issuer"} must match the value of {@code "issuer"} * in the discovery document of the OpenID Provider. The OpenID Provider * must expose its discovery document at * <code><i>{issuer}</i>/.well-known/openid-configuration</code>. * </p> * * @see FederationConfig */ public class ServerConfig implements Serializable { private static final long serialVersionUID = 1L; private String name; private String issuer; public String getName() { return name; } public ServerConfig setName(String name) { this.name = name; return this; } public String getIssuer() { return issuer; } public ServerConfig setIssuer(String issuer) { this.issuer = issuer; return this; } public void validate() throws IllegalStateException { ensureNotEmpty("server/name", name); ensureNotEmpty("server/issuer", issuer);
// Path: src/main/java/com/authlete/jaxrs/server/federation/ConfigValidationHelper.java // public static void ensureNotEmpty(String key, Object value) throws IllegalStateException // { // if (value == null) // { // throw lack(key); // } // } // // Path: src/main/java/com/authlete/jaxrs/server/federation/ConfigValidationHelper.java // public static void ensureUri(String key, String value) throws IllegalStateException // { // try // { // new URI(value); // } // catch (URISyntaxException e) // { // throw illegalState("The value of ''{0}'' in the ID federation configuration is malformed: {1}", key, value); // } // } // Path: src/main/java/com/authlete/jaxrs/server/federation/ServerConfig.java import static com.authlete.jaxrs.server.federation.ConfigValidationHelper.ensureNotEmpty; import static com.authlete.jaxrs.server.federation.ConfigValidationHelper.ensureUri; import java.io.Serializable; /* * Copyright (C) 2022 Authlete, 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.authlete.jaxrs.server.federation; /** * Server configuration for ID federation. * * <pre> * { * "name": "(display name of the OpenID Provider)", * "issuer": "(issuer identifier of the OpenID Provider)" * } * </pre> * * <p> * The value of {@code "issuer"} must match the value of {@code "issuer"} * in the discovery document of the OpenID Provider. The OpenID Provider * must expose its discovery document at * <code><i>{issuer}</i>/.well-known/openid-configuration</code>. * </p> * * @see FederationConfig */ public class ServerConfig implements Serializable { private static final long serialVersionUID = 1L; private String name; private String issuer; public String getName() { return name; } public ServerConfig setName(String name) { this.name = name; return this; } public String getIssuer() { return issuer; } public ServerConfig setIssuer(String issuer) { this.issuer = issuer; return this; } public void validate() throws IllegalStateException { ensureNotEmpty("server/name", name); ensureNotEmpty("server/issuer", issuer);
ensureUri("server/issuer", issuer);
authlete/java-oauth-server
src/main/java/com/authlete/jaxrs/server/ad/dto/AsyncAuthenticationCallbackRequest.java
// Path: src/main/java/com/authlete/jaxrs/server/ad/type/Result.java // public enum Result // { // /** // * The result showing that an end-user authorized a client application's request. // */ // allow, // // // /** // * The result showing that an end-user denied a client application's request. // */ // deny, // // // /** // * The result showing that timeout occurred during end-user authentication and // * authorization process. // */ // timeout // ; // }
import java.io.Serializable; import javax.xml.bind.annotation.XmlElement; import com.authlete.jaxrs.server.ad.type.Result;
/* * Copyright (C) 2019 Authlete, 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.authlete.jaxrs.server.ad.dto; /** * The class representing a callback request that is made from <a href="https://cibasim.authlete.com"> * Authlete CIBA authentication device simulator</a> when it is used in asynchronous * mode. * * <p> * Note that, before the authorization server receives this callback request from * the authentication device simulator, it is assumed that the authorization server * has made a request to the authentication device simulator's <a href="https://app.swaggerhub.com/apis-docs/Authlete/cibasim/1.0.0#/default/post_api_authenticate_async"> * /api/authenticate/async API</a> for end-user authentication and authorization. * This callback request contains the result of the end-user authentication and * authorization. * </p> * * @see <a href="https://cibasim.authlete.com">Authlete CIBA authentication * device simulator</a> * * @see <a href="https://app.swaggerhub.com/apis-docs/Authlete/cibasim/1.0.0#/default/post_api_authenticate_async"> * /api/authenticate/async API</a> * * @author Hideki Ikeda */ public class AsyncAuthenticationCallbackRequest implements Serializable { private static final long serialVersionUID = 1L; @XmlElement(name = "request_id") private String requestId;
// Path: src/main/java/com/authlete/jaxrs/server/ad/type/Result.java // public enum Result // { // /** // * The result showing that an end-user authorized a client application's request. // */ // allow, // // // /** // * The result showing that an end-user denied a client application's request. // */ // deny, // // // /** // * The result showing that timeout occurred during end-user authentication and // * authorization process. // */ // timeout // ; // } // Path: src/main/java/com/authlete/jaxrs/server/ad/dto/AsyncAuthenticationCallbackRequest.java import java.io.Serializable; import javax.xml.bind.annotation.XmlElement; import com.authlete.jaxrs.server.ad.type.Result; /* * Copyright (C) 2019 Authlete, 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.authlete.jaxrs.server.ad.dto; /** * The class representing a callback request that is made from <a href="https://cibasim.authlete.com"> * Authlete CIBA authentication device simulator</a> when it is used in asynchronous * mode. * * <p> * Note that, before the authorization server receives this callback request from * the authentication device simulator, it is assumed that the authorization server * has made a request to the authentication device simulator's <a href="https://app.swaggerhub.com/apis-docs/Authlete/cibasim/1.0.0#/default/post_api_authenticate_async"> * /api/authenticate/async API</a> for end-user authentication and authorization. * This callback request contains the result of the end-user authentication and * authorization. * </p> * * @see <a href="https://cibasim.authlete.com">Authlete CIBA authentication * device simulator</a> * * @see <a href="https://app.swaggerhub.com/apis-docs/Authlete/cibasim/1.0.0#/default/post_api_authenticate_async"> * /api/authenticate/async API</a> * * @author Hideki Ikeda */ public class AsyncAuthenticationCallbackRequest implements Serializable { private static final long serialVersionUID = 1L; @XmlElement(name = "request_id") private String requestId;
private Result result;
authlete/java-oauth-server
src/main/java/com/authlete/jaxrs/server/api/AuthzPageModel.java
// Path: src/main/java/com/authlete/jaxrs/server/federation/FederationConfig.java // public class FederationConfig implements Serializable // { // private static final long serialVersionUID = 1L; // // // private String id; // private ServerConfig server; // private ClientConfig client; // // // public String getId() // { // return id; // } // // // public FederationConfig setId(String id) // { // this.id = id; // // return this; // } // // // public ServerConfig getServer() // { // return server; // } // // // public FederationConfig setServer(ServerConfig server) // { // this.server = server; // // return this; // } // // // public ClientConfig getClient() // { // return client; // } // // // public FederationConfig setClient(ClientConfig client) // { // this.client = client; // // return this; // } // // // public void validate() throws IllegalStateException // { // ensureNotEmpty("id", id); // ensureNotEmpty("server", server); // ensureNotEmpty("client", client); // // server.validate(); // client.validate(); // } // }
import com.authlete.common.dto.AuthorizationResponse; import com.authlete.common.types.User; import com.authlete.jaxrs.AuthorizationPageModel; import com.authlete.jaxrs.server.federation.FederationConfig;
/* * Copyright (C) 2022 Authlete, 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.authlete.jaxrs.server.api; /** * Data used to render the authorization page. */ public class AuthzPageModel extends AuthorizationPageModel { private static final long serialVersionUID = 1L;
// Path: src/main/java/com/authlete/jaxrs/server/federation/FederationConfig.java // public class FederationConfig implements Serializable // { // private static final long serialVersionUID = 1L; // // // private String id; // private ServerConfig server; // private ClientConfig client; // // // public String getId() // { // return id; // } // // // public FederationConfig setId(String id) // { // this.id = id; // // return this; // } // // // public ServerConfig getServer() // { // return server; // } // // // public FederationConfig setServer(ServerConfig server) // { // this.server = server; // // return this; // } // // // public ClientConfig getClient() // { // return client; // } // // // public FederationConfig setClient(ClientConfig client) // { // this.client = client; // // return this; // } // // // public void validate() throws IllegalStateException // { // ensureNotEmpty("id", id); // ensureNotEmpty("server", server); // ensureNotEmpty("client", client); // // server.validate(); // client.validate(); // } // } // Path: src/main/java/com/authlete/jaxrs/server/api/AuthzPageModel.java import com.authlete.common.dto.AuthorizationResponse; import com.authlete.common.types.User; import com.authlete.jaxrs.AuthorizationPageModel; import com.authlete.jaxrs.server.federation.FederationConfig; /* * Copyright (C) 2022 Authlete, 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.authlete.jaxrs.server.api; /** * Data used to render the authorization page. */ public class AuthzPageModel extends AuthorizationPageModel { private static final long serialVersionUID = 1L;
private FederationConfig[] federations;
authlete/java-oauth-server
src/main/java/com/authlete/jaxrs/server/api/device/DeviceVerificationRequestHandlerSpiImpl.java
// Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response badRequest(String entity) // { // return builderForTextPlain(Status.BAD_REQUEST, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response internalServerError(String entity) // { // return builderForTextPlain(Status.INTERNAL_SERVER_ERROR, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response notFound(String entity) // { // return builderForTextPlain(Status.NOT_FOUND, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response ok(String entity) // { // return builderForTextPlain(Status.OK, entity).build(); // }
import static com.authlete.jaxrs.server.util.ResponseUtil.badRequest; import static com.authlete.jaxrs.server.util.ResponseUtil.internalServerError; import static com.authlete.jaxrs.server.util.ResponseUtil.notFound; import static com.authlete.jaxrs.server.util.ResponseUtil.ok; import javax.servlet.http.HttpSession; import javax.ws.rs.core.Response; import org.glassfish.jersey.server.mvc.Viewable; import com.authlete.common.dto.DeviceVerificationResponse; import com.authlete.common.types.User; import com.authlete.jaxrs.DeviceAuthorizationPageModel; import com.authlete.jaxrs.DeviceVerificationPageModel; import com.authlete.jaxrs.spi.DeviceVerificationRequestHandlerSpiAdapter;
/* * Copyright (C) 2019 Authlete, 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.authlete.jaxrs.server.api.device; /** * Empty implementation of {@link DeviceVerificationRequestHandlerSpi} interface. * * @author Hideki Ikeda */ public class DeviceVerificationRequestHandlerSpiImpl extends DeviceVerificationRequestHandlerSpiAdapter { /** * The page template to ask the end-user for a user code. */ private static final String VERIFICATION_PAGE_TEMPLATE = "/device/verification"; /** * The page template to ask the end-user for authorization. */ private static final String AUTHORIZATION_PAGE_TEMPLATE = "/device/authorization"; /** * The current user session. */ private HttpSession mSession; /** * The user code given by the user.. */ private String mUserCode; public DeviceVerificationRequestHandlerSpiImpl(HttpSession session, String userCode) { mSession = session; mUserCode = userCode; } @Override public String getUserCode() { return mUserCode; } @Override public Response onValid(DeviceVerificationResponse info) { // Ask the user to authorize the client. // Store some information to the user's session for later use. mSession.setAttribute("userCode", mUserCode); mSession.setAttribute("claimNames", info.getClaimNames()); mSession.setAttribute("acrs", info.getAcrs()); // The model for rendering the authorization page. DeviceAuthorizationPageModel model = new DeviceAuthorizationPageModel(info); // Create a response having the page.
// Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response badRequest(String entity) // { // return builderForTextPlain(Status.BAD_REQUEST, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response internalServerError(String entity) // { // return builderForTextPlain(Status.INTERNAL_SERVER_ERROR, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response notFound(String entity) // { // return builderForTextPlain(Status.NOT_FOUND, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response ok(String entity) // { // return builderForTextPlain(Status.OK, entity).build(); // } // Path: src/main/java/com/authlete/jaxrs/server/api/device/DeviceVerificationRequestHandlerSpiImpl.java import static com.authlete.jaxrs.server.util.ResponseUtil.badRequest; import static com.authlete.jaxrs.server.util.ResponseUtil.internalServerError; import static com.authlete.jaxrs.server.util.ResponseUtil.notFound; import static com.authlete.jaxrs.server.util.ResponseUtil.ok; import javax.servlet.http.HttpSession; import javax.ws.rs.core.Response; import org.glassfish.jersey.server.mvc.Viewable; import com.authlete.common.dto.DeviceVerificationResponse; import com.authlete.common.types.User; import com.authlete.jaxrs.DeviceAuthorizationPageModel; import com.authlete.jaxrs.DeviceVerificationPageModel; import com.authlete.jaxrs.spi.DeviceVerificationRequestHandlerSpiAdapter; /* * Copyright (C) 2019 Authlete, 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.authlete.jaxrs.server.api.device; /** * Empty implementation of {@link DeviceVerificationRequestHandlerSpi} interface. * * @author Hideki Ikeda */ public class DeviceVerificationRequestHandlerSpiImpl extends DeviceVerificationRequestHandlerSpiAdapter { /** * The page template to ask the end-user for a user code. */ private static final String VERIFICATION_PAGE_TEMPLATE = "/device/verification"; /** * The page template to ask the end-user for authorization. */ private static final String AUTHORIZATION_PAGE_TEMPLATE = "/device/authorization"; /** * The current user session. */ private HttpSession mSession; /** * The user code given by the user.. */ private String mUserCode; public DeviceVerificationRequestHandlerSpiImpl(HttpSession session, String userCode) { mSession = session; mUserCode = userCode; } @Override public String getUserCode() { return mUserCode; } @Override public Response onValid(DeviceVerificationResponse info) { // Ask the user to authorize the client. // Store some information to the user's session for later use. mSession.setAttribute("userCode", mUserCode); mSession.setAttribute("claimNames", info.getClaimNames()); mSession.setAttribute("acrs", info.getAcrs()); // The model for rendering the authorization page. DeviceAuthorizationPageModel model = new DeviceAuthorizationPageModel(info); // Create a response having the page.
return ok(new Viewable(AUTHORIZATION_PAGE_TEMPLATE, model));
authlete/java-oauth-server
src/main/java/com/authlete/jaxrs/server/api/device/DeviceVerificationRequestHandlerSpiImpl.java
// Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response badRequest(String entity) // { // return builderForTextPlain(Status.BAD_REQUEST, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response internalServerError(String entity) // { // return builderForTextPlain(Status.INTERNAL_SERVER_ERROR, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response notFound(String entity) // { // return builderForTextPlain(Status.NOT_FOUND, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response ok(String entity) // { // return builderForTextPlain(Status.OK, entity).build(); // }
import static com.authlete.jaxrs.server.util.ResponseUtil.badRequest; import static com.authlete.jaxrs.server.util.ResponseUtil.internalServerError; import static com.authlete.jaxrs.server.util.ResponseUtil.notFound; import static com.authlete.jaxrs.server.util.ResponseUtil.ok; import javax.servlet.http.HttpSession; import javax.ws.rs.core.Response; import org.glassfish.jersey.server.mvc.Viewable; import com.authlete.common.dto.DeviceVerificationResponse; import com.authlete.common.types.User; import com.authlete.jaxrs.DeviceAuthorizationPageModel; import com.authlete.jaxrs.DeviceVerificationPageModel; import com.authlete.jaxrs.spi.DeviceVerificationRequestHandlerSpiAdapter;
/* * Copyright (C) 2019 Authlete, 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.authlete.jaxrs.server.api.device; /** * Empty implementation of {@link DeviceVerificationRequestHandlerSpi} interface. * * @author Hideki Ikeda */ public class DeviceVerificationRequestHandlerSpiImpl extends DeviceVerificationRequestHandlerSpiAdapter { /** * The page template to ask the end-user for a user code. */ private static final String VERIFICATION_PAGE_TEMPLATE = "/device/verification"; /** * The page template to ask the end-user for authorization. */ private static final String AUTHORIZATION_PAGE_TEMPLATE = "/device/authorization"; /** * The current user session. */ private HttpSession mSession; /** * The user code given by the user.. */ private String mUserCode; public DeviceVerificationRequestHandlerSpiImpl(HttpSession session, String userCode) { mSession = session; mUserCode = userCode; } @Override public String getUserCode() { return mUserCode; } @Override public Response onValid(DeviceVerificationResponse info) { // Ask the user to authorize the client. // Store some information to the user's session for later use. mSession.setAttribute("userCode", mUserCode); mSession.setAttribute("claimNames", info.getClaimNames()); mSession.setAttribute("acrs", info.getAcrs()); // The model for rendering the authorization page. DeviceAuthorizationPageModel model = new DeviceAuthorizationPageModel(info); // Create a response having the page. return ok(new Viewable(AUTHORIZATION_PAGE_TEMPLATE, model)); } @Override public Response onExpired() { // Urge the user to re-initiate the device flow.
// Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response badRequest(String entity) // { // return builderForTextPlain(Status.BAD_REQUEST, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response internalServerError(String entity) // { // return builderForTextPlain(Status.INTERNAL_SERVER_ERROR, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response notFound(String entity) // { // return builderForTextPlain(Status.NOT_FOUND, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response ok(String entity) // { // return builderForTextPlain(Status.OK, entity).build(); // } // Path: src/main/java/com/authlete/jaxrs/server/api/device/DeviceVerificationRequestHandlerSpiImpl.java import static com.authlete.jaxrs.server.util.ResponseUtil.badRequest; import static com.authlete.jaxrs.server.util.ResponseUtil.internalServerError; import static com.authlete.jaxrs.server.util.ResponseUtil.notFound; import static com.authlete.jaxrs.server.util.ResponseUtil.ok; import javax.servlet.http.HttpSession; import javax.ws.rs.core.Response; import org.glassfish.jersey.server.mvc.Viewable; import com.authlete.common.dto.DeviceVerificationResponse; import com.authlete.common.types.User; import com.authlete.jaxrs.DeviceAuthorizationPageModel; import com.authlete.jaxrs.DeviceVerificationPageModel; import com.authlete.jaxrs.spi.DeviceVerificationRequestHandlerSpiAdapter; /* * Copyright (C) 2019 Authlete, 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.authlete.jaxrs.server.api.device; /** * Empty implementation of {@link DeviceVerificationRequestHandlerSpi} interface. * * @author Hideki Ikeda */ public class DeviceVerificationRequestHandlerSpiImpl extends DeviceVerificationRequestHandlerSpiAdapter { /** * The page template to ask the end-user for a user code. */ private static final String VERIFICATION_PAGE_TEMPLATE = "/device/verification"; /** * The page template to ask the end-user for authorization. */ private static final String AUTHORIZATION_PAGE_TEMPLATE = "/device/authorization"; /** * The current user session. */ private HttpSession mSession; /** * The user code given by the user.. */ private String mUserCode; public DeviceVerificationRequestHandlerSpiImpl(HttpSession session, String userCode) { mSession = session; mUserCode = userCode; } @Override public String getUserCode() { return mUserCode; } @Override public Response onValid(DeviceVerificationResponse info) { // Ask the user to authorize the client. // Store some information to the user's session for later use. mSession.setAttribute("userCode", mUserCode); mSession.setAttribute("claimNames", info.getClaimNames()); mSession.setAttribute("acrs", info.getAcrs()); // The model for rendering the authorization page. DeviceAuthorizationPageModel model = new DeviceAuthorizationPageModel(info); // Create a response having the page. return ok(new Viewable(AUTHORIZATION_PAGE_TEMPLATE, model)); } @Override public Response onExpired() { // Urge the user to re-initiate the device flow.
return badRequest("The user Code Expired. Please re-initiate the flow again.");
authlete/java-oauth-server
src/main/java/com/authlete/jaxrs/server/api/device/DeviceVerificationRequestHandlerSpiImpl.java
// Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response badRequest(String entity) // { // return builderForTextPlain(Status.BAD_REQUEST, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response internalServerError(String entity) // { // return builderForTextPlain(Status.INTERNAL_SERVER_ERROR, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response notFound(String entity) // { // return builderForTextPlain(Status.NOT_FOUND, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response ok(String entity) // { // return builderForTextPlain(Status.OK, entity).build(); // }
import static com.authlete.jaxrs.server.util.ResponseUtil.badRequest; import static com.authlete.jaxrs.server.util.ResponseUtil.internalServerError; import static com.authlete.jaxrs.server.util.ResponseUtil.notFound; import static com.authlete.jaxrs.server.util.ResponseUtil.ok; import javax.servlet.http.HttpSession; import javax.ws.rs.core.Response; import org.glassfish.jersey.server.mvc.Viewable; import com.authlete.common.dto.DeviceVerificationResponse; import com.authlete.common.types.User; import com.authlete.jaxrs.DeviceAuthorizationPageModel; import com.authlete.jaxrs.DeviceVerificationPageModel; import com.authlete.jaxrs.spi.DeviceVerificationRequestHandlerSpiAdapter;
// Create a response having the page. return ok(new Viewable(AUTHORIZATION_PAGE_TEMPLATE, model)); } @Override public Response onExpired() { // Urge the user to re-initiate the device flow. return badRequest("The user Code Expired. Please re-initiate the flow again."); } @Override public Response onNotExist() { // Urge the user to re-input a valid user code. // The user. User user = (User)mSession.getAttribute("user"); // The model for rendering the verification page. DeviceVerificationPageModel model = new DeviceVerificationPageModel() .setUserCode(mUserCode) .setUser(user) .setNotification("The user code does not exist."); // Return a response of "404 Not Found" having the verification page and // urge the user to re-input a valid user code.
// Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response badRequest(String entity) // { // return builderForTextPlain(Status.BAD_REQUEST, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response internalServerError(String entity) // { // return builderForTextPlain(Status.INTERNAL_SERVER_ERROR, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response notFound(String entity) // { // return builderForTextPlain(Status.NOT_FOUND, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response ok(String entity) // { // return builderForTextPlain(Status.OK, entity).build(); // } // Path: src/main/java/com/authlete/jaxrs/server/api/device/DeviceVerificationRequestHandlerSpiImpl.java import static com.authlete.jaxrs.server.util.ResponseUtil.badRequest; import static com.authlete.jaxrs.server.util.ResponseUtil.internalServerError; import static com.authlete.jaxrs.server.util.ResponseUtil.notFound; import static com.authlete.jaxrs.server.util.ResponseUtil.ok; import javax.servlet.http.HttpSession; import javax.ws.rs.core.Response; import org.glassfish.jersey.server.mvc.Viewable; import com.authlete.common.dto.DeviceVerificationResponse; import com.authlete.common.types.User; import com.authlete.jaxrs.DeviceAuthorizationPageModel; import com.authlete.jaxrs.DeviceVerificationPageModel; import com.authlete.jaxrs.spi.DeviceVerificationRequestHandlerSpiAdapter; // Create a response having the page. return ok(new Viewable(AUTHORIZATION_PAGE_TEMPLATE, model)); } @Override public Response onExpired() { // Urge the user to re-initiate the device flow. return badRequest("The user Code Expired. Please re-initiate the flow again."); } @Override public Response onNotExist() { // Urge the user to re-input a valid user code. // The user. User user = (User)mSession.getAttribute("user"); // The model for rendering the verification page. DeviceVerificationPageModel model = new DeviceVerificationPageModel() .setUserCode(mUserCode) .setUser(user) .setNotification("The user code does not exist."); // Return a response of "404 Not Found" having the verification page and // urge the user to re-input a valid user code.
return notFound(new Viewable(VERIFICATION_PAGE_TEMPLATE, model));
authlete/java-oauth-server
src/main/java/com/authlete/jaxrs/server/api/device/DeviceVerificationRequestHandlerSpiImpl.java
// Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response badRequest(String entity) // { // return builderForTextPlain(Status.BAD_REQUEST, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response internalServerError(String entity) // { // return builderForTextPlain(Status.INTERNAL_SERVER_ERROR, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response notFound(String entity) // { // return builderForTextPlain(Status.NOT_FOUND, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response ok(String entity) // { // return builderForTextPlain(Status.OK, entity).build(); // }
import static com.authlete.jaxrs.server.util.ResponseUtil.badRequest; import static com.authlete.jaxrs.server.util.ResponseUtil.internalServerError; import static com.authlete.jaxrs.server.util.ResponseUtil.notFound; import static com.authlete.jaxrs.server.util.ResponseUtil.ok; import javax.servlet.http.HttpSession; import javax.ws.rs.core.Response; import org.glassfish.jersey.server.mvc.Viewable; import com.authlete.common.dto.DeviceVerificationResponse; import com.authlete.common.types.User; import com.authlete.jaxrs.DeviceAuthorizationPageModel; import com.authlete.jaxrs.DeviceVerificationPageModel; import com.authlete.jaxrs.spi.DeviceVerificationRequestHandlerSpiAdapter;
{ // Urge the user to re-initiate the device flow. return badRequest("The user Code Expired. Please re-initiate the flow again."); } @Override public Response onNotExist() { // Urge the user to re-input a valid user code. // The user. User user = (User)mSession.getAttribute("user"); // The model for rendering the verification page. DeviceVerificationPageModel model = new DeviceVerificationPageModel() .setUserCode(mUserCode) .setUser(user) .setNotification("The user code does not exist."); // Return a response of "404 Not Found" having the verification page and // urge the user to re-input a valid user code. return notFound(new Viewable(VERIFICATION_PAGE_TEMPLATE, model)); } @Override public Response onServerError() { // Urge the user to re-initiate device flow.
// Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response badRequest(String entity) // { // return builderForTextPlain(Status.BAD_REQUEST, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response internalServerError(String entity) // { // return builderForTextPlain(Status.INTERNAL_SERVER_ERROR, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response notFound(String entity) // { // return builderForTextPlain(Status.NOT_FOUND, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response ok(String entity) // { // return builderForTextPlain(Status.OK, entity).build(); // } // Path: src/main/java/com/authlete/jaxrs/server/api/device/DeviceVerificationRequestHandlerSpiImpl.java import static com.authlete.jaxrs.server.util.ResponseUtil.badRequest; import static com.authlete.jaxrs.server.util.ResponseUtil.internalServerError; import static com.authlete.jaxrs.server.util.ResponseUtil.notFound; import static com.authlete.jaxrs.server.util.ResponseUtil.ok; import javax.servlet.http.HttpSession; import javax.ws.rs.core.Response; import org.glassfish.jersey.server.mvc.Viewable; import com.authlete.common.dto.DeviceVerificationResponse; import com.authlete.common.types.User; import com.authlete.jaxrs.DeviceAuthorizationPageModel; import com.authlete.jaxrs.DeviceVerificationPageModel; import com.authlete.jaxrs.spi.DeviceVerificationRequestHandlerSpiAdapter; { // Urge the user to re-initiate the device flow. return badRequest("The user Code Expired. Please re-initiate the flow again."); } @Override public Response onNotExist() { // Urge the user to re-input a valid user code. // The user. User user = (User)mSession.getAttribute("user"); // The model for rendering the verification page. DeviceVerificationPageModel model = new DeviceVerificationPageModel() .setUserCode(mUserCode) .setUser(user) .setNotification("The user code does not exist."); // Return a response of "404 Not Found" having the verification page and // urge the user to re-input a valid user code. return notFound(new Viewable(VERIFICATION_PAGE_TEMPLATE, model)); } @Override public Response onServerError() { // Urge the user to re-initiate device flow.
return internalServerError("Server Error. Please re-initiate the flow again.");
authlete/java-oauth-server
src/main/java/com/authlete/jaxrs/server/api/backchannel/BackchannelAuthenticationCompleteHandlerSpiImpl.java
// Path: src/main/java/com/authlete/jaxrs/server/util/ExceptionUtil.java // public static WebApplicationException internalServerErrorException(String entity) // { // return new WebApplicationException(entity, internalServerError(entity)); // }
import com.authlete.common.types.User; import com.authlete.jaxrs.spi.BackchannelAuthenticationCompleteRequestHandlerSpiAdapter; import static com.authlete.jaxrs.server.util.ExceptionUtil.internalServerErrorException; import java.net.URI; import java.util.Date; import javax.net.ssl.SSLContext; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.glassfish.jersey.client.ClientProperties; import com.authlete.common.dto.BackchannelAuthenticationCompleteRequest.Result; import com.authlete.common.dto.BackchannelAuthenticationCompleteResponse;
// says as follows. // // CIBA Core spec, 10.2. Ping Callback, 10.3. Push Callback // The Client MUST NOT return an HTTP 3xx code. The OP MUST // NOT follow redirects. // return; } } private Response doSendNotification(URI clientNotificationEndpointUri, String notificationToken, String notificationContent) { // A web client to send a notification to the consumption device's notification // endpoint. Client webClient = createClient(); try { // Send the notification to the consumption device.. return webClient.target(clientNotificationEndpointUri).request() // CIBA Core says "The OP MUST NOT follow redirects." .property(ClientProperties.FOLLOW_REDIRECTS, Boolean.FALSE) .header(HttpHeaders.AUTHORIZATION, "Bearer " + notificationToken) .post(Entity.json(notificationContent)); } catch (Throwable t) { // Failed to send the notification to the consumption device.
// Path: src/main/java/com/authlete/jaxrs/server/util/ExceptionUtil.java // public static WebApplicationException internalServerErrorException(String entity) // { // return new WebApplicationException(entity, internalServerError(entity)); // } // Path: src/main/java/com/authlete/jaxrs/server/api/backchannel/BackchannelAuthenticationCompleteHandlerSpiImpl.java import com.authlete.common.types.User; import com.authlete.jaxrs.spi.BackchannelAuthenticationCompleteRequestHandlerSpiAdapter; import static com.authlete.jaxrs.server.util.ExceptionUtil.internalServerErrorException; import java.net.URI; import java.util.Date; import javax.net.ssl.SSLContext; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.glassfish.jersey.client.ClientProperties; import com.authlete.common.dto.BackchannelAuthenticationCompleteRequest.Result; import com.authlete.common.dto.BackchannelAuthenticationCompleteResponse; // says as follows. // // CIBA Core spec, 10.2. Ping Callback, 10.3. Push Callback // The Client MUST NOT return an HTTP 3xx code. The OP MUST // NOT follow redirects. // return; } } private Response doSendNotification(URI clientNotificationEndpointUri, String notificationToken, String notificationContent) { // A web client to send a notification to the consumption device's notification // endpoint. Client webClient = createClient(); try { // Send the notification to the consumption device.. return webClient.target(clientNotificationEndpointUri).request() // CIBA Core says "The OP MUST NOT follow redirects." .property(ClientProperties.FOLLOW_REDIRECTS, Boolean.FALSE) .header(HttpHeaders.AUTHORIZATION, "Bearer " + notificationToken) .post(Entity.json(notificationContent)); } catch (Throwable t) { // Failed to send the notification to the consumption device.
throw internalServerErrorException(
authlete/java-oauth-server
src/main/java/com/authlete/jaxrs/server/api/device/DeviceCompleteEndpoint.java
// Path: src/main/java/com/authlete/jaxrs/server/util/ExceptionUtil.java // public static WebApplicationException badRequestException(String entity) // { // return new WebApplicationException(entity, badRequest(entity)); // }
import com.authlete.jaxrs.BaseDeviceCompleteEndpoint; import static com.authlete.jaxrs.server.util.ExceptionUtil.badRequestException; import java.util.Date; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import com.authlete.common.api.AuthleteApiFactory; import com.authlete.common.types.User;
/* * Copyright (C) 2019 Authlete, 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.authlete.jaxrs.server.api.device; /** * The endpoint that receives a request from the form in the authorization page * in OAuth 2.0 Device Authorization Grant (Device Flow). * * @author Hideki Ikeda */ @Path("/api/device/complete") public class DeviceCompleteEndpoint extends BaseDeviceCompleteEndpoint { /** * Process a request from the form in the authorization page in OAuth 2.0 * Device Authorization Grant (Device Flow). */ @POST @Consumes(MediaType.APPLICATION_FORM_URLENCODED) public Response post( @Context HttpServletRequest request, MultivaluedMap<String, String> parameters) { // Get the existing session. HttpSession session = getSession(request); // Get the information from the session. String userCode = getUserCode(session); User user = getUser(session); Date authTime = (Date)session.getAttribute("authTime"); String[] claimNames = (String[])takeAttribute(session, "claimNames"); String[] acrs = (String[])takeAttribute(session, "acrs"); // Handle the device complete request. return handle(parameters, user, authTime, acrs, userCode, claimNames); } /** * Get the existing session. */ private HttpSession getSession(HttpServletRequest request) { // Get the existing session. HttpSession session = request.getSession(false); // If there exists a session. if (session != null) { // OK. return session; } // A session does not exist. Make a response of "400 Bad Request".
// Path: src/main/java/com/authlete/jaxrs/server/util/ExceptionUtil.java // public static WebApplicationException badRequestException(String entity) // { // return new WebApplicationException(entity, badRequest(entity)); // } // Path: src/main/java/com/authlete/jaxrs/server/api/device/DeviceCompleteEndpoint.java import com.authlete.jaxrs.BaseDeviceCompleteEndpoint; import static com.authlete.jaxrs.server.util.ExceptionUtil.badRequestException; import java.util.Date; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import com.authlete.common.api.AuthleteApiFactory; import com.authlete.common.types.User; /* * Copyright (C) 2019 Authlete, 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.authlete.jaxrs.server.api.device; /** * The endpoint that receives a request from the form in the authorization page * in OAuth 2.0 Device Authorization Grant (Device Flow). * * @author Hideki Ikeda */ @Path("/api/device/complete") public class DeviceCompleteEndpoint extends BaseDeviceCompleteEndpoint { /** * Process a request from the form in the authorization page in OAuth 2.0 * Device Authorization Grant (Device Flow). */ @POST @Consumes(MediaType.APPLICATION_FORM_URLENCODED) public Response post( @Context HttpServletRequest request, MultivaluedMap<String, String> parameters) { // Get the existing session. HttpSession session = getSession(request); // Get the information from the session. String userCode = getUserCode(session); User user = getUser(session); Date authTime = (Date)session.getAttribute("authTime"); String[] claimNames = (String[])takeAttribute(session, "claimNames"); String[] acrs = (String[])takeAttribute(session, "acrs"); // Handle the device complete request. return handle(parameters, user, authTime, acrs, userCode, claimNames); } /** * Get the existing session. */ private HttpSession getSession(HttpServletRequest request) { // Get the existing session. HttpSession session = request.getSession(false); // If there exists a session. if (session != null) { // OK. return session; } // A session does not exist. Make a response of "400 Bad Request".
throw badRequestException("A session does not exist. Re-initiate the flow again.");
authlete/java-oauth-server
src/main/java/com/authlete/jaxrs/server/api/backchannel/AuthenticationDeviceProcessorFactory.java
// Path: src/main/java/com/authlete/jaxrs/server/ad/type/Mode.java // public enum Mode // { // /** // * The synchronous mode. // */ // SYNC, // // // /** // * The asynchronous mode. // */ // ASYNC, // // // /** // * The poll mode. // */ // POLL // ; // }
import com.authlete.common.dto.Scope; import com.authlete.common.types.User; import com.authlete.jaxrs.server.ad.type.Mode;
/* * Copyright (C) 2019 Authlete, 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.authlete.jaxrs.server.api.backchannel; /** * The factory class that creates a processor that communicates with * <a href="https://cibasim.authlete.com">Authlete CIBA authentication device simulator</a> * for end-user authentication and authorization. * * @see <a href="https://cibasim.authlete.com">Authlete CIBA authentication device * simulator</a> * * @see <a href="https://app.swaggerhub.com/apis-docs/Authlete/cibasim/">Authlete * CIBA authentication device simulator API</a> * * @author Hideki Ikeda */ public class AuthenticationDeviceProcessorFactory { /** * Create a processor that communicates with the authentication device simulator * for end-user authentication and authorization. * * @param mode * The mode communication with the authentication device simulator. * * @param ticket * A ticket that was issued by Authlete's {@code /api/backchannel/authentication} * API. * * @param user * An end-user to be authenticated and asked to authorize the client * application. * * @param clientName * The name of the client application. * * @param acrs * The requested ACRs. * * @param scopes * The requested scopes. * * @param claimNames * The names of the requested claims. * * @param bindingMessage * The binding message to be shown to the end-user on the authentication * device. * * @param authReqId * The authentication request ID ({@code auth_req_id}) issued to the * client. * * @param expiresIn * The duration of the issued authentication request ID ({@code auth_req_id}) * in seconds. * * @return * A processor that communicates with the authentication device simulator * for end-user authentication and authorization. */
// Path: src/main/java/com/authlete/jaxrs/server/ad/type/Mode.java // public enum Mode // { // /** // * The synchronous mode. // */ // SYNC, // // // /** // * The asynchronous mode. // */ // ASYNC, // // // /** // * The poll mode. // */ // POLL // ; // } // Path: src/main/java/com/authlete/jaxrs/server/api/backchannel/AuthenticationDeviceProcessorFactory.java import com.authlete.common.dto.Scope; import com.authlete.common.types.User; import com.authlete.jaxrs.server.ad.type.Mode; /* * Copyright (C) 2019 Authlete, 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.authlete.jaxrs.server.api.backchannel; /** * The factory class that creates a processor that communicates with * <a href="https://cibasim.authlete.com">Authlete CIBA authentication device simulator</a> * for end-user authentication and authorization. * * @see <a href="https://cibasim.authlete.com">Authlete CIBA authentication device * simulator</a> * * @see <a href="https://app.swaggerhub.com/apis-docs/Authlete/cibasim/">Authlete * CIBA authentication device simulator API</a> * * @author Hideki Ikeda */ public class AuthenticationDeviceProcessorFactory { /** * Create a processor that communicates with the authentication device simulator * for end-user authentication and authorization. * * @param mode * The mode communication with the authentication device simulator. * * @param ticket * A ticket that was issued by Authlete's {@code /api/backchannel/authentication} * API. * * @param user * An end-user to be authenticated and asked to authorize the client * application. * * @param clientName * The name of the client application. * * @param acrs * The requested ACRs. * * @param scopes * The requested scopes. * * @param claimNames * The names of the requested claims. * * @param bindingMessage * The binding message to be shown to the end-user on the authentication * device. * * @param authReqId * The authentication request ID ({@code auth_req_id}) issued to the * client. * * @param expiresIn * The duration of the issued authentication request ID ({@code auth_req_id}) * in seconds. * * @return * A processor that communicates with the authentication device simulator * for end-user authentication and authorization. */
public static AuthenticationDeviceProcessor create(Mode mode, String ticket,
authlete/java-oauth-server
src/main/java/com/authlete/jaxrs/server/ad/dto/PollAuthenticationResultResponse.java
// Path: src/main/java/com/authlete/jaxrs/server/ad/type/Result.java // public enum Result // { // /** // * The result showing that an end-user authorized a client application's request. // */ // allow, // // // /** // * The result showing that an end-user denied a client application's request. // */ // deny, // // // /** // * The result showing that timeout occurred during end-user authentication and // * authorization process. // */ // timeout // ; // } // // Path: src/main/java/com/authlete/jaxrs/server/ad/type/Status.java // public enum Status // { // /** // * The status showing that end-user authentication and authorization is being // * processed. // */ // active, // // // /** // * The status showing that end-user authentication and authorization process // * has completed. // */ // complete, // // // /** // * The status showing that timeout occurred during end-user authentication // * and authorization process // */ // timeout // ; // }
import java.io.Serializable; import com.authlete.jaxrs.server.ad.type.Result; import com.authlete.jaxrs.server.ad.type.Status;
/* * Copyright (C) 2019 Authlete, 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.authlete.jaxrs.server.ad.dto; /** * A class representing a request from <a href="https://app.swaggerhub.com/apis-docs/Authlete/cibasim/1.0.0#/default/post_api_authenticate_result"> * /api/authenticate/result API</a> of <a href="https://cibasim.authlete.com"> * Authlete CIBA authentication device simulator</a>. * * @see <a href="https://cibasim.authlete.com">Authlete CIBA authentication * device simulator</a> * * @see <a href="https://app.swaggerhub.com/apis-docs/Authlete/cibasim/1.0.0#/default/post_api_authenticate_result"> * /api/authenticate/result API</a> * * @author Hideki Ikeda */ public class PollAuthenticationResultResponse implements Serializable { private static final long serialVersionUID = 1L;
// Path: src/main/java/com/authlete/jaxrs/server/ad/type/Result.java // public enum Result // { // /** // * The result showing that an end-user authorized a client application's request. // */ // allow, // // // /** // * The result showing that an end-user denied a client application's request. // */ // deny, // // // /** // * The result showing that timeout occurred during end-user authentication and // * authorization process. // */ // timeout // ; // } // // Path: src/main/java/com/authlete/jaxrs/server/ad/type/Status.java // public enum Status // { // /** // * The status showing that end-user authentication and authorization is being // * processed. // */ // active, // // // /** // * The status showing that end-user authentication and authorization process // * has completed. // */ // complete, // // // /** // * The status showing that timeout occurred during end-user authentication // * and authorization process // */ // timeout // ; // } // Path: src/main/java/com/authlete/jaxrs/server/ad/dto/PollAuthenticationResultResponse.java import java.io.Serializable; import com.authlete.jaxrs.server.ad.type.Result; import com.authlete.jaxrs.server.ad.type.Status; /* * Copyright (C) 2019 Authlete, 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.authlete.jaxrs.server.ad.dto; /** * A class representing a request from <a href="https://app.swaggerhub.com/apis-docs/Authlete/cibasim/1.0.0#/default/post_api_authenticate_result"> * /api/authenticate/result API</a> of <a href="https://cibasim.authlete.com"> * Authlete CIBA authentication device simulator</a>. * * @see <a href="https://cibasim.authlete.com">Authlete CIBA authentication * device simulator</a> * * @see <a href="https://app.swaggerhub.com/apis-docs/Authlete/cibasim/1.0.0#/default/post_api_authenticate_result"> * /api/authenticate/result API</a> * * @author Hideki Ikeda */ public class PollAuthenticationResultResponse implements Serializable { private static final long serialVersionUID = 1L;
Status status;
authlete/java-oauth-server
src/main/java/com/authlete/jaxrs/server/ad/dto/PollAuthenticationResultResponse.java
// Path: src/main/java/com/authlete/jaxrs/server/ad/type/Result.java // public enum Result // { // /** // * The result showing that an end-user authorized a client application's request. // */ // allow, // // // /** // * The result showing that an end-user denied a client application's request. // */ // deny, // // // /** // * The result showing that timeout occurred during end-user authentication and // * authorization process. // */ // timeout // ; // } // // Path: src/main/java/com/authlete/jaxrs/server/ad/type/Status.java // public enum Status // { // /** // * The status showing that end-user authentication and authorization is being // * processed. // */ // active, // // // /** // * The status showing that end-user authentication and authorization process // * has completed. // */ // complete, // // // /** // * The status showing that timeout occurred during end-user authentication // * and authorization process // */ // timeout // ; // }
import java.io.Serializable; import com.authlete.jaxrs.server.ad.type.Result; import com.authlete.jaxrs.server.ad.type.Status;
/* * Copyright (C) 2019 Authlete, 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.authlete.jaxrs.server.ad.dto; /** * A class representing a request from <a href="https://app.swaggerhub.com/apis-docs/Authlete/cibasim/1.0.0#/default/post_api_authenticate_result"> * /api/authenticate/result API</a> of <a href="https://cibasim.authlete.com"> * Authlete CIBA authentication device simulator</a>. * * @see <a href="https://cibasim.authlete.com">Authlete CIBA authentication * device simulator</a> * * @see <a href="https://app.swaggerhub.com/apis-docs/Authlete/cibasim/1.0.0#/default/post_api_authenticate_result"> * /api/authenticate/result API</a> * * @author Hideki Ikeda */ public class PollAuthenticationResultResponse implements Serializable { private static final long serialVersionUID = 1L; Status status;
// Path: src/main/java/com/authlete/jaxrs/server/ad/type/Result.java // public enum Result // { // /** // * The result showing that an end-user authorized a client application's request. // */ // allow, // // // /** // * The result showing that an end-user denied a client application's request. // */ // deny, // // // /** // * The result showing that timeout occurred during end-user authentication and // * authorization process. // */ // timeout // ; // } // // Path: src/main/java/com/authlete/jaxrs/server/ad/type/Status.java // public enum Status // { // /** // * The status showing that end-user authentication and authorization is being // * processed. // */ // active, // // // /** // * The status showing that end-user authentication and authorization process // * has completed. // */ // complete, // // // /** // * The status showing that timeout occurred during end-user authentication // * and authorization process // */ // timeout // ; // } // Path: src/main/java/com/authlete/jaxrs/server/ad/dto/PollAuthenticationResultResponse.java import java.io.Serializable; import com.authlete.jaxrs.server.ad.type.Result; import com.authlete.jaxrs.server.ad.type.Status; /* * Copyright (C) 2019 Authlete, 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.authlete.jaxrs.server.ad.dto; /** * A class representing a request from <a href="https://app.swaggerhub.com/apis-docs/Authlete/cibasim/1.0.0#/default/post_api_authenticate_result"> * /api/authenticate/result API</a> of <a href="https://cibasim.authlete.com"> * Authlete CIBA authentication device simulator</a>. * * @see <a href="https://cibasim.authlete.com">Authlete CIBA authentication * device simulator</a> * * @see <a href="https://app.swaggerhub.com/apis-docs/Authlete/cibasim/1.0.0#/default/post_api_authenticate_result"> * /api/authenticate/result API</a> * * @author Hideki Ikeda */ public class PollAuthenticationResultResponse implements Serializable { private static final long serialVersionUID = 1L; Status status;
Result result;
authlete/java-oauth-server
src/main/java/com/authlete/jaxrs/server/api/device/DeviceCompleteRequestHandlerSpiImpl.java
// Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response badRequest(String entity) // { // return builderForTextPlain(Status.BAD_REQUEST, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response internalServerError(String entity) // { // return builderForTextPlain(Status.INTERNAL_SERVER_ERROR, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response ok(String entity) // { // return builderForTextPlain(Status.OK, entity).build(); // }
import static com.authlete.jaxrs.server.util.ResponseUtil.badRequest; import static com.authlete.jaxrs.server.util.ResponseUtil.internalServerError; import static com.authlete.jaxrs.server.util.ResponseUtil.ok; import java.util.Date; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import com.authlete.common.dto.DeviceCompleteRequest.Result; import com.authlete.common.types.User; import com.authlete.jaxrs.spi.DeviceCompleteRequestHandlerSpiAdapter;
{ return null; } // The first element of the requested ACRs. String acr = mAcrs[0]; if (acr == null || acr.length() == 0) { return null; } // Return the first element of the requested ACRs. Again, // this implementation is not suitable for commercial use. return acr; } @Override public Object getUserClaim(String claimName) { return mUser.getClaim(claimName, null); } @Override public Response onSuccess() { // The user has authorized or denied the client. // Return a response of "200 OK".
// Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response badRequest(String entity) // { // return builderForTextPlain(Status.BAD_REQUEST, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response internalServerError(String entity) // { // return builderForTextPlain(Status.INTERNAL_SERVER_ERROR, entity).build(); // } // // Path: src/main/java/com/authlete/jaxrs/server/util/ResponseUtil.java // public static Response ok(String entity) // { // return builderForTextPlain(Status.OK, entity).build(); // } // Path: src/main/java/com/authlete/jaxrs/server/api/device/DeviceCompleteRequestHandlerSpiImpl.java import static com.authlete.jaxrs.server.util.ResponseUtil.badRequest; import static com.authlete.jaxrs.server.util.ResponseUtil.internalServerError; import static com.authlete.jaxrs.server.util.ResponseUtil.ok; import java.util.Date; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.Response; import com.authlete.common.dto.DeviceCompleteRequest.Result; import com.authlete.common.types.User; import com.authlete.jaxrs.spi.DeviceCompleteRequestHandlerSpiAdapter; { return null; } // The first element of the requested ACRs. String acr = mAcrs[0]; if (acr == null || acr.length() == 0) { return null; } // Return the first element of the requested ACRs. Again, // this implementation is not suitable for commercial use. return acr; } @Override public Object getUserClaim(String claimName) { return mUser.getClaim(claimName, null); } @Override public Response onSuccess() { // The user has authorized or denied the client. // Return a response of "200 OK".
return ok("OK. The user authorization process has been done.");