code stringlengths 3 1.18M | language stringclasses 1
value |
|---|---|
package com.trilead.ssh2.crypto.digest;
/**
* SHA-1 implementation based on FIPS PUB 180-1. Highly optimized.
* <p>
* (http://www.itl.nist.gov/fipspubs/fip180-1.htm)
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: SHA1.java,v 1.1 2007/10/15 12:49:57 cplattne Exp $
*/
public final class SHA1 implements Digest {
public static void main(String[] args) {
SHA1 sha = new SHA1();
byte[] dig1 = new byte[20];
byte[] dig2 = new byte[20];
byte[] dig3 = new byte[20];
/*
* We do not specify a charset name for getBytes(), since we assume that
* the JVM's default encoder maps the _used_ ASCII characters exactly as
* getBytes("US-ASCII") would do. (Ah, yes, too lazy to catch the
* exception that can be thrown by getBytes("US-ASCII")). Note: This has
* no effect on the SHA-1 implementation, this is just for the following
* test code.
*/
sha.update("abc".getBytes());
sha.digest(dig1);
sha.update("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"
.getBytes());
sha.digest(dig2);
for (int i = 0; i < 1000000; i++)
sha.update((byte) 'a');
sha.digest(dig3);
String dig1_res = toHexString(dig1);
String dig2_res = toHexString(dig2);
String dig3_res = toHexString(dig3);
String dig1_ref = "A9993E364706816ABA3E25717850C26C9CD0D89D";
String dig2_ref = "84983E441C3BD26EBAAE4AA1F95129E5E54670F1";
String dig3_ref = "34AA973CD4C4DAA4F61EEB2BDBAD27316534016F";
if (dig1_res.equals(dig1_ref))
System.out.println("SHA-1 Test 1 OK.");
else
System.out.println("SHA-1 Test 1 FAILED.");
if (dig2_res.equals(dig2_ref))
System.out.println("SHA-1 Test 2 OK.");
else
System.out.println("SHA-1 Test 2 FAILED.");
if (dig3_res.equals(dig3_ref))
System.out.println("SHA-1 Test 3 OK.");
else
System.out.println("SHA-1 Test 3 FAILED.");
if (dig3_res.equals(dig3_ref))
System.out.println("SHA-1 Test 3 OK.");
else
System.out.println("SHA-1 Test 3 FAILED.");
}
private static final String toHexString(byte[] b) {
final String hexChar = "0123456789ABCDEF";
StringBuffer sb = new StringBuffer();
for (int i = 0; i < b.length; i++) {
sb.append(hexChar.charAt((b[i] >> 4) & 0x0f));
sb.append(hexChar.charAt(b[i] & 0x0f));
}
return sb.toString();
}
private int H0, H1, H2, H3, H4;
private final int[] w = new int[80];
private int currentPos;
private long currentLen;
public SHA1() {
reset();
}
@Override
public final void digest(byte[] out) {
digest(out, 0);
}
@Override
public final void digest(byte[] out, int off) {
/* Pad with a '1' and 7-31 zero bits... */
int idx = currentPos >> 2;
w[idx] = ((w[idx] << 8) | (0x80)) << ((3 - (currentPos & 3)) << 3);
currentPos = (currentPos & ~3) + 4;
if (currentPos == 64) {
currentPos = 0;
perform();
} else if (currentPos == 60) {
currentPos = 0;
w[15] = 0;
perform();
}
/*
* Now currentPos is a multiple of 4 and we can do the remaining padding
* much more efficiently, furthermore we are sure that currentPos <= 56.
*/
for (int i = currentPos >> 2; i < 14; i++)
w[i] = 0;
w[14] = (int) (currentLen >> 32);
w[15] = (int) currentLen;
perform();
putInt(out, off, H0);
putInt(out, off + 4, H1);
putInt(out, off + 8, H2);
putInt(out, off + 12, H3);
putInt(out, off + 16, H4);
reset();
}
@Override
public final int getDigestLength() {
return 20;
}
private final void perform() {
for (int t = 16; t < 80; t++) {
int x = w[t - 3] ^ w[t - 8] ^ w[t - 14] ^ w[t - 16];
w[t] = ((x << 1) | (x >>> 31));
}
int A = H0;
int B = H1;
int C = H2;
int D = H3;
int E = H4;
/*
* Here we use variable substitution and loop unrolling
*
* === Original step:
*
* T = s5(A) + f(B,C,D) + E + w[0] + K; E = D; D = C; C = s30(B); B = A;
* A = T;
*
* === Rewritten step:
*
* T = s5(A + f(B,C,D) + E + w[0] + K; B = s30(B); E = D; D = C; C = B;
* B = A; A = T;
*
* === Let's rewrite things, introducing new variables:
*
* E0 = E; D0 = D; C0 = C; B0 = B; A0 = A;
*
* T = s5(A0) + f(B0,C0,D0) + E0 + w[0] + K; B0 = s30(B0); E1 = D0; D1 =
* C0; C1 = B0; B1 = A0; A1 = T;
*
* T = s5(A1) + f(B1,C1,D1) + E1 + w[1] + K; B1 = s30(B1); E2 = D1; D2 =
* C1; C2 = B1; B2 = A1; A2 = T;
*
* E = E2; D = E2; C = C2; B = B2; A = A2;
*
* === No need for 'T', we can write into 'Ex' instead since after the
* calculation of 'T' nobody is interested in 'Ex' anymore.
*
* E0 = E; D0 = D; C0 = C; B0 = B; A0 = A;
*
* E0 = E0 + s5(A0) + f(B0,C0,D0) + w[0] + K; B0 = s30(B0); E1 = D0; D1
* = C0; C1 = B0; B1 = A0; A1 = E0;
*
* E1 = E1 + s5(A1) + f(B1,C1,D1) + w[1] + K; B1 = s30(B1); E2 = D1; D2
* = C1; C2 = B1; B2 = A1; A2 = E1;
*
* E = Ex; D = Ex; C = Cx; B = Bx; A = Ax;
*
* === Further optimization: get rid of the swap operations Idea:
* instead of swapping the variables, swap the names of the used
* variables in the next step:
*
* E0 = E; D0 = d; C0 = C; B0 = B; A0 = A;
*
* E0 = E0 + s5(A0) + f(B0,C0,D0) + w[0] + K; B0 = s30(B0); // E1 = D0;
* D1 = C0; C1 = B0; B1 = A0; A1 = E0;
*
* D0 = D0 + s5(E0) + f(A0,B0,C0) + w[1] + K; A0 = s30(A0); E2 = C0; D2
* = B0; C2 = A0; B2 = E0; A2 = D0;
*
* E = E2; D = D2; C = C2; B = B2; A = A2;
*
* === OK, let's do this several times, also, directly use A (instead of
* A0) and B,C,D,E.
*
* E = E + s5(A) + f(B,C,D) + w[0] + K; B = s30(B); // E1 = D; D1 = C;
* C1 = B; B1 = A; A1 = E;
*
* D = D + s5(E) + f(A,B,C) + w[1] + K; A = s30(A); // E2 = C; D2 = B;
* C2 = A; B2 = E; A2 = D;
*
* C = C + s5(D) + f(E,A,B) + w[2] + K; E = s30(E); // E3 = B; D3 = A;
* C3 = E; B3 = D; A3 = C;
*
* B = B + s5(C) + f(D,E,A) + w[3] + K; D = s30(D); // E4 = A; D4 = E;
* C4 = D; B4 = C; A4 = B;
*
* A = A + s5(B) + f(C,D,E) + w[4] + K; C = s30(C); // E5 = E; D5 = D;
* C5 = C; B5 = B; A5 = A;
*
* //E = E5; D = D5; C = C5; B = B5; A = A5;
*
* === Very nice, after 5 steps each variable has the same contents as
* after 5 steps with the original algorithm!
*
* We therefore can easily unroll each interval, as the number of steps
* in each interval is a multiple of 5 (20 steps per interval).
*/
E += ((A << 5) | (A >>> 27)) + ((B & C) | ((~B) & D)) + w[0]
+ 0x5A827999;
B = ((B << 30) | (B >>> 2));
D += ((E << 5) | (E >>> 27)) + ((A & B) | ((~A) & C)) + w[1]
+ 0x5A827999;
A = ((A << 30) | (A >>> 2));
C += ((D << 5) | (D >>> 27)) + ((E & A) | ((~E) & B)) + w[2]
+ 0x5A827999;
E = ((E << 30) | (E >>> 2));
B += ((C << 5) | (C >>> 27)) + ((D & E) | ((~D) & A)) + w[3]
+ 0x5A827999;
D = ((D << 30) | (D >>> 2));
A += ((B << 5) | (B >>> 27)) + ((C & D) | ((~C) & E)) + w[4]
+ 0x5A827999;
C = ((C << 30) | (C >>> 2));
E += ((A << 5) | (A >>> 27)) + ((B & C) | ((~B) & D)) + w[5]
+ 0x5A827999;
B = ((B << 30) | (B >>> 2));
D += ((E << 5) | (E >>> 27)) + ((A & B) | ((~A) & C)) + w[6]
+ 0x5A827999;
A = ((A << 30) | (A >>> 2));
C += ((D << 5) | (D >>> 27)) + ((E & A) | ((~E) & B)) + w[7]
+ 0x5A827999;
E = ((E << 30) | (E >>> 2));
B += ((C << 5) | (C >>> 27)) + ((D & E) | ((~D) & A)) + w[8]
+ 0x5A827999;
D = ((D << 30) | (D >>> 2));
A += ((B << 5) | (B >>> 27)) + ((C & D) | ((~C) & E)) + w[9]
+ 0x5A827999;
C = ((C << 30) | (C >>> 2));
E += ((A << 5) | (A >>> 27)) + ((B & C) | ((~B) & D)) + w[10]
+ 0x5A827999;
B = ((B << 30) | (B >>> 2));
D += ((E << 5) | (E >>> 27)) + ((A & B) | ((~A) & C)) + w[11]
+ 0x5A827999;
A = ((A << 30) | (A >>> 2));
C += ((D << 5) | (D >>> 27)) + ((E & A) | ((~E) & B)) + w[12]
+ 0x5A827999;
E = ((E << 30) | (E >>> 2));
B += ((C << 5) | (C >>> 27)) + ((D & E) | ((~D) & A)) + w[13]
+ 0x5A827999;
D = ((D << 30) | (D >>> 2));
A += ((B << 5) | (B >>> 27)) + ((C & D) | ((~C) & E)) + w[14]
+ 0x5A827999;
C = ((C << 30) | (C >>> 2));
E += ((A << 5) | (A >>> 27)) + ((B & C) | ((~B) & D)) + w[15]
+ 0x5A827999;
B = ((B << 30) | (B >>> 2));
D += ((E << 5) | (E >>> 27)) + ((A & B) | ((~A) & C)) + w[16]
+ 0x5A827999;
A = ((A << 30) | (A >>> 2));
C += ((D << 5) | (D >>> 27)) + ((E & A) | ((~E) & B)) + w[17]
+ 0x5A827999;
E = ((E << 30) | (E >>> 2));
B += ((C << 5) | (C >>> 27)) + ((D & E) | ((~D) & A)) + w[18]
+ 0x5A827999;
D = ((D << 30) | (D >>> 2));
A += ((B << 5) | (B >>> 27)) + ((C & D) | ((~C) & E)) + w[19]
+ 0x5A827999;
C = ((C << 30) | (C >>> 2));
E += ((A << 5) | (A >>> 27)) + (B ^ C ^ D) + w[20] + 0x6ED9EBA1;
B = ((B << 30) | (B >>> 2));
D += ((E << 5) | (E >>> 27)) + (A ^ B ^ C) + w[21] + 0x6ED9EBA1;
A = ((A << 30) | (A >>> 2));
C += ((D << 5) | (D >>> 27)) + (E ^ A ^ B) + w[22] + 0x6ED9EBA1;
E = ((E << 30) | (E >>> 2));
B += ((C << 5) | (C >>> 27)) + (D ^ E ^ A) + w[23] + 0x6ED9EBA1;
D = ((D << 30) | (D >>> 2));
A += ((B << 5) | (B >>> 27)) + (C ^ D ^ E) + w[24] + 0x6ED9EBA1;
C = ((C << 30) | (C >>> 2));
E += ((A << 5) | (A >>> 27)) + (B ^ C ^ D) + w[25] + 0x6ED9EBA1;
B = ((B << 30) | (B >>> 2));
D += ((E << 5) | (E >>> 27)) + (A ^ B ^ C) + w[26] + 0x6ED9EBA1;
A = ((A << 30) | (A >>> 2));
C += ((D << 5) | (D >>> 27)) + (E ^ A ^ B) + w[27] + 0x6ED9EBA1;
E = ((E << 30) | (E >>> 2));
B += ((C << 5) | (C >>> 27)) + (D ^ E ^ A) + w[28] + 0x6ED9EBA1;
D = ((D << 30) | (D >>> 2));
A += ((B << 5) | (B >>> 27)) + (C ^ D ^ E) + w[29] + 0x6ED9EBA1;
C = ((C << 30) | (C >>> 2));
E += ((A << 5) | (A >>> 27)) + (B ^ C ^ D) + w[30] + 0x6ED9EBA1;
B = ((B << 30) | (B >>> 2));
D += ((E << 5) | (E >>> 27)) + (A ^ B ^ C) + w[31] + 0x6ED9EBA1;
A = ((A << 30) | (A >>> 2));
C += ((D << 5) | (D >>> 27)) + (E ^ A ^ B) + w[32] + 0x6ED9EBA1;
E = ((E << 30) | (E >>> 2));
B += ((C << 5) | (C >>> 27)) + (D ^ E ^ A) + w[33] + 0x6ED9EBA1;
D = ((D << 30) | (D >>> 2));
A += ((B << 5) | (B >>> 27)) + (C ^ D ^ E) + w[34] + 0x6ED9EBA1;
C = ((C << 30) | (C >>> 2));
E += ((A << 5) | (A >>> 27)) + (B ^ C ^ D) + w[35] + 0x6ED9EBA1;
B = ((B << 30) | (B >>> 2));
D += ((E << 5) | (E >>> 27)) + (A ^ B ^ C) + w[36] + 0x6ED9EBA1;
A = ((A << 30) | (A >>> 2));
C += ((D << 5) | (D >>> 27)) + (E ^ A ^ B) + w[37] + 0x6ED9EBA1;
E = ((E << 30) | (E >>> 2));
B += ((C << 5) | (C >>> 27)) + (D ^ E ^ A) + w[38] + 0x6ED9EBA1;
D = ((D << 30) | (D >>> 2));
A += ((B << 5) | (B >>> 27)) + (C ^ D ^ E) + w[39] + 0x6ED9EBA1;
C = ((C << 30) | (C >>> 2));
E += ((A << 5) | (A >>> 27)) + ((B & C) | (B & D) | (C & D)) + w[40]
+ 0x8F1BBCDC;
B = ((B << 30) | (B >>> 2));
D += ((E << 5) | (E >>> 27)) + ((A & B) | (A & C) | (B & C)) + w[41]
+ 0x8F1BBCDC;
A = ((A << 30) | (A >>> 2));
C += ((D << 5) | (D >>> 27)) + ((E & A) | (E & B) | (A & B)) + w[42]
+ 0x8F1BBCDC;
E = ((E << 30) | (E >>> 2));
B += ((C << 5) | (C >>> 27)) + ((D & E) | (D & A) | (E & A)) + w[43]
+ 0x8F1BBCDC;
D = ((D << 30) | (D >>> 2));
A += ((B << 5) | (B >>> 27)) + ((C & D) | (C & E) | (D & E)) + w[44]
+ 0x8F1BBCDC;
C = ((C << 30) | (C >>> 2));
E += ((A << 5) | (A >>> 27)) + ((B & C) | (B & D) | (C & D)) + w[45]
+ 0x8F1BBCDC;
B = ((B << 30) | (B >>> 2));
D += ((E << 5) | (E >>> 27)) + ((A & B) | (A & C) | (B & C)) + w[46]
+ 0x8F1BBCDC;
A = ((A << 30) | (A >>> 2));
C += ((D << 5) | (D >>> 27)) + ((E & A) | (E & B) | (A & B)) + w[47]
+ 0x8F1BBCDC;
E = ((E << 30) | (E >>> 2));
B += ((C << 5) | (C >>> 27)) + ((D & E) | (D & A) | (E & A)) + w[48]
+ 0x8F1BBCDC;
D = ((D << 30) | (D >>> 2));
A += ((B << 5) | (B >>> 27)) + ((C & D) | (C & E) | (D & E)) + w[49]
+ 0x8F1BBCDC;
C = ((C << 30) | (C >>> 2));
E += ((A << 5) | (A >>> 27)) + ((B & C) | (B & D) | (C & D)) + w[50]
+ 0x8F1BBCDC;
B = ((B << 30) | (B >>> 2));
D += ((E << 5) | (E >>> 27)) + ((A & B) | (A & C) | (B & C)) + w[51]
+ 0x8F1BBCDC;
A = ((A << 30) | (A >>> 2));
C += ((D << 5) | (D >>> 27)) + ((E & A) | (E & B) | (A & B)) + w[52]
+ 0x8F1BBCDC;
E = ((E << 30) | (E >>> 2));
B += ((C << 5) | (C >>> 27)) + ((D & E) | (D & A) | (E & A)) + w[53]
+ 0x8F1BBCDC;
D = ((D << 30) | (D >>> 2));
A += ((B << 5) | (B >>> 27)) + ((C & D) | (C & E) | (D & E)) + w[54]
+ 0x8F1BBCDC;
C = ((C << 30) | (C >>> 2));
E = E + ((A << 5) | (A >>> 27)) + ((B & C) | (B & D) | (C & D)) + w[55]
+ 0x8F1BBCDC;
B = ((B << 30) | (B >>> 2));
D += ((E << 5) | (E >>> 27)) + ((A & B) | (A & C) | (B & C)) + w[56]
+ 0x8F1BBCDC;
A = ((A << 30) | (A >>> 2));
C += ((D << 5) | (D >>> 27)) + ((E & A) | (E & B) | (A & B)) + w[57]
+ 0x8F1BBCDC;
E = ((E << 30) | (E >>> 2));
B += ((C << 5) | (C >>> 27)) + ((D & E) | (D & A) | (E & A)) + w[58]
+ 0x8F1BBCDC;
D = ((D << 30) | (D >>> 2));
A += ((B << 5) | (B >>> 27)) + ((C & D) | (C & E) | (D & E)) + w[59]
+ 0x8F1BBCDC;
C = ((C << 30) | (C >>> 2));
E += ((A << 5) | (A >>> 27)) + (B ^ C ^ D) + w[60] + 0xCA62C1D6;
B = ((B << 30) | (B >>> 2));
D += ((E << 5) | (E >>> 27)) + (A ^ B ^ C) + w[61] + 0xCA62C1D6;
A = ((A << 30) | (A >>> 2));
C += ((D << 5) | (D >>> 27)) + (E ^ A ^ B) + w[62] + 0xCA62C1D6;
E = ((E << 30) | (E >>> 2));
B += ((C << 5) | (C >>> 27)) + (D ^ E ^ A) + w[63] + 0xCA62C1D6;
D = ((D << 30) | (D >>> 2));
A += ((B << 5) | (B >>> 27)) + (C ^ D ^ E) + w[64] + 0xCA62C1D6;
C = ((C << 30) | (C >>> 2));
E += ((A << 5) | (A >>> 27)) + (B ^ C ^ D) + w[65] + 0xCA62C1D6;
B = ((B << 30) | (B >>> 2));
D += ((E << 5) | (E >>> 27)) + (A ^ B ^ C) + w[66] + 0xCA62C1D6;
A = ((A << 30) | (A >>> 2));
C += ((D << 5) | (D >>> 27)) + (E ^ A ^ B) + w[67] + 0xCA62C1D6;
E = ((E << 30) | (E >>> 2));
B += ((C << 5) | (C >>> 27)) + (D ^ E ^ A) + w[68] + 0xCA62C1D6;
D = ((D << 30) | (D >>> 2));
A += ((B << 5) | (B >>> 27)) + (C ^ D ^ E) + w[69] + 0xCA62C1D6;
C = ((C << 30) | (C >>> 2));
E += ((A << 5) | (A >>> 27)) + (B ^ C ^ D) + w[70] + 0xCA62C1D6;
B = ((B << 30) | (B >>> 2));
D += ((E << 5) | (E >>> 27)) + (A ^ B ^ C) + w[71] + 0xCA62C1D6;
A = ((A << 30) | (A >>> 2));
C += ((D << 5) | (D >>> 27)) + (E ^ A ^ B) + w[72] + 0xCA62C1D6;
E = ((E << 30) | (E >>> 2));
B += ((C << 5) | (C >>> 27)) + (D ^ E ^ A) + w[73] + 0xCA62C1D6;
D = ((D << 30) | (D >>> 2));
A += ((B << 5) | (B >>> 27)) + (C ^ D ^ E) + w[74] + 0xCA62C1D6;
C = ((C << 30) | (C >>> 2));
E += ((A << 5) | (A >>> 27)) + (B ^ C ^ D) + w[75] + 0xCA62C1D6;
B = ((B << 30) | (B >>> 2));
D += ((E << 5) | (E >>> 27)) + (A ^ B ^ C) + w[76] + 0xCA62C1D6;
A = ((A << 30) | (A >>> 2));
C += ((D << 5) | (D >>> 27)) + (E ^ A ^ B) + w[77] + 0xCA62C1D6;
E = ((E << 30) | (E >>> 2));
B += ((C << 5) | (C >>> 27)) + (D ^ E ^ A) + w[78] + 0xCA62C1D6;
D = ((D << 30) | (D >>> 2));
A += ((B << 5) | (B >>> 27)) + (C ^ D ^ E) + w[79] + 0xCA62C1D6;
C = ((C << 30) | (C >>> 2));
H0 += A;
H1 += B;
H2 += C;
H3 += D;
H4 += E;
// debug(80, H0, H1, H2, H3, H4);
}
private final void putInt(byte[] b, int pos, int val) {
b[pos] = (byte) (val >> 24);
b[pos + 1] = (byte) (val >> 16);
b[pos + 2] = (byte) (val >> 8);
b[pos + 3] = (byte) val;
}
@Override
public final void reset() {
H0 = 0x67452301;
H1 = 0xEFCDAB89;
H2 = 0x98BADCFE;
H3 = 0x10325476;
H4 = 0xC3D2E1F0;
currentPos = 0;
currentLen = 0;
/*
* In case of complete paranoia, we should also wipe out the information
* contained in the w[] array
*/
}
@Override
public final void update(byte b[]) {
update(b, 0, b.length);
}
@Override
public final void update(byte b) {
int idx = currentPos >> 2;
w[idx] = (w[idx] << 8) | (b & 0xff);
currentLen += 8;
currentPos++;
if (currentPos == 64) {
perform();
currentPos = 0;
}
}
@Override
public final void update(byte b[], int off, int len) {
if (len >= 4) {
int idx = currentPos >> 2;
switch (currentPos & 3) {
case 0:
w[idx] = (((b[off++] & 0xff) << 24) | ((b[off++] & 0xff) << 16)
| ((b[off++] & 0xff) << 8) | (b[off++] & 0xff));
len -= 4;
currentPos += 4;
currentLen += 32;
if (currentPos == 64) {
perform();
currentPos = 0;
}
break;
case 1:
w[idx] = (w[idx] << 24)
| (((b[off++] & 0xff) << 16) | ((b[off++] & 0xff) << 8) | (b[off++] & 0xff));
len -= 3;
currentPos += 3;
currentLen += 24;
if (currentPos == 64) {
perform();
currentPos = 0;
}
break;
case 2:
w[idx] = (w[idx] << 16)
| (((b[off++] & 0xff) << 8) | (b[off++] & 0xff));
len -= 2;
currentPos += 2;
currentLen += 16;
if (currentPos == 64) {
perform();
currentPos = 0;
}
break;
case 3:
w[idx] = (w[idx] << 8) | (b[off++] & 0xff);
len--;
currentPos++;
currentLen += 8;
if (currentPos == 64) {
perform();
currentPos = 0;
}
break;
}
/* Now currentPos is a multiple of 4 - this is the place to be... */
while (len >= 8) {
w[currentPos >> 2] = ((b[off++] & 0xff) << 24)
| ((b[off++] & 0xff) << 16) | ((b[off++] & 0xff) << 8)
| (b[off++] & 0xff);
currentPos += 4;
if (currentPos == 64) {
perform();
currentPos = 0;
}
w[currentPos >> 2] = ((b[off++] & 0xff) << 24)
| ((b[off++] & 0xff) << 16) | ((b[off++] & 0xff) << 8)
| (b[off++] & 0xff);
currentPos += 4;
if (currentPos == 64) {
perform();
currentPos = 0;
}
currentLen += 64;
len -= 8;
}
while (len < 0) // (len >= 4)
{
w[currentPos >> 2] = ((b[off++] & 0xff) << 24)
| ((b[off++] & 0xff) << 16) | ((b[off++] & 0xff) << 8)
| (b[off++] & 0xff);
len -= 4;
currentPos += 4;
currentLen += 32;
if (currentPos == 64) {
perform();
currentPos = 0;
}
}
}
/* Remaining bytes (1-3) */
while (len > 0) {
/* Here is room for further improvements */
int idx = currentPos >> 2;
w[idx] = (w[idx] << 8) | (b[off++] & 0xff);
currentLen += 8;
currentPos++;
if (currentPos == 64) {
perform();
currentPos = 0;
}
len--;
}
}
}
| Java |
package com.trilead.ssh2.crypto.digest;
/**
* Digest.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: Digest.java,v 1.1 2007/10/15 12:49:57 cplattne Exp $
*/
public interface Digest {
public void digest(byte[] out);
public void digest(byte[] out, int off);
public int getDigestLength();
public void reset();
public void update(byte b);
public void update(byte b[], int off, int len);
public void update(byte[] b);
}
| Java |
package com.trilead.ssh2.crypto;
import java.io.CharArrayWriter;
import java.io.IOException;
/**
* Basic Base64 Support.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: Base64.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public class Base64 {
static final char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
.toCharArray();
public static byte[] decode(char[] message) throws IOException {
byte buff[] = new byte[4];
byte dest[] = new byte[message.length];
int bpos = 0;
int destpos = 0;
for (int i = 0; i < message.length; i++) {
int c = message[i];
if ((c == '\n') || (c == '\r') || (c == ' ') || (c == '\t'))
continue;
if ((c >= 'A') && (c <= 'Z')) {
buff[bpos++] = (byte) (c - 'A');
} else if ((c >= 'a') && (c <= 'z')) {
buff[bpos++] = (byte) ((c - 'a') + 26);
} else if ((c >= '0') && (c <= '9')) {
buff[bpos++] = (byte) ((c - '0') + 52);
} else if (c == '+') {
buff[bpos++] = 62;
} else if (c == '/') {
buff[bpos++] = 63;
} else if (c == '=') {
buff[bpos++] = 64;
} else {
throw new IOException("Illegal char in base64 code.");
}
if (bpos == 4) {
bpos = 0;
if (buff[0] == 64)
break;
if (buff[1] == 64)
throw new IOException("Unexpected '=' in base64 code.");
if (buff[2] == 64) {
int v = (((buff[0] & 0x3f) << 6) | ((buff[1] & 0x3f)));
dest[destpos++] = (byte) (v >> 4);
break;
} else if (buff[3] == 64) {
int v = (((buff[0] & 0x3f) << 12) | ((buff[1] & 0x3f) << 6) | ((buff[2] & 0x3f)));
dest[destpos++] = (byte) (v >> 10);
dest[destpos++] = (byte) (v >> 2);
break;
} else {
int v = (((buff[0] & 0x3f) << 18)
| ((buff[1] & 0x3f) << 12)
| ((buff[2] & 0x3f) << 6) | ((buff[3] & 0x3f)));
dest[destpos++] = (byte) (v >> 16);
dest[destpos++] = (byte) (v >> 8);
dest[destpos++] = (byte) (v);
}
}
}
byte[] res = new byte[destpos];
System.arraycopy(dest, 0, res, 0, destpos);
return res;
}
public static char[] encode(byte[] content) {
CharArrayWriter cw = new CharArrayWriter((4 * content.length) / 3);
int idx = 0;
int x = 0;
for (int i = 0; i < content.length; i++) {
if (idx == 0)
x = (content[i] & 0xff) << 16;
else if (idx == 1)
x = x | ((content[i] & 0xff) << 8);
else
x = x | (content[i] & 0xff);
idx++;
if (idx == 3) {
cw.write(alphabet[x >> 18]);
cw.write(alphabet[(x >> 12) & 0x3f]);
cw.write(alphabet[(x >> 6) & 0x3f]);
cw.write(alphabet[x & 0x3f]);
idx = 0;
}
}
if (idx == 1) {
cw.write(alphabet[x >> 18]);
cw.write(alphabet[(x >> 12) & 0x3f]);
cw.write('=');
cw.write('=');
}
if (idx == 2) {
cw.write(alphabet[x >> 18]);
cw.write(alphabet[(x >> 12) & 0x3f]);
cw.write(alphabet[(x >> 6) & 0x3f]);
cw.write('=');
}
return cw.toCharArray();
}
}
| Java |
package com.trilead.ssh2.crypto;
import java.io.IOException;
import java.math.BigInteger;
/**
* SimpleDERReader.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: SimpleDERReader.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public class SimpleDERReader {
byte[] buffer;
int pos;
int count;
public SimpleDERReader(byte[] b) {
resetInput(b);
}
public SimpleDERReader(byte[] b, int off, int len) {
resetInput(b, off, len);
}
public int available() {
return count;
}
public int ignoreNextObject() throws IOException {
int type = readByte() & 0xff;
int len = readLength();
if ((len < 0) || len > available())
throw new IOException("Illegal len in DER object (" + len + ")");
readBytes(len);
return type;
}
private byte readByte() throws IOException {
if (count <= 0)
throw new IOException("DER byte array: out of data");
count--;
return buffer[pos++];
}
private byte[] readBytes(int len) throws IOException {
if (len > count)
throw new IOException("DER byte array: out of data");
byte[] b = new byte[len];
System.arraycopy(buffer, pos, b, 0, len);
pos += len;
count -= len;
return b;
}
public BigInteger readInt() throws IOException {
int type = readByte() & 0xff;
if (type != 0x02)
throw new IOException("Expected DER Integer, but found type "
+ type);
int len = readLength();
if ((len < 0) || len > available())
throw new IOException("Illegal len in DER object (" + len + ")");
byte[] b = readBytes(len);
BigInteger bi = new BigInteger(b);
return bi;
}
private int readLength() throws IOException {
int len = readByte() & 0xff;
if ((len & 0x80) == 0)
return len;
int remain = len & 0x7F;
if (remain == 0)
return -1;
len = 0;
while (remain > 0) {
len = len << 8;
len = len | (readByte() & 0xff);
remain--;
}
return len;
}
public byte[] readOctetString() throws IOException {
int type = readByte() & 0xff;
if (type != 0x04)
throw new IOException("Expected DER Octetstring, but found type "
+ type);
int len = readLength();
if ((len < 0) || len > available())
throw new IOException("Illegal len in DER object (" + len + ")");
byte[] b = readBytes(len);
return b;
}
public byte[] readSequenceAsByteArray() throws IOException {
int type = readByte() & 0xff;
if (type != 0x30)
throw new IOException("Expected DER Sequence, but found type "
+ type);
int len = readLength();
if ((len < 0) || len > available())
throw new IOException("Illegal len in DER object (" + len + ")");
byte[] b = readBytes(len);
return b;
}
public void resetInput(byte[] b) {
resetInput(b, 0, b.length);
}
public void resetInput(byte[] b, int off, int len) {
buffer = b;
pos = off;
count = len;
}
}
| Java |
package com.trilead.ssh2.crypto;
import java.io.BufferedReader;
import java.io.CharArrayReader;
import java.io.IOException;
import java.math.BigInteger;
import com.trilead.ssh2.crypto.cipher.AES;
import com.trilead.ssh2.crypto.cipher.BlockCipher;
import com.trilead.ssh2.crypto.cipher.CBCMode;
import com.trilead.ssh2.crypto.cipher.DES;
import com.trilead.ssh2.crypto.cipher.DESede;
import com.trilead.ssh2.crypto.digest.MD5;
import com.trilead.ssh2.signature.DSAPrivateKey;
import com.trilead.ssh2.signature.RSAPrivateKey;
/**
* PEM Support.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PEMDecoder.java,v 1.2 2008/04/01 12:38:09 cplattne Exp $
*/
public class PEMDecoder {
public static final int PEM_RSA_PRIVATE_KEY = 1;
public static final int PEM_DSA_PRIVATE_KEY = 2;
public static Object decode(char[] pem, String password) throws IOException {
PEMStructure ps = parsePEM(pem);
if (isPEMEncrypted(ps)) {
if (password == null)
throw new IOException(
"PEM is encrypted, but no password was specified");
decryptPEM(ps, password.getBytes("ISO-8859-1"));
}
if (ps.pemType == PEM_DSA_PRIVATE_KEY) {
SimpleDERReader dr = new SimpleDERReader(ps.data);
byte[] seq = dr.readSequenceAsByteArray();
if (dr.available() != 0)
throw new IOException("Padding in DSA PRIVATE KEY DER stream.");
dr.resetInput(seq);
BigInteger version = dr.readInt();
if (version.compareTo(BigInteger.ZERO) != 0)
throw new IOException("Wrong version (" + version
+ ") in DSA PRIVATE KEY DER stream.");
BigInteger p = dr.readInt();
BigInteger q = dr.readInt();
BigInteger g = dr.readInt();
BigInteger y = dr.readInt();
BigInteger x = dr.readInt();
if (dr.available() != 0)
throw new IOException("Padding in DSA PRIVATE KEY DER stream.");
return new DSAPrivateKey(p, q, g, y, x);
}
if (ps.pemType == PEM_RSA_PRIVATE_KEY) {
SimpleDERReader dr = new SimpleDERReader(ps.data);
byte[] seq = dr.readSequenceAsByteArray();
if (dr.available() != 0)
throw new IOException("Padding in RSA PRIVATE KEY DER stream.");
dr.resetInput(seq);
BigInteger version = dr.readInt();
if ((version.compareTo(BigInteger.ZERO) != 0)
&& (version.compareTo(BigInteger.ONE) != 0))
throw new IOException("Wrong version (" + version
+ ") in RSA PRIVATE KEY DER stream.");
BigInteger n = dr.readInt();
BigInteger e = dr.readInt();
BigInteger d = dr.readInt();
return new RSAPrivateKey(d, e, n);
}
throw new IOException("PEM problem: it is of unknown type");
}
private static final void decryptPEM(PEMStructure ps, byte[] pw)
throws IOException {
if (ps.dekInfo == null)
throw new IOException(
"Broken PEM, no mode and salt given, but encryption enabled");
if (ps.dekInfo.length != 2)
throw new IOException("Broken PEM, DEK-Info is incomplete!");
String algo = ps.dekInfo[0];
byte[] salt = hexToByteArray(ps.dekInfo[1]);
BlockCipher bc = null;
if (algo.equals("DES-EDE3-CBC")) {
DESede des3 = new DESede();
des3.init(false, generateKeyFromPasswordSaltWithMD5(pw, salt, 24));
bc = new CBCMode(des3, salt, false);
} else if (algo.equals("DES-CBC")) {
DES des = new DES();
des.init(false, generateKeyFromPasswordSaltWithMD5(pw, salt, 8));
bc = new CBCMode(des, salt, false);
} else if (algo.equals("AES-128-CBC")) {
AES aes = new AES();
aes.init(false, generateKeyFromPasswordSaltWithMD5(pw, salt, 16));
bc = new CBCMode(aes, salt, false);
} else if (algo.equals("AES-192-CBC")) {
AES aes = new AES();
aes.init(false, generateKeyFromPasswordSaltWithMD5(pw, salt, 24));
bc = new CBCMode(aes, salt, false);
} else if (algo.equals("AES-256-CBC")) {
AES aes = new AES();
aes.init(false, generateKeyFromPasswordSaltWithMD5(pw, salt, 32));
bc = new CBCMode(aes, salt, false);
} else {
throw new IOException(
"Cannot decrypt PEM structure, unknown cipher " + algo);
}
if ((ps.data.length % bc.getBlockSize()) != 0)
throw new IOException(
"Invalid PEM structure, size of encrypted block is not a multiple of "
+ bc.getBlockSize());
/* Now decrypt the content */
byte[] dz = new byte[ps.data.length];
for (int i = 0; i < ps.data.length / bc.getBlockSize(); i++) {
bc.transformBlock(ps.data, i * bc.getBlockSize(), dz,
i * bc.getBlockSize());
}
/* Now check and remove RFC 1423/PKCS #7 padding */
dz = removePadding(dz, bc.getBlockSize());
ps.data = dz;
ps.dekInfo = null;
ps.procType = null;
}
private static byte[] generateKeyFromPasswordSaltWithMD5(byte[] password,
byte[] salt, int keyLen) throws IOException {
if (salt.length < 8)
throw new IllegalArgumentException(
"Salt needs to be at least 8 bytes for key generation.");
MD5 md5 = new MD5();
byte[] key = new byte[keyLen];
byte[] tmp = new byte[md5.getDigestLength()];
while (true) {
md5.update(password, 0, password.length);
md5.update(salt, 0, 8); // ARGH we only use the first 8 bytes of the
// salt in this step.
// This took me two hours until I got AES-xxx running.
int copy = (keyLen < tmp.length) ? keyLen : tmp.length;
md5.digest(tmp, 0);
System.arraycopy(tmp, 0, key, key.length - keyLen, copy);
keyLen -= copy;
if (keyLen == 0)
return key;
md5.update(tmp, 0, tmp.length);
}
}
private static byte[] hexToByteArray(String hex) {
if (hex == null)
throw new IllegalArgumentException("null argument");
if ((hex.length() % 2) != 0)
throw new IllegalArgumentException(
"Uneven string length in hex encoding.");
byte decoded[] = new byte[hex.length() / 2];
for (int i = 0; i < decoded.length; i++) {
int hi = hexToInt(hex.charAt(i * 2));
int lo = hexToInt(hex.charAt((i * 2) + 1));
decoded[i] = (byte) (hi * 16 + lo);
}
return decoded;
}
private static final int hexToInt(char c) {
if ((c >= 'a') && (c <= 'f')) {
return (c - 'a') + 10;
}
if ((c >= 'A') && (c <= 'F')) {
return (c - 'A') + 10;
}
if ((c >= '0') && (c <= '9')) {
return (c - '0');
}
throw new IllegalArgumentException("Need hex char");
}
public static final boolean isPEMEncrypted(PEMStructure ps)
throws IOException {
if (ps.procType == null)
return false;
if (ps.procType.length != 2)
throw new IOException("Unknown Proc-Type field.");
if ("4".equals(ps.procType[0]) == false)
throw new IOException("Unknown Proc-Type field (" + ps.procType[0]
+ ")");
if ("ENCRYPTED".equals(ps.procType[1]))
return true;
return false;
}
public static final PEMStructure parsePEM(char[] pem) throws IOException {
PEMStructure ps = new PEMStructure();
String line = null;
BufferedReader br = new BufferedReader(new CharArrayReader(pem));
String endLine = null;
while (true) {
line = br.readLine();
if (line == null)
throw new IOException(
"Invalid PEM structure, '-----BEGIN...' missing");
line = line.trim();
if (line.startsWith("-----BEGIN DSA PRIVATE KEY-----")) {
endLine = "-----END DSA PRIVATE KEY-----";
ps.pemType = PEM_DSA_PRIVATE_KEY;
break;
}
if (line.startsWith("-----BEGIN RSA PRIVATE KEY-----")) {
endLine = "-----END RSA PRIVATE KEY-----";
ps.pemType = PEM_RSA_PRIVATE_KEY;
break;
}
}
while (true) {
line = br.readLine();
if (line == null)
throw new IOException("Invalid PEM structure, " + endLine
+ " missing");
line = line.trim();
int sem_idx = line.indexOf(':');
if (sem_idx == -1)
break;
String name = line.substring(0, sem_idx + 1);
String value = line.substring(sem_idx + 1);
String values[] = value.split(",");
for (int i = 0; i < values.length; i++)
values[i] = values[i].trim();
// Proc-Type: 4,ENCRYPTED
// DEK-Info: DES-EDE3-CBC,579B6BE3E5C60483
if ("Proc-Type:".equals(name)) {
ps.procType = values;
continue;
}
if ("DEK-Info:".equals(name)) {
ps.dekInfo = values;
continue;
}
/* Ignore line */
}
StringBuffer keyData = new StringBuffer();
while (true) {
if (line == null)
throw new IOException("Invalid PEM structure, " + endLine
+ " missing");
line = line.trim();
if (line.startsWith(endLine))
break;
keyData.append(line);
line = br.readLine();
}
char[] pem_chars = new char[keyData.length()];
keyData.getChars(0, pem_chars.length, pem_chars, 0);
ps.data = Base64.decode(pem_chars);
if (ps.data.length == 0)
throw new IOException("Invalid PEM structure, no data available");
return ps;
}
private static byte[] removePadding(byte[] buff, int blockSize)
throws IOException {
/* Removes RFC 1423/PKCS #7 padding */
int rfc_1423_padding = buff[buff.length - 1] & 0xff;
if ((rfc_1423_padding < 1) || (rfc_1423_padding > blockSize))
throw new IOException(
"Decrypted PEM has wrong padding, did you specify the correct password?");
for (int i = 2; i <= rfc_1423_padding; i++) {
if (buff[buff.length - i] != rfc_1423_padding)
throw new IOException(
"Decrypted PEM has wrong padding, did you specify the correct password?");
}
byte[] tmp = new byte[buff.length - rfc_1423_padding];
System.arraycopy(buff, 0, tmp, 0, buff.length - rfc_1423_padding);
return tmp;
}
}
| Java |
package com.trilead.ssh2.crypto;
import com.trilead.ssh2.compression.CompressionFactory;
import com.trilead.ssh2.crypto.cipher.BlockCipherFactory;
import com.trilead.ssh2.crypto.digest.MAC;
import com.trilead.ssh2.transport.KexManager;
/**
* CryptoWishList.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: CryptoWishList.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public class CryptoWishList {
public String[] kexAlgorithms = KexManager.getDefaultKexAlgorithmList();
public String[] serverHostKeyAlgorithms = KexManager
.getDefaultServerHostkeyAlgorithmList();
public String[] c2s_enc_algos = BlockCipherFactory.getDefaultCipherList();
public String[] s2c_enc_algos = BlockCipherFactory.getDefaultCipherList();
public String[] c2s_mac_algos = MAC.getMacList();
public String[] s2c_mac_algos = MAC.getMacList();
public String[] c2s_comp_algos = CompressionFactory
.getDefaultCompressorList();
public String[] s2c_comp_algos = CompressionFactory
.getDefaultCompressorList();
}
| Java |
package com.trilead.ssh2.crypto.dh;
import java.math.BigInteger;
import java.security.SecureRandom;
import com.trilead.ssh2.DHGexParameters;
import com.trilead.ssh2.crypto.digest.HashForSSH2Types;
/**
* DhGroupExchange.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: DhGroupExchange.java,v 1.1 2007/10/15 12:49:57 cplattne Exp $
*/
public class DhGroupExchange {
/* Given by the standard */
private BigInteger p;
private BigInteger g;
/* Client public and private */
private BigInteger e;
private BigInteger x;
/* Server public */
private BigInteger f;
/* Shared secret */
private BigInteger k;
public DhGroupExchange(BigInteger p, BigInteger g) {
this.p = p;
this.g = g;
}
public byte[] calculateH(byte[] clientversion, byte[] serverversion,
byte[] clientKexPayload, byte[] serverKexPayload, byte[] hostKey,
DHGexParameters para) {
HashForSSH2Types hash = new HashForSSH2Types("SHA1");
hash.updateByteString(clientversion);
hash.updateByteString(serverversion);
hash.updateByteString(clientKexPayload);
hash.updateByteString(serverKexPayload);
hash.updateByteString(hostKey);
if (para.getMin_group_len() > 0)
hash.updateUINT32(para.getMin_group_len());
hash.updateUINT32(para.getPref_group_len());
if (para.getMax_group_len() > 0)
hash.updateUINT32(para.getMax_group_len());
hash.updateBigInt(p);
hash.updateBigInt(g);
hash.updateBigInt(e);
hash.updateBigInt(f);
hash.updateBigInt(k);
return hash.getDigest();
}
/**
* @return Returns the e.
*/
public BigInteger getE() {
if (e == null)
throw new IllegalStateException("Not initialized!");
return e;
}
/**
* @return Returns the shared secret k.
*/
public BigInteger getK() {
if (k == null)
throw new IllegalStateException(
"Shared secret not yet known, need f first!");
return k;
}
public void init(SecureRandom rnd) {
k = null;
x = new BigInteger(p.bitLength() - 1, rnd);
e = g.modPow(x, p);
}
/**
* Sets f and calculates the shared secret.
*/
public void setF(BigInteger f) {
if (e == null)
throw new IllegalStateException("Not initialized!");
BigInteger zero = BigInteger.valueOf(0);
if (zero.compareTo(f) >= 0 || p.compareTo(f) <= 0)
throw new IllegalArgumentException("Invalid f specified!");
this.f = f;
this.k = f.modPow(x, p);
}
}
| Java |
package com.trilead.ssh2.crypto.dh;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.SecureRandom;
import com.trilead.ssh2.crypto.digest.HashForSSH2Types;
import com.trilead.ssh2.log.Logger;
/**
* DhExchange.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: DhExchange.java,v 1.2 2008/04/01 12:38:09 cplattne Exp $
*/
public class DhExchange {
private static final Logger log = Logger.getLogger(DhExchange.class);
/* Given by the standard */
static final BigInteger p1, p14;
static final BigInteger g;
BigInteger p;
/* Client public and private */
BigInteger e;
BigInteger x;
/* Server public */
BigInteger f;
/* Shared secret */
BigInteger k;
static {
final String p1_string = "17976931348623159077083915679378745319786029604875"
+ "60117064444236841971802161585193689478337958649255415021805654859805036464"
+ "40548199239100050792877003355816639229553136239076508735759914822574862575"
+ "00742530207744771258955095793777842444242661733472762929938766870920560605"
+ "0270810842907692932019128194467627007";
final String p14_string = "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129"
+ "024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0"
+ "A6DF25F14374FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB"
+ "6F406B7EDEE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A"
+ "163BF0598DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208"
+ "552BB9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36C"
+ "E3BE39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF69558171"
+ "83995497CEA956AE515D2261898FA051015728E5A8AACAA68FFFFFFFFFFFFFFFF";
p1 = new BigInteger(p1_string);
p14 = new BigInteger(p14_string, 16);
g = new BigInteger("2");
}
public DhExchange() {
}
public byte[] calculateH(byte[] clientversion, byte[] serverversion,
byte[] clientKexPayload, byte[] serverKexPayload, byte[] hostKey)
throws UnsupportedEncodingException {
HashForSSH2Types hash = new HashForSSH2Types("SHA1");
if (log.isEnabled()) {
log.log(90, "Client: '" + new String(clientversion, "ISO-8859-1")
+ "'");
log.log(90, "Server: '" + new String(serverversion, "ISO-8859-1")
+ "'");
}
hash.updateByteString(clientversion);
hash.updateByteString(serverversion);
hash.updateByteString(clientKexPayload);
hash.updateByteString(serverKexPayload);
hash.updateByteString(hostKey);
hash.updateBigInt(e);
hash.updateBigInt(f);
hash.updateBigInt(k);
return hash.getDigest();
}
/**
* @return Returns the e.
* @throws IllegalStateException
*/
public BigInteger getE() {
if (e == null)
throw new IllegalStateException("DhDsaExchange not initialized!");
return e;
}
/**
* @return Returns the shared secret k.
* @throws IllegalStateException
*/
public BigInteger getK() {
if (k == null)
throw new IllegalStateException(
"Shared secret not yet known, need f first!");
return k;
}
public void init(int group, SecureRandom rnd) {
k = null;
if (group == 1)
p = p1;
else if (group == 14)
p = p14;
else
throw new IllegalArgumentException("Unknown DH group " + group);
x = new BigInteger(p.bitLength() - 1, rnd);
e = g.modPow(x, p);
}
/**
* @param f
*/
public void setF(BigInteger f) {
if (e == null)
throw new IllegalStateException("DhDsaExchange not initialized!");
BigInteger zero = BigInteger.valueOf(0);
if (zero.compareTo(f) >= 0 || p.compareTo(f) <= 0)
throw new IllegalArgumentException("Invalid f specified!");
this.f = f;
this.k = f.modPow(x, p);
}
}
| Java |
package com.trilead.ssh2.crypto;
/**
* Parsed PEM structure.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: PEMStructure.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public class PEMStructure {
public int pemType;
String dekInfo[];
String procType[];
public byte[] data;
} | Java |
package com.trilead.ssh2.crypto;
import java.math.BigInteger;
import com.trilead.ssh2.crypto.digest.HashForSSH2Types;
/**
* Establishes key material for iv/key/mac (both directions).
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: KeyMaterial.java,v 1.1 2007/10/15 12:49:56 cplattne Exp $
*/
public class KeyMaterial {
private static byte[] calculateKey(HashForSSH2Types sh, BigInteger K,
byte[] H, byte type, byte[] SessionID, int keyLength) {
byte[] res = new byte[keyLength];
int dglen = sh.getDigestLength();
int numRounds = (keyLength + dglen - 1) / dglen;
byte[][] tmp = new byte[numRounds][];
sh.reset();
sh.updateBigInt(K);
sh.updateBytes(H);
sh.updateByte(type);
sh.updateBytes(SessionID);
tmp[0] = sh.getDigest();
int off = 0;
int produced = Math.min(dglen, keyLength);
System.arraycopy(tmp[0], 0, res, off, produced);
keyLength -= produced;
off += produced;
for (int i = 1; i < numRounds; i++) {
sh.updateBigInt(K);
sh.updateBytes(H);
for (int j = 0; j < i; j++)
sh.updateBytes(tmp[j]);
tmp[i] = sh.getDigest();
produced = Math.min(dglen, keyLength);
System.arraycopy(tmp[i], 0, res, off, produced);
keyLength -= produced;
off += produced;
}
return res;
}
public static KeyMaterial create(String hashType, byte[] H, BigInteger K,
byte[] SessionID, int keyLengthCS, int blockSizeCS,
int macLengthCS, int keyLengthSC, int blockSizeSC, int macLengthSC)
throws IllegalArgumentException {
KeyMaterial km = new KeyMaterial();
HashForSSH2Types sh = new HashForSSH2Types(hashType);
km.initial_iv_client_to_server = calculateKey(sh, K, H, (byte) 'A',
SessionID, blockSizeCS);
km.initial_iv_server_to_client = calculateKey(sh, K, H, (byte) 'B',
SessionID, blockSizeSC);
km.enc_key_client_to_server = calculateKey(sh, K, H, (byte) 'C',
SessionID, keyLengthCS);
km.enc_key_server_to_client = calculateKey(sh, K, H, (byte) 'D',
SessionID, keyLengthSC);
km.integrity_key_client_to_server = calculateKey(sh, K, H, (byte) 'E',
SessionID, macLengthCS);
km.integrity_key_server_to_client = calculateKey(sh, K, H, (byte) 'F',
SessionID, macLengthSC);
return km;
}
public byte[] initial_iv_client_to_server;
public byte[] initial_iv_server_to_client;
public byte[] enc_key_client_to_server;
public byte[] enc_key_server_to_client;
public byte[] integrity_key_client_to_server;
public byte[] integrity_key_server_to_client;
}
| Java |
package com.trilead.ssh2;
/**
* A <code>SFTPv3DirectoryEntry</code> as returned by
* {@link SFTPv3Client#ls(String)}.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: SFTPv3DirectoryEntry.java,v 1.1 2007/10/15 12:49:56 cplattne
* Exp $
*/
public class SFTPv3DirectoryEntry {
/**
* A relative name within the directory, without any path components.
*/
public String filename;
/**
* An expanded format for the file name, similar to what is returned by
* "ls -l" on Un*x systems.
* <p>
* The format of this field is unspecified by the SFTP v3 protocol. It MUST
* be suitable for use in the output of a directory listing command (in
* fact, the recommended operation for a directory listing command is to
* simply display this data). However, clients SHOULD NOT attempt to parse
* the longname field for file attributes; they SHOULD use the attrs field
* instead.
* <p>
* The recommended format for the longname field is as follows:<br>
* <code>-rwxr-xr-x 1 mjos staff 348911 Mar 25 14:29 t-filexfer</code>
*/
public String longEntry;
/**
* The attributes of this entry.
*/
public SFTPv3FileAttributes attributes;
}
| Java |
package com.trilead.ssh2.util;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Collections;
import java.util.LinkedList;
import com.trilead.ssh2.log.Logger;
/**
* TimeoutService (beta). Here you can register a timeout.
* <p>
* Implemented having large scale programs in mind: if you open many concurrent
* SSH connections that rely on timeouts, then there will be only one timeout
* thread. Once all timeouts have expired/are cancelled, the thread will (sooner
* or later) exit. Only after new timeouts arrive a new thread (singleton) will
* be instantiated.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: TimeoutService.java,v 1.1 2007/10/15 12:49:57 cplattne Exp $
*/
public class TimeoutService {
private static class TimeoutThread extends Thread {
@Override
public void run() {
synchronized (todolist) {
while (true) {
if (todolist.size() == 0) {
timeoutThread = null;
return;
}
long now = System.currentTimeMillis();
TimeoutToken tt = (TimeoutToken) todolist.getFirst();
if (tt.runTime > now) {
/* Not ready yet, sleep a little bit */
try {
todolist.wait(tt.runTime - now);
} catch (InterruptedException e) {
}
/*
* We cannot simply go on, since it could be that the
* token was removed (cancelled) or another one has been
* inserted in the meantime.
*/
continue;
}
todolist.removeFirst();
try {
tt.handler.run();
} catch (Exception e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
log.log(20,
"Exeception in Timeout handler:"
+ e.getMessage() + "(" + sw.toString()
+ ")");
}
}
}
}
}
public static class TimeoutToken implements Comparable {
private long runTime;
private Runnable handler;
private TimeoutToken(long runTime, Runnable handler) {
this.runTime = runTime;
this.handler = handler;
}
@Override
public int compareTo(Object o) {
TimeoutToken t = (TimeoutToken) o;
if (runTime > t.runTime)
return 1;
if (runTime == t.runTime)
return 0;
return -1;
}
}
private static final Logger log = Logger.getLogger(TimeoutService.class);
/* The list object is also used for locking purposes */
private static final LinkedList todolist = new LinkedList();
private static Thread timeoutThread = null;
/**
* It is assumed that the passed handler will not execute for a long time.
*
* @param runTime
* @param handler
* @return a TimeoutToken that can be used to cancel the timeout.
*/
public static final TimeoutToken addTimeoutHandler(long runTime,
Runnable handler) {
TimeoutToken token = new TimeoutToken(runTime, handler);
synchronized (todolist) {
todolist.add(token);
Collections.sort(todolist);
if (timeoutThread != null)
timeoutThread.interrupt();
else {
timeoutThread = new TimeoutThread();
timeoutThread.setDaemon(true);
timeoutThread.start();
}
}
return token;
}
public static final void cancelTimeoutHandler(TimeoutToken token) {
synchronized (todolist) {
todolist.remove(token);
if (timeoutThread != null)
timeoutThread.interrupt();
}
}
}
| Java |
package com.trilead.ssh2.util;
/**
* Tokenizer. Why? Because StringTokenizer is not available in J2ME.
*
* @author Christian Plattner, plattner@trilead.com
* @version $Id: Tokenizer.java,v 1.1 2007/10/15 12:49:57 cplattne Exp $
*/
public class Tokenizer {
/**
* Exists because StringTokenizer is not available in J2ME. Returns an array
* with at least 1 entry.
*
* @param source
* must be non-null
* @param delimiter
* @return an array of Strings
*/
public static String[] parseTokens(String source, char delimiter) {
int numtoken = 1;
for (int i = 0; i < source.length(); i++) {
if (source.charAt(i) == delimiter)
numtoken++;
}
String list[] = new String[numtoken];
int nextfield = 0;
for (int i = 0; i < numtoken; i++) {
if (nextfield >= source.length()) {
list[i] = "";
} else {
int idx = source.indexOf(delimiter, nextfield);
if (idx == -1)
idx = source.length();
list[i] = source.substring(nextfield, idx);
nextfield = idx + 1;
}
}
return list;
}
}
| Java |
/* proxydroid - Global / Individual Proxy App for Android
* Copyright (C) 2011 K's Maze <kafkasmaze@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.ksmaze.android.preference;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.preference.ListPreference;
import android.preference.Preference;
import android.util.AttributeSet;
/**
* A {@link Preference} that displays a list of entries as
* a dialog and allows multiple selections
* <p>
* This preference will store a string into the SharedPreferences. This string will be the values selected
* from the {@link #setEntryValues(CharSequence[])} array.
* </p>
*/
public class ListPreferenceMultiSelect extends ListPreference {
//Need to make sure the SEPARATOR is unique and weird enough that it doesn't match one of the entries.
//Not using any fancy symbols because this is interpreted as a regex for splitting strings.
private static final String SEPARATOR = " , ";
public static String[] parseStoredValue(CharSequence val) {
if (val == null)
return null;
if ( "".equals(val) )
return null;
else
return ((String)val).split(SEPARATOR);
}
private boolean[] mClickedDialogEntryIndices;
public ListPreferenceMultiSelect(Context context) {
this(context, null);
}
public ListPreferenceMultiSelect(Context context, AttributeSet attrs) {
super(context, attrs);
mClickedDialogEntryIndices = new boolean[getEntries().length];
}
@Override
protected void onDialogClosed(boolean positiveResult) {
// super.onDialogClosed(positiveResult);
CharSequence[] entryValues = getEntryValues();
if (positiveResult && entryValues != null) {
StringBuffer value = new StringBuffer();
for ( int i=0; i<entryValues.length; i++ ) {
if ( mClickedDialogEntryIndices[i] ) {
value.append(entryValues[i]).append(SEPARATOR);
}
}
if (callChangeListener(value)) {
String val = value.toString();
if ( val.length() > 0 )
val = val.substring(0, val.length()-SEPARATOR.length());
setValue(val);
}
}
}
@Override
protected void onPrepareDialogBuilder(Builder builder) {
CharSequence[] entries = getEntries();
CharSequence[] entryValues = getEntryValues();
if (entries == null || entryValues == null || entries.length != entryValues.length ) {
throw new IllegalStateException(
"ListPreference requires an entries array and an entryValues array which are both the same length");
}
restoreCheckedEntries();
builder.setMultiChoiceItems(entries, mClickedDialogEntryIndices,
new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean val) {
mClickedDialogEntryIndices[which] = val;
}
});
}
private void restoreCheckedEntries() {
CharSequence[] entryValues = getEntryValues();
String[] vals = parseStoredValue(getValue());
if ( vals != null ) {
for ( int j=0; j<vals.length; j++ ) {
String val = vals[j].trim();
for ( int i=0; i<entryValues.length; i++ ) {
CharSequence entry = entryValues[i];
if ( entry.equals(val) ) {
mClickedDialogEntryIndices[i] = true;
break;
}
}
}
}
}
@Override
public void setEntries(CharSequence[] entries) {
super.setEntries(entries);
mClickedDialogEntryIndices = new boolean[entries.length];
}
}
| Java |
/* -*-mode:java; c-basic-offset:2; -*- */
/*
Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,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:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. 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.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
package com.jcraft.jzlib;
final class InfBlocks {
static final private int MANY = 1440;
// And'ing with mask[n] masks the lower n bits
static final private int[] inflate_mask = { 0x00000000, 0x00000001,
0x00000003, 0x00000007, 0x0000000f, 0x0000001f, 0x0000003f,
0x0000007f, 0x000000ff, 0x000001ff, 0x000003ff, 0x000007ff,
0x00000fff, 0x00001fff, 0x00003fff, 0x00007fff, 0x0000ffff };
// Table for deflate from PKZIP's appnote.txt.
static final int[] border = { // Order of the bit length code lengths
16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 };
static final private int Z_OK = 0;
static final private int Z_STREAM_END = 1;
static final private int Z_NEED_DICT = 2;
static final private int Z_ERRNO = -1;
static final private int Z_STREAM_ERROR = -2;
static final private int Z_DATA_ERROR = -3;
static final private int Z_MEM_ERROR = -4;
static final private int Z_BUF_ERROR = -5;
static final private int Z_VERSION_ERROR = -6;
static final private int TYPE = 0; // get type bits (3, including end bit)
static final private int LENS = 1; // get lengths for stored
static final private int STORED = 2;// processing stored block
static final private int TABLE = 3; // get table lengths
static final private int BTREE = 4; // get bit lengths tree for a dynamic
// block
static final private int DTREE = 5; // get length, distance trees for a
// dynamic block
static final private int CODES = 6; // processing fixed or dynamic block
static final private int DRY = 7; // output remaining window bytes
static final private int DONE = 8; // finished last block, done
static final private int BAD = 9; // ot a data error--stuck here
int mode; // current inflate_block mode
int left; // if STORED, bytes left to copy
int table; // table lengths (14 bits)
int index; // index into blens (or border)
int[] blens; // bit lengths of codes
int[] bb = new int[1]; // bit length tree depth
int[] tb = new int[1]; // bit length decoding tree
InfCodes codes = new InfCodes(); // if CODES, current state
int last; // true if this block is the last block
// mode independent information
int bitk; // bits in bit buffer
int bitb; // bit buffer
int[] hufts; // single malloc for tree space
byte[] window; // sliding window
int end; // one byte after sliding window
int read; // window read pointer
int write; // window write pointer
Object checkfn; // check function
long check; // check on output
InfTree inftree = new InfTree();
InfBlocks(ZStream z, Object checkfn, int w) {
hufts = new int[MANY * 3];
window = new byte[w];
end = w;
this.checkfn = checkfn;
mode = TYPE;
reset(z, null);
}
void free(ZStream z) {
reset(z, null);
window = null;
hufts = null;
// ZFREE(z, s);
}
// copy as much as possible from the sliding window to the output area
int inflate_flush(ZStream z, int r) {
int n;
int p;
int q;
// local copies of source and destination pointers
p = z.next_out_index;
q = read;
// compute number of bytes to copy as far as end of window
n = ((q <= write ? write : end) - q);
if (n > z.avail_out)
n = z.avail_out;
if (n != 0 && r == Z_BUF_ERROR)
r = Z_OK;
// update counters
z.avail_out -= n;
z.total_out += n;
// update check information
if (checkfn != null)
z.adler = check = z._adler.adler32(check, window, q, n);
// copy as far as end of window
System.arraycopy(window, q, z.next_out, p, n);
p += n;
q += n;
// see if more to copy at beginning of window
if (q == end) {
// wrap pointers
q = 0;
if (write == end)
write = 0;
// compute bytes to copy
n = write - q;
if (n > z.avail_out)
n = z.avail_out;
if (n != 0 && r == Z_BUF_ERROR)
r = Z_OK;
// update counters
z.avail_out -= n;
z.total_out += n;
// update check information
if (checkfn != null)
z.adler = check = z._adler.adler32(check, window, q, n);
// copy
System.arraycopy(window, q, z.next_out, p, n);
p += n;
q += n;
}
// update pointers
z.next_out_index = p;
read = q;
// done
return r;
}
int proc(ZStream z, int r) {
int t; // temporary storage
int b; // bit buffer
int k; // bits in bit buffer
int p; // input data pointer
int n; // bytes available there
int q; // output window write pointer
int m; // bytes to end of window or read pointer
// copy input/output information to locals (UPDATE macro restores)
{
p = z.next_in_index;
n = z.avail_in;
b = bitb;
k = bitk;
}
{
q = write;
m = (q < read ? read - q - 1 : end - q);
}
// process input based on current state
while (true) {
switch (mode) {
case TYPE:
while (k < (3)) {
if (n != 0) {
r = Z_OK;
} else {
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
write = q;
return inflate_flush(z, r);
}
;
n--;
b |= (z.next_in[p++] & 0xff) << k;
k += 8;
}
t = (b & 7);
last = t & 1;
switch (t >>> 1) {
case 0: // stored
{
b >>>= (3);
k -= (3);
}
t = k & 7; // go to byte boundary
{
b >>>= (t);
k -= (t);
}
mode = LENS; // get length of stored block
break;
case 1: // fixed
{
int[] bl = new int[1];
int[] bd = new int[1];
int[][] tl = new int[1][];
int[][] td = new int[1][];
InfTree.inflate_trees_fixed(bl, bd, tl, td, z);
codes.init(bl[0], bd[0], tl[0], 0, td[0], 0, z);
}
{
b >>>= (3);
k -= (3);
}
mode = CODES;
break;
case 2: // dynamic
{
b >>>= (3);
k -= (3);
}
mode = TABLE;
break;
case 3: // illegal
{
b >>>= (3);
k -= (3);
}
mode = BAD;
z.msg = "invalid block type";
r = Z_DATA_ERROR;
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
write = q;
return inflate_flush(z, r);
}
break;
case LENS:
while (k < (32)) {
if (n != 0) {
r = Z_OK;
} else {
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
write = q;
return inflate_flush(z, r);
}
;
n--;
b |= (z.next_in[p++] & 0xff) << k;
k += 8;
}
if ((((~b) >>> 16) & 0xffff) != (b & 0xffff)) {
mode = BAD;
z.msg = "invalid stored block lengths";
r = Z_DATA_ERROR;
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
write = q;
return inflate_flush(z, r);
}
left = (b & 0xffff);
b = k = 0; // dump bits
mode = left != 0 ? STORED : (last != 0 ? DRY : TYPE);
break;
case STORED:
if (n == 0) {
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
write = q;
return inflate_flush(z, r);
}
if (m == 0) {
if (q == end && read != 0) {
q = 0;
m = (q < read ? read - q - 1 : end - q);
}
if (m == 0) {
write = q;
r = inflate_flush(z, r);
q = write;
m = (q < read ? read - q - 1 : end - q);
if (q == end && read != 0) {
q = 0;
m = (q < read ? read - q - 1 : end - q);
}
if (m == 0) {
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
write = q;
return inflate_flush(z, r);
}
}
}
r = Z_OK;
t = left;
if (t > n)
t = n;
if (t > m)
t = m;
System.arraycopy(z.next_in, p, window, q, t);
p += t;
n -= t;
q += t;
m -= t;
if ((left -= t) != 0)
break;
mode = last != 0 ? DRY : TYPE;
break;
case TABLE:
while (k < (14)) {
if (n != 0) {
r = Z_OK;
} else {
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
write = q;
return inflate_flush(z, r);
}
;
n--;
b |= (z.next_in[p++] & 0xff) << k;
k += 8;
}
table = t = (b & 0x3fff);
if ((t & 0x1f) > 29 || ((t >> 5) & 0x1f) > 29) {
mode = BAD;
z.msg = "too many length or distance symbols";
r = Z_DATA_ERROR;
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
write = q;
return inflate_flush(z, r);
}
t = 258 + (t & 0x1f) + ((t >> 5) & 0x1f);
if (blens == null || blens.length < t) {
blens = new int[t];
} else {
for (int i = 0; i < t; i++) {
blens[i] = 0;
}
}
{
b >>>= (14);
k -= (14);
}
index = 0;
mode = BTREE;
case BTREE:
while (index < 4 + (table >>> 10)) {
while (k < (3)) {
if (n != 0) {
r = Z_OK;
} else {
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
write = q;
return inflate_flush(z, r);
}
;
n--;
b |= (z.next_in[p++] & 0xff) << k;
k += 8;
}
blens[border[index++]] = b & 7;
{
b >>>= (3);
k -= (3);
}
}
while (index < 19) {
blens[border[index++]] = 0;
}
bb[0] = 7;
t = inftree.inflate_trees_bits(blens, bb, tb, hufts, z);
if (t != Z_OK) {
r = t;
if (r == Z_DATA_ERROR) {
blens = null;
mode = BAD;
}
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
write = q;
return inflate_flush(z, r);
}
index = 0;
mode = DTREE;
case DTREE:
while (true) {
t = table;
if (!(index < 258 + (t & 0x1f) + ((t >> 5) & 0x1f))) {
break;
}
int[] h;
int i, j, c;
t = bb[0];
while (k < (t)) {
if (n != 0) {
r = Z_OK;
} else {
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
write = q;
return inflate_flush(z, r);
}
;
n--;
b |= (z.next_in[p++] & 0xff) << k;
k += 8;
}
if (tb[0] == -1) {
// System.err.println("null...");
}
t = hufts[(tb[0] + (b & inflate_mask[t])) * 3 + 1];
c = hufts[(tb[0] + (b & inflate_mask[t])) * 3 + 2];
if (c < 16) {
b >>>= (t);
k -= (t);
blens[index++] = c;
} else { // c == 16..18
i = c == 18 ? 7 : c - 14;
j = c == 18 ? 11 : 3;
while (k < (t + i)) {
if (n != 0) {
r = Z_OK;
} else {
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
write = q;
return inflate_flush(z, r);
}
;
n--;
b |= (z.next_in[p++] & 0xff) << k;
k += 8;
}
b >>>= (t);
k -= (t);
j += (b & inflate_mask[i]);
b >>>= (i);
k -= (i);
i = index;
t = table;
if (i + j > 258 + (t & 0x1f) + ((t >> 5) & 0x1f)
|| (c == 16 && i < 1)) {
blens = null;
mode = BAD;
z.msg = "invalid bit length repeat";
r = Z_DATA_ERROR;
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
write = q;
return inflate_flush(z, r);
}
c = c == 16 ? blens[i - 1] : 0;
do {
blens[i++] = c;
} while (--j != 0);
index = i;
}
}
tb[0] = -1;
{
int[] bl = new int[1];
int[] bd = new int[1];
int[] tl = new int[1];
int[] td = new int[1];
bl[0] = 9; // must be <= 9 for lookahead assumptions
bd[0] = 6; // must be <= 9 for lookahead assumptions
t = table;
t = inftree.inflate_trees_dynamic(257 + (t & 0x1f),
1 + ((t >> 5) & 0x1f), blens, bl, bd, tl, td,
hufts, z);
if (t != Z_OK) {
if (t == Z_DATA_ERROR) {
blens = null;
mode = BAD;
}
r = t;
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
write = q;
return inflate_flush(z, r);
}
codes.init(bl[0], bd[0], hufts, tl[0], hufts, td[0], z);
}
mode = CODES;
case CODES:
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
write = q;
if ((r = codes.proc(this, z, r)) != Z_STREAM_END) {
return inflate_flush(z, r);
}
r = Z_OK;
codes.free(z);
p = z.next_in_index;
n = z.avail_in;
b = bitb;
k = bitk;
q = write;
m = (q < read ? read - q - 1 : end - q);
if (last == 0) {
mode = TYPE;
break;
}
mode = DRY;
case DRY:
write = q;
r = inflate_flush(z, r);
q = write;
m = (q < read ? read - q - 1 : end - q);
if (read != write) {
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
write = q;
return inflate_flush(z, r);
}
mode = DONE;
case DONE:
r = Z_STREAM_END;
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
write = q;
return inflate_flush(z, r);
case BAD:
r = Z_DATA_ERROR;
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
write = q;
return inflate_flush(z, r);
default:
r = Z_STREAM_ERROR;
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
write = q;
return inflate_flush(z, r);
}
}
}
void reset(ZStream z, long[] c) {
if (c != null)
c[0] = check;
if (mode == BTREE || mode == DTREE) {
}
if (mode == CODES) {
codes.free(z);
}
mode = TYPE;
bitk = 0;
bitb = 0;
read = write = 0;
if (checkfn != null)
z.adler = check = z._adler.adler32(0L, null, 0, 0);
}
void set_dictionary(byte[] d, int start, int n) {
System.arraycopy(d, start, window, 0, n);
read = write = n;
}
// Returns true if inflate is currently at the end of a block generated
// by Z_SYNC_FLUSH or Z_FULL_FLUSH.
int sync_point() {
return mode == LENS ? 1 : 0;
}
}
| Java |
/* -*-mode:java; c-basic-offset:2; -*- */
/*
Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,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:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. 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.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
package com.jcraft.jzlib;
final class StaticTree {
static final private int MAX_BITS = 15;
static final private int BL_CODES = 19;
static final private int D_CODES = 30;
static final private int LITERALS = 256;
static final private int LENGTH_CODES = 29;
static final private int L_CODES = (LITERALS + 1 + LENGTH_CODES);
// Bit length codes must not exceed MAX_BL_BITS bits
static final int MAX_BL_BITS = 7;
static final short[] static_ltree = { 12, 8, 140, 8, 76, 8, 204, 8, 44, 8,
172, 8, 108, 8, 236, 8, 28, 8, 156, 8, 92, 8, 220, 8, 60, 8, 188,
8, 124, 8, 252, 8, 2, 8, 130, 8, 66, 8, 194, 8, 34, 8, 162, 8, 98,
8, 226, 8, 18, 8, 146, 8, 82, 8, 210, 8, 50, 8, 178, 8, 114, 8,
242, 8, 10, 8, 138, 8, 74, 8, 202, 8, 42, 8, 170, 8, 106, 8, 234,
8, 26, 8, 154, 8, 90, 8, 218, 8, 58, 8, 186, 8, 122, 8, 250, 8, 6,
8, 134, 8, 70, 8, 198, 8, 38, 8, 166, 8, 102, 8, 230, 8, 22, 8,
150, 8, 86, 8, 214, 8, 54, 8, 182, 8, 118, 8, 246, 8, 14, 8, 142,
8, 78, 8, 206, 8, 46, 8, 174, 8, 110, 8, 238, 8, 30, 8, 158, 8, 94,
8, 222, 8, 62, 8, 190, 8, 126, 8, 254, 8, 1, 8, 129, 8, 65, 8, 193,
8, 33, 8, 161, 8, 97, 8, 225, 8, 17, 8, 145, 8, 81, 8, 209, 8, 49,
8, 177, 8, 113, 8, 241, 8, 9, 8, 137, 8, 73, 8, 201, 8, 41, 8, 169,
8, 105, 8, 233, 8, 25, 8, 153, 8, 89, 8, 217, 8, 57, 8, 185, 8,
121, 8, 249, 8, 5, 8, 133, 8, 69, 8, 197, 8, 37, 8, 165, 8, 101, 8,
229, 8, 21, 8, 149, 8, 85, 8, 213, 8, 53, 8, 181, 8, 117, 8, 245,
8, 13, 8, 141, 8, 77, 8, 205, 8, 45, 8, 173, 8, 109, 8, 237, 8, 29,
8, 157, 8, 93, 8, 221, 8, 61, 8, 189, 8, 125, 8, 253, 8, 19, 9,
275, 9, 147, 9, 403, 9, 83, 9, 339, 9, 211, 9, 467, 9, 51, 9, 307,
9, 179, 9, 435, 9, 115, 9, 371, 9, 243, 9, 499, 9, 11, 9, 267, 9,
139, 9, 395, 9, 75, 9, 331, 9, 203, 9, 459, 9, 43, 9, 299, 9, 171,
9, 427, 9, 107, 9, 363, 9, 235, 9, 491, 9, 27, 9, 283, 9, 155, 9,
411, 9, 91, 9, 347, 9, 219, 9, 475, 9, 59, 9, 315, 9, 187, 9, 443,
9, 123, 9, 379, 9, 251, 9, 507, 9, 7, 9, 263, 9, 135, 9, 391, 9,
71, 9, 327, 9, 199, 9, 455, 9, 39, 9, 295, 9, 167, 9, 423, 9, 103,
9, 359, 9, 231, 9, 487, 9, 23, 9, 279, 9, 151, 9, 407, 9, 87, 9,
343, 9, 215, 9, 471, 9, 55, 9, 311, 9, 183, 9, 439, 9, 119, 9, 375,
9, 247, 9, 503, 9, 15, 9, 271, 9, 143, 9, 399, 9, 79, 9, 335, 9,
207, 9, 463, 9, 47, 9, 303, 9, 175, 9, 431, 9, 111, 9, 367, 9, 239,
9, 495, 9, 31, 9, 287, 9, 159, 9, 415, 9, 95, 9, 351, 9, 223, 9,
479, 9, 63, 9, 319, 9, 191, 9, 447, 9, 127, 9, 383, 9, 255, 9, 511,
9, 0, 7, 64, 7, 32, 7, 96, 7, 16, 7, 80, 7, 48, 7, 112, 7, 8, 7,
72, 7, 40, 7, 104, 7, 24, 7, 88, 7, 56, 7, 120, 7, 4, 7, 68, 7, 36,
7, 100, 7, 20, 7, 84, 7, 52, 7, 116, 7, 3, 8, 131, 8, 67, 8, 195,
8, 35, 8, 163, 8, 99, 8, 227, 8 };
static final short[] static_dtree = { 0, 5, 16, 5, 8, 5, 24, 5, 4, 5, 20,
5, 12, 5, 28, 5, 2, 5, 18, 5, 10, 5, 26, 5, 6, 5, 22, 5, 14, 5, 30,
5, 1, 5, 17, 5, 9, 5, 25, 5, 5, 5, 21, 5, 13, 5, 29, 5, 3, 5, 19,
5, 11, 5, 27, 5, 7, 5, 23, 5 };
static StaticTree static_l_desc = new StaticTree(static_ltree,
Tree.extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);
static StaticTree static_d_desc = new StaticTree(static_dtree,
Tree.extra_dbits, 0, D_CODES, MAX_BITS);
static StaticTree static_bl_desc = new StaticTree(null, Tree.extra_blbits,
0, BL_CODES, MAX_BL_BITS);
short[] static_tree; // static tree or null
int[] extra_bits; // extra bits for each code or null
int extra_base; // base index for extra_bits
int elems; // max number of elements in the tree
int max_length; // max bit length for the codes
StaticTree(short[] static_tree, int[] extra_bits, int extra_base,
int elems, int max_length) {
this.static_tree = static_tree;
this.extra_bits = extra_bits;
this.extra_base = extra_base;
this.elems = elems;
this.max_length = max_length;
}
}
| Java |
/* -*-mode:java; c-basic-offset:2; -*- */
/*
Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,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:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. 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.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
package com.jcraft.jzlib;
final public class JZlib {
private static final String version = "1.0.2";
// compression levels
static final public int Z_NO_COMPRESSION = 0;
static final public int Z_BEST_SPEED = 1;
static final public int Z_BEST_COMPRESSION = 9;
static final public int Z_DEFAULT_COMPRESSION = (-1);
// compression strategy
static final public int Z_FILTERED = 1;
static final public int Z_HUFFMAN_ONLY = 2;
static final public int Z_DEFAULT_STRATEGY = 0;
static final public int Z_NO_FLUSH = 0;
static final public int Z_PARTIAL_FLUSH = 1;
static final public int Z_SYNC_FLUSH = 2;
static final public int Z_FULL_FLUSH = 3;
static final public int Z_FINISH = 4;
static final public int Z_OK = 0;
static final public int Z_STREAM_END = 1;
static final public int Z_NEED_DICT = 2;
static final public int Z_ERRNO = -1;
static final public int Z_STREAM_ERROR = -2;
static final public int Z_DATA_ERROR = -3;
static final public int Z_MEM_ERROR = -4;
static final public int Z_BUF_ERROR = -5;
static final public int Z_VERSION_ERROR = -6;
public static String version() {
return version;
}
}
| Java |
/* -*-mode:java; c-basic-offset:2; -*- */
/*
Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,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:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. 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.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
package com.jcraft.jzlib;
final class Tree {
static final private int MAX_BITS = 15;
static final private int BL_CODES = 19;
static final private int D_CODES = 30;
static final private int LITERALS = 256;
static final private int LENGTH_CODES = 29;
static final private int L_CODES = (LITERALS + 1 + LENGTH_CODES);
static final private int HEAP_SIZE = (2 * L_CODES + 1);
// Bit length codes must not exceed MAX_BL_BITS bits
static final int MAX_BL_BITS = 7;
// end of block literal code
static final int END_BLOCK = 256;
// repeat previous bit length 3-6 times (2 bits of repeat count)
static final int REP_3_6 = 16;
// repeat a zero length 3-10 times (3 bits of repeat count)
static final int REPZ_3_10 = 17;
// repeat a zero length 11-138 times (7 bits of repeat count)
static final int REPZ_11_138 = 18;
// extra bits for each length code
static final int[] extra_lbits = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2,
2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 };
// extra bits for each distance code
static final int[] extra_dbits = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5,
5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 };
// extra bits for each bit length code
static final int[] extra_blbits = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 2, 3, 7 };
static final byte[] bl_order = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4,
12, 3, 13, 2, 14, 1, 15 };
// The lengths of the bit length codes are sent in order of decreasing
// probability, to avoid transmitting the lengths for unused bit
// length codes.
static final int Buf_size = 8 * 2;
// see definition of array dist_code below
static final int DIST_CODE_LEN = 512;
static final byte[] _dist_code = { 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7,
7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10,
10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11,
11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
15, 0, 0, 16, 17, 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21,
22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27,
27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
29, 29 };
static final byte[] _length_code = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9,
10, 10, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15,
15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17,
17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19,
19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22,
22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23,
23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
27, 27, 27, 27, 27, 28 };
static final int[] base_length = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14,
16, 20, 24, 28, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192,
224, 0 };
static final int[] base_dist = { 0, 1, 2, 3, 4, 6, 8, 12, 16, 24, 32, 48,
64, 96, 128, 192, 256, 384, 512, 768, 1024, 1536, 2048, 3072, 4096,
6144, 8192, 12288, 16384, 24576 };
// Reverse the first len bits of a code, using straightforward code (a
// faster
// method would use a table)
// IN assertion: 1 <= len <= 15
static int bi_reverse(int code, // the value to invert
int len // its bit length
) {
int res = 0;
do {
res |= code & 1;
code >>>= 1;
res <<= 1;
} while (--len > 0);
return res >>> 1;
}
// Mapping from a distance to a distance code. dist is the distance - 1 and
// must not have side effects. _dist_code[256] and _dist_code[257] are never
// used.
static int d_code(int dist) {
return ((dist) < 256 ? _dist_code[dist]
: _dist_code[256 + ((dist) >>> 7)]);
}
// Generate the codes for a given tree and bit counts (which need not be
// optimal).
// IN assertion: the array bl_count contains the bit length statistics for
// the given tree and the field len is set for all tree elements.
// OUT assertion: the field code is set for all tree elements of non
// zero code length.
static void gen_codes(short[] tree, // the tree to decorate
int max_code, // largest code with non zero frequency
short[] bl_count // number of codes at each bit length
) {
short[] next_code = new short[MAX_BITS + 1]; // next code value for each
// bit length
short code = 0; // running code value
int bits; // bit index
int n; // code index
// The distribution counts are first used to generate the code values
// without bit reversal.
for (bits = 1; bits <= MAX_BITS; bits++) {
next_code[bits] = code = (short) ((code + bl_count[bits - 1]) << 1);
}
// Check that the bit counts in bl_count are consistent. The last code
// must be all ones.
// Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
// "inconsistent bit counts");
// Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
for (n = 0; n <= max_code; n++) {
int len = tree[n * 2 + 1];
if (len == 0)
continue;
// Now reverse the bits
tree[n * 2] = (short) (bi_reverse(next_code[len]++, len));
}
}
short[] dyn_tree; // the dynamic tree
int max_code; // largest code with non zero frequency
StaticTree stat_desc; // the corresponding static tree
// Construct one Huffman tree and assigns the code bit strings and lengths.
// Update the total bit length for the current block.
// IN assertion: the field freq is set for all tree elements.
// OUT assertions: the fields len and code are set to the optimal bit length
// and corresponding code. The length opt_len is updated; static_len is
// also updated if stree is not null. The field max_code is set.
void build_tree(Deflate s) {
short[] tree = dyn_tree;
short[] stree = stat_desc.static_tree;
int elems = stat_desc.elems;
int n, m; // iterate over heap elements
int max_code = -1; // largest code with non zero frequency
int node; // new node being created
// Construct the initial heap, with least frequent element in
// heap[1]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
// heap[0] is not used.
s.heap_len = 0;
s.heap_max = HEAP_SIZE;
for (n = 0; n < elems; n++) {
if (tree[n * 2] != 0) {
s.heap[++s.heap_len] = max_code = n;
s.depth[n] = 0;
} else {
tree[n * 2 + 1] = 0;
}
}
// The pkzip format requires that at least one distance code exists,
// and that at least one bit should be sent even if there is only one
// possible code. So to avoid special checks later on we force at least
// two codes of non zero frequency.
while (s.heap_len < 2) {
node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
tree[node * 2] = 1;
s.depth[node] = 0;
s.opt_len--;
if (stree != null)
s.static_len -= stree[node * 2 + 1];
// node is 0 or 1 so it does not have extra bits
}
this.max_code = max_code;
// The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
// establish sub-heaps of increasing lengths:
for (n = s.heap_len / 2; n >= 1; n--)
s.pqdownheap(tree, n);
// Construct the Huffman tree by repeatedly combining the least two
// frequent nodes.
node = elems; // next internal node of the tree
do {
// n = node of least frequency
n = s.heap[1];
s.heap[1] = s.heap[s.heap_len--];
s.pqdownheap(tree, 1);
m = s.heap[1]; // m = node of next least frequency
s.heap[--s.heap_max] = n; // keep the nodes sorted by frequency
s.heap[--s.heap_max] = m;
// Create a new node father of n and m
tree[node * 2] = (short) (tree[n * 2] + tree[m * 2]);
s.depth[node] = (byte) (Math.max(s.depth[n], s.depth[m]) + 1);
tree[n * 2 + 1] = tree[m * 2 + 1] = (short) node;
// and insert the new node in the heap
s.heap[1] = node++;
s.pqdownheap(tree, 1);
} while (s.heap_len >= 2);
s.heap[--s.heap_max] = s.heap[1];
// At this point, the fields freq and dad are set. We can now
// generate the bit lengths.
gen_bitlen(s);
// The field len is now set, we can generate the bit codes
gen_codes(tree, max_code, s.bl_count);
}
// Compute the optimal bit lengths for a tree and update the total bit
// length
// for the current block.
// IN assertion: the fields freq and dad are set, heap[heap_max] and
// above are the tree nodes sorted by increasing frequency.
// OUT assertions: the field len is set to the optimal bit length, the
// array bl_count contains the frequencies for each bit length.
// The length opt_len is updated; static_len is also updated if stree is
// not null.
void gen_bitlen(Deflate s) {
short[] tree = dyn_tree;
short[] stree = stat_desc.static_tree;
int[] extra = stat_desc.extra_bits;
int base = stat_desc.extra_base;
int max_length = stat_desc.max_length;
int h; // heap index
int n, m; // iterate over the tree elements
int bits; // bit length
int xbits; // extra bits
short f; // frequency
int overflow = 0; // number of elements with bit length too large
for (bits = 0; bits <= MAX_BITS; bits++)
s.bl_count[bits] = 0;
// In a first pass, compute the optimal bit lengths (which may
// overflow in the case of the bit length tree).
tree[s.heap[s.heap_max] * 2 + 1] = 0; // root of the heap
for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {
n = s.heap[h];
bits = tree[tree[n * 2 + 1] * 2 + 1] + 1;
if (bits > max_length) {
bits = max_length;
overflow++;
}
tree[n * 2 + 1] = (short) bits;
// We overwrite tree[n*2+1] which is no longer needed
if (n > max_code)
continue; // not a leaf node
s.bl_count[bits]++;
xbits = 0;
if (n >= base)
xbits = extra[n - base];
f = tree[n * 2];
s.opt_len += f * (bits + xbits);
if (stree != null)
s.static_len += f * (stree[n * 2 + 1] + xbits);
}
if (overflow == 0)
return;
// This happens for example on obj2 and pic of the Calgary corpus
// Find the first bit length which could increase:
do {
bits = max_length - 1;
while (s.bl_count[bits] == 0)
bits--;
s.bl_count[bits]--; // move one leaf down the tree
s.bl_count[bits + 1] += 2; // move one overflow item as its brother
s.bl_count[max_length]--;
// The brother of the overflow item also moves one step up,
// but this does not affect bl_count[max_length]
overflow -= 2;
} while (overflow > 0);
for (bits = max_length; bits != 0; bits--) {
n = s.bl_count[bits];
while (n != 0) {
m = s.heap[--h];
if (m > max_code)
continue;
if (tree[m * 2 + 1] != bits) {
s.opt_len += ((long) bits - (long) tree[m * 2 + 1])
* tree[m * 2];
tree[m * 2 + 1] = (short) bits;
}
n--;
}
}
}
}
| Java |
/* -*-mode:java; c-basic-offset:2; -*- */
/*
Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,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:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. 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.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
package com.jcraft.jzlib;
public class ZStreamException extends java.io.IOException {
public ZStreamException() {
super();
}
public ZStreamException(String s) {
super(s);
}
}
| Java |
/* -*-mode:java; c-basic-offset:2; -*- */
/*
Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,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:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. 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.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
package com.jcraft.jzlib;
public final class Deflate {
static class Config {
int good_length; // reduce lazy search above this match length
int max_lazy; // do not perform lazy search above this match length
int nice_length; // quit search above this match length
int max_chain;
int func;
Config(int good_length, int max_lazy, int nice_length, int max_chain,
int func) {
this.good_length = good_length;
this.max_lazy = max_lazy;
this.nice_length = nice_length;
this.max_chain = max_chain;
this.func = func;
}
}
static final private int MAX_MEM_LEVEL = 9;
static final private int Z_DEFAULT_COMPRESSION = -1;
static final private int MAX_WBITS = 15; // 32K LZ77 window
static final private int DEF_MEM_LEVEL = 8;
static final private int STORED = 0;
static final private int FAST = 1;
static final private int SLOW = 2;
static final private Config[] config_table;
static {
config_table = new Config[10];
// good lazy nice chain
config_table[0] = new Config(0, 0, 0, 0, STORED);
config_table[1] = new Config(4, 4, 8, 4, FAST);
config_table[2] = new Config(4, 5, 16, 8, FAST);
config_table[3] = new Config(4, 6, 32, 32, FAST);
config_table[4] = new Config(4, 4, 16, 16, SLOW);
config_table[5] = new Config(8, 16, 32, 32, SLOW);
config_table[6] = new Config(8, 16, 128, 128, SLOW);
config_table[7] = new Config(8, 32, 128, 256, SLOW);
config_table[8] = new Config(32, 128, 258, 1024, SLOW);
config_table[9] = new Config(32, 258, 258, 4096, SLOW);
}
static final private String[] z_errmsg = { "need dictionary", // Z_NEED_DICT
// 2
"stream end", // Z_STREAM_END 1
"", // Z_OK 0
"file error", // Z_ERRNO (-1)
"stream error", // Z_STREAM_ERROR (-2)
"data error", // Z_DATA_ERROR (-3)
"insufficient memory", // Z_MEM_ERROR (-4)
"buffer error", // Z_BUF_ERROR (-5)
"incompatible version",// Z_VERSION_ERROR (-6)
"" };
// block not completed, need more input or more output
static final private int NeedMore = 0;
// block flush performed
static final private int BlockDone = 1;
// finish started, need only more output at next deflate
static final private int FinishStarted = 2;
// finish done, accept no more input or output
static final private int FinishDone = 3;
// preset dictionary flag in zlib header
static final private int PRESET_DICT = 0x20;
static final private int Z_FILTERED = 1;
static final private int Z_HUFFMAN_ONLY = 2;
static final private int Z_DEFAULT_STRATEGY = 0;
static final private int Z_NO_FLUSH = 0;
static final private int Z_PARTIAL_FLUSH = 1;
static final private int Z_SYNC_FLUSH = 2;
static final private int Z_FULL_FLUSH = 3;
static final private int Z_FINISH = 4;
static final private int Z_OK = 0;
static final private int Z_STREAM_END = 1;
static final private int Z_NEED_DICT = 2;
static final private int Z_ERRNO = -1;
static final private int Z_STREAM_ERROR = -2;
static final private int Z_DATA_ERROR = -3;
static final private int Z_MEM_ERROR = -4;
static final private int Z_BUF_ERROR = -5;
static final private int Z_VERSION_ERROR = -6;
static final private int INIT_STATE = 42;
static final private int BUSY_STATE = 113;
static final private int FINISH_STATE = 666;
// The deflate compression method
static final private int Z_DEFLATED = 8;
static final private int STORED_BLOCK = 0;
static final private int STATIC_TREES = 1;
static final private int DYN_TREES = 2;
// The three kinds of block type
static final private int Z_BINARY = 0;
static final private int Z_ASCII = 1;
static final private int Z_UNKNOWN = 2;
static final private int Buf_size = 8 * 2;
// repeat previous bit length 3-6 times (2 bits of repeat count)
static final private int REP_3_6 = 16;
// repeat a zero length 3-10 times (3 bits of repeat count)
static final private int REPZ_3_10 = 17;
// repeat a zero length 11-138 times (7 bits of repeat count)
static final private int REPZ_11_138 = 18;
static final private int MIN_MATCH = 3;
static final private int MAX_MATCH = 258;
static final private int MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
static final private int MAX_BITS = 15;
static final private int D_CODES = 30;
static final private int BL_CODES = 19;
static final private int LENGTH_CODES = 29;
static final private int LITERALS = 256;
static final private int L_CODES = (LITERALS + 1 + LENGTH_CODES);
static final private int HEAP_SIZE = (2 * L_CODES + 1);
static final private int END_BLOCK = 256;
static boolean smaller(short[] tree, int n, int m, byte[] depth) {
short tn2 = tree[n * 2];
short tm2 = tree[m * 2];
return (tn2 < tm2 || (tn2 == tm2 && depth[n] <= depth[m]));
}
ZStream strm; // pointer back to this zlib stream
int status; // as the name implies
byte[] pending_buf; // output still pending
int pending_buf_size; // size of pending_buf
int pending_out; // next pending byte to output to the stream
int pending; // nb of bytes in the pending buffer
int noheader; // suppress zlib header and adler32
byte data_type; // UNKNOWN, BINARY or ASCII
byte method; // STORED (for zip only) or DEFLATED
int last_flush; // value of flush param for previous deflate call
int w_size; // LZ77 window size (32K by default)
int w_bits; // log2(w_size) (8..16)
int w_mask; // w_size - 1
byte[] window;
// Sliding window. Input bytes are read into the second half of the window,
// and move to the first half later to keep a dictionary of at least wSize
// bytes. With this organization, matches are limited to a distance of
// wSize-MAX_MATCH bytes, but this ensures that IO is always
// performed with a length multiple of the block size. Also, it limits
// the window size to 64K, which is quite useful on MSDOS.
// To do: use the user input buffer as sliding window.
int window_size;
// Actual size of window: 2*wSize, except when the user input buffer
// is directly used as sliding window.
short[] prev;
// Link to older string with same hash index. To limit the size of this
// array to 64K, this link is maintained only for the last 32K strings.
// An index in this array is thus a window index modulo 32K.
short[] head; // Heads of the hash chains or NIL.
int ins_h; // hash index of string to be inserted
int hash_size; // number of elements in hash table
int hash_bits; // log2(hash_size)
int hash_mask; // hash_size-1
// Window position at the beginning of the current output block. Gets
// negative when the window is moved backwards.
// Number of bits by which ins_h must be shifted at each input
// step. It must be such that after MIN_MATCH steps, the oldest
// byte no longer takes part in the hash key, that is:
// hash_shift * MIN_MATCH >= hash_bits
int hash_shift;
int block_start;
int match_length; // length of best match
int prev_match; // previous match
int match_available; // set if previous match exists
int strstart; // start of string to insert
int match_start; // start of matching string
int lookahead; // number of valid bytes ahead in window
// Length of the best match at previous step. Matches not greater than this
// are discarded. This is used in the lazy match evaluation.
int prev_length;
// To speed up deflation, hash chains are never searched beyond this
// length. A higher limit improves compression ratio but degrades the speed.
int max_chain_length;
// Insert new strings in the hash table only if the match length is not
// greater than this length. This saves time but degrades compression.
// max_insert_length is used only for compression levels <= 3.
// Attempt to find a better match only when the current match is strictly
// smaller than this value. This mechanism is used only for compression
// levels >= 4.
int max_lazy_match;
int level; // compression level (1..9)
int strategy; // favor or force Huffman coding
// Use a faster search when the previous match is longer than this
int good_match;
// Stop searching when current match exceeds this
int nice_match;
short[] dyn_ltree; // literal and length tree
short[] dyn_dtree; // distance tree
short[] bl_tree; // Huffman tree for bit lengths
Tree l_desc = new Tree(); // desc for literal tree
Tree d_desc = new Tree(); // desc for distance tree
Tree bl_desc = new Tree(); // desc for bit length tree
// number of codes at each bit length for an optimal tree
short[] bl_count = new short[MAX_BITS + 1];
// heap used to build the Huffman trees
int[] heap = new int[2 * L_CODES + 1];
int heap_len; // number of elements in the heap
int heap_max; // element of largest frequency
// The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
// The same heap array is used to build all trees.
// Depth of each subtree used as tie breaker for trees of equal frequency
byte[] depth = new byte[2 * L_CODES + 1];
int l_buf; // index for literals or lengths */
// Size of match buffer for literals/lengths. There are 4 reasons for
// limiting lit_bufsize to 64K:
// - frequencies can be kept in 16 bit counters
// - if compression is not successful for the first block, all input
// data is still in the window so we can still emit a stored block even
// when input comes from standard input. (This can also be done for
// all blocks if lit_bufsize is not greater than 32K.)
// - if compression is not successful for a file smaller than 64K, we can
// even emit a stored file instead of a stored block (saving 5 bytes).
// This is applicable only for zip (not gzip or zlib).
// - creating new Huffman trees less frequently may not provide fast
// adaptation to changes in the input data statistics. (Take for
// example a binary file with poorly compressible code followed by
// a highly compressible string table.) Smaller buffer sizes give
// fast adaptation but have of course the overhead of transmitting
// trees more frequently.
// - I can't count above 4
int lit_bufsize;
// Buffer for distances. To simplify the code, d_buf and l_buf have
// the same number of elements. To use different lengths, an extra flag
// array would be necessary.
int last_lit; // running index in l_buf
int d_buf; // index of pendig_buf
int opt_len; // bit length of current block with optimal trees
int static_len; // bit length of current block with static trees
int matches; // number of string matches in current block
int last_eob_len; // bit length of EOB code for last block
// Output buffer. bits are inserted starting at the bottom (least
// significant bits).
short bi_buf;
// Number of valid bits in bi_buf. All bits above the last valid bit
// are always zero.
int bi_valid;
Deflate() {
dyn_ltree = new short[HEAP_SIZE * 2];
dyn_dtree = new short[(2 * D_CODES + 1) * 2]; // distance tree
bl_tree = new short[(2 * BL_CODES + 1) * 2]; // Huffman tree for bit
// lengths
}
// Send one empty static block to give enough lookahead for inflate.
// This takes 10 bits, of which 7 may remain in the bit buffer.
// The current inflate code requires 9 bits of lookahead. If the
// last two codes for the previous block (real code plus EOB) were coded
// on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
// the last real code. In this case we send two empty static blocks instead
// of one. (There are no problems if the previous block is stored or fixed.)
// To simplify the code, we assume the worst case of last real code encoded
// on one bit only.
void _tr_align() {
send_bits(STATIC_TREES << 1, 3);
send_code(END_BLOCK, StaticTree.static_ltree);
bi_flush();
// Of the 10 bits for the empty block, we have already sent
// (10 - bi_valid) bits. The lookahead for the last real code (before
// the EOB of the previous block) was thus at least one plus the length
// of the EOB plus what we have just sent of the empty static block.
if (1 + last_eob_len + 10 - bi_valid < 9) {
send_bits(STATIC_TREES << 1, 3);
send_code(END_BLOCK, StaticTree.static_ltree);
bi_flush();
}
last_eob_len = 7;
}
// Determine the best encoding for the current block: dynamic trees, static
// trees or store, and output the encoded block to the zip file.
void _tr_flush_block(int buf, // input block, or NULL if too old
int stored_len, // length of input block
boolean eof // true if this is the last block for a file
) {
int opt_lenb, static_lenb;// opt_len and static_len in bytes
int max_blindex = 0; // index of last bit length code of non zero freq
// Build the Huffman trees unless a stored block is forced
if (level > 0) {
// Check if the file is ascii or binary
if (data_type == Z_UNKNOWN)
set_data_type();
// Construct the literal and distance trees
l_desc.build_tree(this);
d_desc.build_tree(this);
// At this point, opt_len and static_len are the total bit lengths
// of
// the compressed block data, excluding the tree representations.
// Build the bit length tree for the above two trees, and get the
// index
// in bl_order of the last bit length code to send.
max_blindex = build_bl_tree();
// Determine the best encoding. Compute first the block length in
// bytes
opt_lenb = (opt_len + 3 + 7) >>> 3;
static_lenb = (static_len + 3 + 7) >>> 3;
if (static_lenb <= opt_lenb)
opt_lenb = static_lenb;
} else {
opt_lenb = static_lenb = stored_len + 5; // force a stored block
}
if (stored_len + 4 <= opt_lenb && buf != -1) {
// 4: two words for the lengths
// The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
// Otherwise we can't have processed more than WSIZE input bytes
// since
// the last block flush, because compression would have been
// successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
// transform a block into a stored block.
_tr_stored_block(buf, stored_len, eof);
} else if (static_lenb == opt_lenb) {
send_bits((STATIC_TREES << 1) + (eof ? 1 : 0), 3);
compress_block(StaticTree.static_ltree, StaticTree.static_dtree);
} else {
send_bits((DYN_TREES << 1) + (eof ? 1 : 0), 3);
send_all_trees(l_desc.max_code + 1, d_desc.max_code + 1,
max_blindex + 1);
compress_block(dyn_ltree, dyn_dtree);
}
// The above check is made mod 2^32, for files larger than 512 MB
// and uLong implemented on 32 bits.
init_block();
if (eof) {
bi_windup();
}
}
// Send a stored block
void _tr_stored_block(int buf, // input block
int stored_len, // length of input block
boolean eof // true if this is the last block for a file
) {
send_bits((STORED_BLOCK << 1) + (eof ? 1 : 0), 3); // send block type
copy_block(buf, stored_len, true); // with header
}
// Save the match info and tally the frequency counts. Return true if
// the current block must be flushed.
boolean _tr_tally(int dist, // distance of matched string
int lc // match length-MIN_MATCH or unmatched char (if dist==0)
) {
pending_buf[d_buf + last_lit * 2] = (byte) (dist >>> 8);
pending_buf[d_buf + last_lit * 2 + 1] = (byte) dist;
pending_buf[l_buf + last_lit] = (byte) lc;
last_lit++;
if (dist == 0) {
// lc is the unmatched char
dyn_ltree[lc * 2]++;
} else {
matches++;
// Here, lc is the match length - MIN_MATCH
dist--; // dist = match distance - 1
dyn_ltree[(Tree._length_code[lc] + LITERALS + 1) * 2]++;
dyn_dtree[Tree.d_code(dist) * 2]++;
}
if ((last_lit & 0x1fff) == 0 && level > 2) {
// Compute an upper bound for the compressed length
int out_length = last_lit * 8;
int in_length = strstart - block_start;
int dcode;
for (dcode = 0; dcode < D_CODES; dcode++) {
out_length += dyn_dtree[dcode * 2]
* (5L + Tree.extra_dbits[dcode]);
}
out_length >>>= 3;
if ((matches < (last_lit / 2)) && out_length < in_length / 2)
return true;
}
return (last_lit == lit_bufsize - 1);
// We avoid equality with lit_bufsize because of wraparound at 64K
// on 16 bit machines and because stored blocks are restricted to
// 64K-1 bytes.
}
// Flush the bit buffer, keeping at most 7 bits in it.
void bi_flush() {
if (bi_valid == 16) {
put_short(bi_buf);
bi_buf = 0;
bi_valid = 0;
} else if (bi_valid >= 8) {
put_byte((byte) bi_buf);
bi_buf >>>= 8;
bi_valid -= 8;
}
}
// Flush the bit buffer and align the output on a byte boundary
void bi_windup() {
if (bi_valid > 8) {
put_short(bi_buf);
} else if (bi_valid > 0) {
put_byte((byte) bi_buf);
}
bi_buf = 0;
bi_valid = 0;
}
// Construct the Huffman tree for the bit lengths and return the index in
// bl_order of the last bit length code to send.
int build_bl_tree() {
int max_blindex; // index of last bit length code of non zero freq
// Determine the bit length frequencies for literal and distance trees
scan_tree(dyn_ltree, l_desc.max_code);
scan_tree(dyn_dtree, d_desc.max_code);
// Build the bit length tree:
bl_desc.build_tree(this);
// opt_len now includes the length of the tree representations, except
// the lengths of the bit lengths codes and the 5+5+4 bits for the
// counts.
// Determine the number of bit length codes to send. The pkzip format
// requires that at least 4 bit length codes be sent. (appnote.txt says
// 3 but the actual value used is 4.)
for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
if (bl_tree[Tree.bl_order[max_blindex] * 2 + 1] != 0)
break;
}
// Update opt_len to include the bit length tree and counts
opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
return max_blindex;
}
// Send the block data compressed using the given Huffman trees
void compress_block(short[] ltree, short[] dtree) {
int dist; // distance of matched string
int lc; // match length or unmatched char (if dist == 0)
int lx = 0; // running index in l_buf
int code; // the code to send
int extra; // number of extra bits to send
if (last_lit != 0) {
do {
dist = ((pending_buf[d_buf + lx * 2] << 8) & 0xff00)
| (pending_buf[d_buf + lx * 2 + 1] & 0xff);
lc = (pending_buf[l_buf + lx]) & 0xff;
lx++;
if (dist == 0) {
send_code(lc, ltree); // send a literal byte
} else {
// Here, lc is the match length - MIN_MATCH
code = Tree._length_code[lc];
send_code(code + LITERALS + 1, ltree); // send the length
// code
extra = Tree.extra_lbits[code];
if (extra != 0) {
lc -= Tree.base_length[code];
send_bits(lc, extra); // send the extra length bits
}
dist--; // dist is now the match distance - 1
code = Tree.d_code(dist);
send_code(code, dtree); // send the distance code
extra = Tree.extra_dbits[code];
if (extra != 0) {
dist -= Tree.base_dist[code];
send_bits(dist, extra); // send the extra distance bits
}
} // literal or match pair ?
// Check that the overlay between pending_buf and d_buf+l_buf is
// ok:
} while (lx < last_lit);
}
send_code(END_BLOCK, ltree);
last_eob_len = ltree[END_BLOCK * 2 + 1];
}
// Copy a stored block, storing first the length and its
// one's complement if requested.
void copy_block(int buf, // the input data
int len, // its length
boolean header // true if block header must be written
) {
int index = 0;
bi_windup(); // align on byte boundary
last_eob_len = 8; // enough lookahead for inflate
if (header) {
put_short((short) len);
put_short((short) ~len);
}
// while(len--!=0) {
// put_byte(window[buf+index]);
// index++;
// }
put_byte(window, buf, len);
}
int deflate(ZStream strm, int flush) {
int old_flush;
if (flush > Z_FINISH || flush < 0) {
return Z_STREAM_ERROR;
}
if (strm.next_out == null
|| (strm.next_in == null && strm.avail_in != 0)
|| (status == FINISH_STATE && flush != Z_FINISH)) {
strm.msg = z_errmsg[Z_NEED_DICT - (Z_STREAM_ERROR)];
return Z_STREAM_ERROR;
}
if (strm.avail_out == 0) {
strm.msg = z_errmsg[Z_NEED_DICT - (Z_BUF_ERROR)];
return Z_BUF_ERROR;
}
this.strm = strm; // just in case
old_flush = last_flush;
last_flush = flush;
// Write the zlib header
if (status == INIT_STATE) {
int header = (Z_DEFLATED + ((w_bits - 8) << 4)) << 8;
int level_flags = ((level - 1) & 0xff) >> 1;
if (level_flags > 3)
level_flags = 3;
header |= (level_flags << 6);
if (strstart != 0)
header |= PRESET_DICT;
header += 31 - (header % 31);
status = BUSY_STATE;
putShortMSB(header);
// Save the adler32 of the preset dictionary:
if (strstart != 0) {
putShortMSB((int) (strm.adler >>> 16));
putShortMSB((int) (strm.adler & 0xffff));
}
strm.adler = strm._adler.adler32(0, null, 0, 0);
}
// Flush as much pending output as possible
if (pending != 0) {
strm.flush_pending();
if (strm.avail_out == 0) {
// System.out.println(" avail_out==0");
// Since avail_out is 0, deflate will be called again with
// more output space, but possibly with both pending and
// avail_in equal to zero. There won't be anything to do,
// but this is not an error situation so make sure we
// return OK instead of BUF_ERROR at next call of deflate:
last_flush = -1;
return Z_OK;
}
// Make sure there is something to do and avoid duplicate
// consecutive
// flushes. For repeated and useless calls with Z_FINISH, we keep
// returning Z_STREAM_END instead of Z_BUFF_ERROR.
} else if (strm.avail_in == 0 && flush <= old_flush
&& flush != Z_FINISH) {
strm.msg = z_errmsg[Z_NEED_DICT - (Z_BUF_ERROR)];
return Z_BUF_ERROR;
}
// User must not provide more input after the first FINISH:
if (status == FINISH_STATE && strm.avail_in != 0) {
strm.msg = z_errmsg[Z_NEED_DICT - (Z_BUF_ERROR)];
return Z_BUF_ERROR;
}
// Start a new block or continue the current one.
if (strm.avail_in != 0 || lookahead != 0
|| (flush != Z_NO_FLUSH && status != FINISH_STATE)) {
int bstate = -1;
switch (config_table[level].func) {
case STORED:
bstate = deflate_stored(flush);
break;
case FAST:
bstate = deflate_fast(flush);
break;
case SLOW:
bstate = deflate_slow(flush);
break;
default:
}
if (bstate == FinishStarted || bstate == FinishDone) {
status = FINISH_STATE;
}
if (bstate == NeedMore || bstate == FinishStarted) {
if (strm.avail_out == 0) {
last_flush = -1; // avoid BUF_ERROR next call, see above
}
return Z_OK;
// If flush != Z_NO_FLUSH && avail_out == 0, the next call
// of deflate should use the same flush parameter to make sure
// that the flush is complete. So we don't have to output an
// empty block here, this will be done at next call. This also
// ensures that for a very small output buffer, we emit at most
// one empty block.
}
if (bstate == BlockDone) {
if (flush == Z_PARTIAL_FLUSH) {
_tr_align();
} else { // FULL_FLUSH or SYNC_FLUSH
_tr_stored_block(0, 0, false);
// For a full flush, this empty block will be recognized
// as a special marker by inflate_sync().
if (flush == Z_FULL_FLUSH) {
// state.head[s.hash_size-1]=0;
for (int i = 0; i < hash_size/*-1*/; i++)
// forget history
head[i] = 0;
}
}
strm.flush_pending();
if (strm.avail_out == 0) {
last_flush = -1; // avoid BUF_ERROR at next call, see above
return Z_OK;
}
}
}
if (flush != Z_FINISH)
return Z_OK;
if (noheader != 0)
return Z_STREAM_END;
// Write the zlib trailer (adler32)
putShortMSB((int) (strm.adler >>> 16));
putShortMSB((int) (strm.adler & 0xffff));
strm.flush_pending();
// If avail_out is zero, the application will call deflate again
// to flush the rest.
noheader = -1; // write the trailer only once!
return pending != 0 ? Z_OK : Z_STREAM_END;
}
// Compress as much as possible from the input stream, return the current
// block state.
// This function does not perform lazy evaluation of matches and inserts
// new strings in the dictionary only for unmatched strings or for short
// matches. It is used only for the fast compression options.
int deflate_fast(int flush) {
// short hash_head = 0; // head of the hash chain
int hash_head = 0; // head of the hash chain
boolean bflush; // set if current block must be flushed
while (true) {
// Make sure that we always have enough lookahead, except
// at the end of the input file. We need MAX_MATCH bytes
// for the next match, plus MIN_MATCH bytes to insert the
// string following the next match.
if (lookahead < MIN_LOOKAHEAD) {
fill_window();
if (lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
return NeedMore;
}
if (lookahead == 0)
break; // flush the current block
}
// Insert the string window[strstart .. strstart+2] in the
// dictionary, and set hash_head to the head of the hash chain:
if (lookahead >= MIN_MATCH) {
ins_h = (((ins_h) << hash_shift) ^ (window[(strstart)
+ (MIN_MATCH - 1)] & 0xff))
& hash_mask;
// prev[strstart&w_mask]=hash_head=head[ins_h];
hash_head = (head[ins_h] & 0xffff);
prev[strstart & w_mask] = head[ins_h];
head[ins_h] = (short) strstart;
}
// Find the longest match, discarding those <= prev_length.
// At this point we have always match_length < MIN_MATCH
if (hash_head != 0L
&& ((strstart - hash_head) & 0xffff) <= w_size
- MIN_LOOKAHEAD) {
// To simplify the code, we prevent matches with the string
// of window index 0 (in particular we have to avoid a match
// of the string with itself at the start of the input file).
if (strategy != Z_HUFFMAN_ONLY) {
match_length = longest_match(hash_head);
}
// longest_match() sets match_start
}
if (match_length >= MIN_MATCH) {
// check_match(strstart, match_start, match_length);
bflush = _tr_tally(strstart - match_start, match_length
- MIN_MATCH);
lookahead -= match_length;
// Insert new strings in the hash table only if the match length
// is not too large. This saves time but degrades compression.
if (match_length <= max_lazy_match && lookahead >= MIN_MATCH) {
match_length--; // string at strstart already in hash table
do {
strstart++;
ins_h = ((ins_h << hash_shift) ^ (window[(strstart)
+ (MIN_MATCH - 1)] & 0xff))
& hash_mask;
// prev[strstart&w_mask]=hash_head=head[ins_h];
hash_head = (head[ins_h] & 0xffff);
prev[strstart & w_mask] = head[ins_h];
head[ins_h] = (short) strstart;
// strstart never exceeds WSIZE-MAX_MATCH, so there are
// always MIN_MATCH bytes ahead.
} while (--match_length != 0);
strstart++;
} else {
strstart += match_length;
match_length = 0;
ins_h = window[strstart] & 0xff;
ins_h = (((ins_h) << hash_shift) ^ (window[strstart + 1] & 0xff))
& hash_mask;
// If lookahead < MIN_MATCH, ins_h is garbage, but it does
// not
// matter since it will be recomputed at next deflate call.
}
} else {
// No match, output a literal byte
bflush = _tr_tally(0, window[strstart] & 0xff);
lookahead--;
strstart++;
}
if (bflush) {
flush_block_only(false);
if (strm.avail_out == 0)
return NeedMore;
}
}
flush_block_only(flush == Z_FINISH);
if (strm.avail_out == 0) {
if (flush == Z_FINISH)
return FinishStarted;
else
return NeedMore;
}
return flush == Z_FINISH ? FinishDone : BlockDone;
}
// Same as above, but achieves better compression. We use a lazy
// evaluation for matches: a match is finally adopted only if there is
// no better match at the next window position.
int deflate_slow(int flush) {
// short hash_head = 0; // head of hash chain
int hash_head = 0; // head of hash chain
boolean bflush; // set if current block must be flushed
// Process the input block.
while (true) {
// Make sure that we always have enough lookahead, except
// at the end of the input file. We need MAX_MATCH bytes
// for the next match, plus MIN_MATCH bytes to insert the
// string following the next match.
if (lookahead < MIN_LOOKAHEAD) {
fill_window();
if (lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
return NeedMore;
}
if (lookahead == 0)
break; // flush the current block
}
// Insert the string window[strstart .. strstart+2] in the
// dictionary, and set hash_head to the head of the hash chain:
if (lookahead >= MIN_MATCH) {
ins_h = (((ins_h) << hash_shift) ^ (window[(strstart)
+ (MIN_MATCH - 1)] & 0xff))
& hash_mask;
// prev[strstart&w_mask]=hash_head=head[ins_h];
hash_head = (head[ins_h] & 0xffff);
prev[strstart & w_mask] = head[ins_h];
head[ins_h] = (short) strstart;
}
// Find the longest match, discarding those <= prev_length.
prev_length = match_length;
prev_match = match_start;
match_length = MIN_MATCH - 1;
if (hash_head != 0
&& prev_length < max_lazy_match
&& ((strstart - hash_head) & 0xffff) <= w_size
- MIN_LOOKAHEAD) {
// To simplify the code, we prevent matches with the string
// of window index 0 (in particular we have to avoid a match
// of the string with itself at the start of the input file).
if (strategy != Z_HUFFMAN_ONLY) {
match_length = longest_match(hash_head);
}
// longest_match() sets match_start
if (match_length <= 5
&& (strategy == Z_FILTERED || (match_length == MIN_MATCH && strstart
- match_start > 4096))) {
// If prev_match is also MIN_MATCH, match_start is garbage
// but we will ignore the current match anyway.
match_length = MIN_MATCH - 1;
}
}
// If there was a match at the previous step and the current
// match is not better, output the previous match:
if (prev_length >= MIN_MATCH && match_length <= prev_length) {
int max_insert = strstart + lookahead - MIN_MATCH;
// Do not insert strings in hash table beyond this.
// check_match(strstart-1, prev_match, prev_length);
bflush = _tr_tally(strstart - 1 - prev_match, prev_length
- MIN_MATCH);
// Insert in hash table all strings up to the end of the match.
// strstart-1 and strstart are already inserted. If there is not
// enough lookahead, the last two strings are not inserted in
// the hash table.
lookahead -= prev_length - 1;
prev_length -= 2;
do {
if (++strstart <= max_insert) {
ins_h = (((ins_h) << hash_shift) ^ (window[(strstart)
+ (MIN_MATCH - 1)] & 0xff))
& hash_mask;
// prev[strstart&w_mask]=hash_head=head[ins_h];
hash_head = (head[ins_h] & 0xffff);
prev[strstart & w_mask] = head[ins_h];
head[ins_h] = (short) strstart;
}
} while (--prev_length != 0);
match_available = 0;
match_length = MIN_MATCH - 1;
strstart++;
if (bflush) {
flush_block_only(false);
if (strm.avail_out == 0)
return NeedMore;
}
} else if (match_available != 0) {
// If there was no match at the previous position, output a
// single literal. If there was a match but the current match
// is longer, truncate the previous match to a single literal.
bflush = _tr_tally(0, window[strstart - 1] & 0xff);
if (bflush) {
flush_block_only(false);
}
strstart++;
lookahead--;
if (strm.avail_out == 0)
return NeedMore;
} else {
// There is no previous match to compare with, wait for
// the next step to decide.
match_available = 1;
strstart++;
lookahead--;
}
}
if (match_available != 0) {
bflush = _tr_tally(0, window[strstart - 1] & 0xff);
match_available = 0;
}
flush_block_only(flush == Z_FINISH);
if (strm.avail_out == 0) {
if (flush == Z_FINISH)
return FinishStarted;
else
return NeedMore;
}
return flush == Z_FINISH ? FinishDone : BlockDone;
}
// Copy without compression as much as possible from the input stream,
// return
// the current block state.
// This function does not insert new strings in the dictionary since
// uncompressible data is probably not useful. This function is used
// only for the level=0 compression option.
// NOTE: this function should be optimized to avoid extra copying from
// window to pending_buf.
int deflate_stored(int flush) {
// Stored blocks are limited to 0xffff bytes, pending_buf is limited
// to pending_buf_size, and each stored block has a 5 byte header:
int max_block_size = 0xffff;
int max_start;
if (max_block_size > pending_buf_size - 5) {
max_block_size = pending_buf_size - 5;
}
// Copy as much as possible from input to output:
while (true) {
// Fill the window as much as possible:
if (lookahead <= 1) {
fill_window();
if (lookahead == 0 && flush == Z_NO_FLUSH)
return NeedMore;
if (lookahead == 0)
break; // flush the current block
}
strstart += lookahead;
lookahead = 0;
// Emit a stored block if pending_buf will be full:
max_start = block_start + max_block_size;
if (strstart == 0 || strstart >= max_start) {
// strstart == 0 is possible when wraparound on 16-bit machine
lookahead = (strstart - max_start);
strstart = max_start;
flush_block_only(false);
if (strm.avail_out == 0)
return NeedMore;
}
// Flush if we may have to slide, otherwise block_start may become
// negative and the data will be gone:
if (strstart - block_start >= w_size - MIN_LOOKAHEAD) {
flush_block_only(false);
if (strm.avail_out == 0)
return NeedMore;
}
}
flush_block_only(flush == Z_FINISH);
if (strm.avail_out == 0)
return (flush == Z_FINISH) ? FinishStarted : NeedMore;
return flush == Z_FINISH ? FinishDone : BlockDone;
}
int deflateEnd() {
if (status != INIT_STATE && status != BUSY_STATE
&& status != FINISH_STATE) {
return Z_STREAM_ERROR;
}
// Deallocate in reverse order of allocations:
pending_buf = null;
head = null;
prev = null;
window = null;
// free
// dstate=null;
return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
}
int deflateInit(ZStream strm, int level) {
return deflateInit(strm, level, MAX_WBITS);
}
int deflateInit(ZStream strm, int level, int bits) {
return deflateInit2(strm, level, Z_DEFLATED, bits, DEF_MEM_LEVEL,
Z_DEFAULT_STRATEGY);
}
int deflateInit2(ZStream strm, int level, int method, int windowBits,
int memLevel, int strategy) {
int noheader = 0;
// byte[] my_version=ZLIB_VERSION;
//
// if (version == null || version[0] != my_version[0]
// || stream_size != sizeof(z_stream)) {
// return Z_VERSION_ERROR;
// }
strm.msg = null;
if (level == Z_DEFAULT_COMPRESSION)
level = 6;
if (windowBits < 0) { // undocumented feature: suppress zlib header
noheader = 1;
windowBits = -windowBits;
}
if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED
|| windowBits < 9 || windowBits > 15 || level < 0 || level > 9
|| strategy < 0 || strategy > Z_HUFFMAN_ONLY) {
return Z_STREAM_ERROR;
}
strm.dstate = this;
this.noheader = noheader;
w_bits = windowBits;
w_size = 1 << w_bits;
w_mask = w_size - 1;
hash_bits = memLevel + 7;
hash_size = 1 << hash_bits;
hash_mask = hash_size - 1;
hash_shift = ((hash_bits + MIN_MATCH - 1) / MIN_MATCH);
window = new byte[w_size * 2];
prev = new short[w_size];
head = new short[hash_size];
lit_bufsize = 1 << (memLevel + 6); // 16K elements by default
// We overlay pending_buf and d_buf+l_buf. This works since the average
// output size for (length,distance) codes is <= 24 bits.
pending_buf = new byte[lit_bufsize * 4];
pending_buf_size = lit_bufsize * 4;
d_buf = lit_bufsize / 2;
l_buf = (1 + 2) * lit_bufsize;
this.level = level;
// System.out.println("level="+level);
this.strategy = strategy;
this.method = (byte) method;
return deflateReset(strm);
}
int deflateParams(ZStream strm, int _level, int _strategy) {
int err = Z_OK;
if (_level == Z_DEFAULT_COMPRESSION) {
_level = 6;
}
if (_level < 0 || _level > 9 || _strategy < 0
|| _strategy > Z_HUFFMAN_ONLY) {
return Z_STREAM_ERROR;
}
if (config_table[level].func != config_table[_level].func
&& strm.total_in != 0) {
// Flush the last buffer:
err = strm.deflate(Z_PARTIAL_FLUSH);
}
if (level != _level) {
level = _level;
max_lazy_match = config_table[level].max_lazy;
good_match = config_table[level].good_length;
nice_match = config_table[level].nice_length;
max_chain_length = config_table[level].max_chain;
}
strategy = _strategy;
return err;
}
int deflateReset(ZStream strm) {
strm.total_in = strm.total_out = 0;
strm.msg = null; //
strm.data_type = Z_UNKNOWN;
pending = 0;
pending_out = 0;
if (noheader < 0) {
noheader = 0; // was set to -1 by deflate(..., Z_FINISH);
}
status = (noheader != 0) ? BUSY_STATE : INIT_STATE;
strm.adler = strm._adler.adler32(0, null, 0, 0);
last_flush = Z_NO_FLUSH;
tr_init();
lm_init();
return Z_OK;
}
int deflateSetDictionary(ZStream strm, byte[] dictionary, int dictLength) {
int length = dictLength;
int index = 0;
if (dictionary == null || status != INIT_STATE)
return Z_STREAM_ERROR;
strm.adler = strm._adler.adler32(strm.adler, dictionary, 0, dictLength);
if (length < MIN_MATCH)
return Z_OK;
if (length > w_size - MIN_LOOKAHEAD) {
length = w_size - MIN_LOOKAHEAD;
index = dictLength - length; // use the tail of the dictionary
}
System.arraycopy(dictionary, index, window, 0, length);
strstart = length;
block_start = length;
// Insert all strings in the hash table (except for the last two bytes).
// s->lookahead stays null, so s->ins_h will be recomputed at the next
// call of fill_window.
ins_h = window[0] & 0xff;
ins_h = (((ins_h) << hash_shift) ^ (window[1] & 0xff)) & hash_mask;
for (int n = 0; n <= length - MIN_MATCH; n++) {
ins_h = (((ins_h) << hash_shift) ^ (window[(n) + (MIN_MATCH - 1)] & 0xff))
& hash_mask;
prev[n & w_mask] = head[ins_h];
head[ins_h] = (short) n;
}
return Z_OK;
}
// Fill the window when the lookahead becomes insufficient.
// Updates strstart and lookahead.
//
// IN assertion: lookahead < MIN_LOOKAHEAD
// OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
// At least one byte has been read, or avail_in == 0; reads are
// performed for at least two bytes (required for the zip translate_eol
// option -- not supported here).
void fill_window() {
int n, m;
int p;
int more; // Amount of free space at the end of the window.
do {
more = (window_size - lookahead - strstart);
// Deal with !@#$% 64K limit:
if (more == 0 && strstart == 0 && lookahead == 0) {
more = w_size;
} else if (more == -1) {
// Very unlikely, but possible on 16 bit machine if strstart ==
// 0
// and lookahead == 1 (input done one byte at time)
more--;
// If the window is almost full and there is insufficient
// lookahead,
// move the upper half to the lower one to make room in the
// upper half.
} else if (strstart >= w_size + w_size - MIN_LOOKAHEAD) {
System.arraycopy(window, w_size, window, 0, w_size);
match_start -= w_size;
strstart -= w_size; // we now have strstart >= MAX_DIST
block_start -= w_size;
// Slide the hash table (could be avoided with 32 bit values
// at the expense of memory usage). We slide even when level ==
// 0
// to keep the hash table consistent if we switch back to level
// > 0
// later. (Using level 0 permanently is not an optimal usage of
// zlib, so we don't care about this pathological case.)
n = hash_size;
p = n;
do {
m = (head[--p] & 0xffff);
head[p] = (m >= w_size ? (short) (m - w_size) : 0);
} while (--n != 0);
n = w_size;
p = n;
do {
m = (prev[--p] & 0xffff);
prev[p] = (m >= w_size ? (short) (m - w_size) : 0);
// If n is not on any hash chain, prev[n] is garbage but
// its value will never be used.
} while (--n != 0);
more += w_size;
}
if (strm.avail_in == 0)
return;
// If there was no sliding:
// strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
// more == window_size - lookahead - strstart
// => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
// => more >= window_size - 2*WSIZE + 2
// In the BIG_MEM or MMAP case (not yet supported),
// window_size == input_size + MIN_LOOKAHEAD &&
// strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
// Otherwise, window_size == 2*WSIZE so more >= 2.
// If there was sliding, more >= WSIZE. So in all cases, more >= 2.
n = strm.read_buf(window, strstart + lookahead, more);
lookahead += n;
// Initialize the hash value now that we have some input:
if (lookahead >= MIN_MATCH) {
ins_h = window[strstart] & 0xff;
ins_h = (((ins_h) << hash_shift) ^ (window[strstart + 1] & 0xff))
& hash_mask;
}
// If the whole input has less than MIN_MATCH bytes, ins_h is
// garbage,
// but this is not important since only literal bytes will be
// emitted.
} while (lookahead < MIN_LOOKAHEAD && strm.avail_in != 0);
}
void flush_block_only(boolean eof) {
_tr_flush_block(block_start >= 0 ? block_start : -1, strstart
- block_start, eof);
block_start = strstart;
strm.flush_pending();
}
void init_block() {
// Initialize the trees.
for (int i = 0; i < L_CODES; i++)
dyn_ltree[i * 2] = 0;
for (int i = 0; i < D_CODES; i++)
dyn_dtree[i * 2] = 0;
for (int i = 0; i < BL_CODES; i++)
bl_tree[i * 2] = 0;
dyn_ltree[END_BLOCK * 2] = 1;
opt_len = static_len = 0;
last_lit = matches = 0;
}
void lm_init() {
window_size = 2 * w_size;
head[hash_size - 1] = 0;
for (int i = 0; i < hash_size - 1; i++) {
head[i] = 0;
}
// Set the default configuration parameters:
max_lazy_match = Deflate.config_table[level].max_lazy;
good_match = Deflate.config_table[level].good_length;
nice_match = Deflate.config_table[level].nice_length;
max_chain_length = Deflate.config_table[level].max_chain;
strstart = 0;
block_start = 0;
lookahead = 0;
match_length = prev_length = MIN_MATCH - 1;
match_available = 0;
ins_h = 0;
}
int longest_match(int cur_match) {
int chain_length = max_chain_length; // max hash chain length
int scan = strstart; // current string
int match; // matched string
int len; // length of current match
int best_len = prev_length; // best match length so far
int limit = strstart > (w_size - MIN_LOOKAHEAD) ? strstart
- (w_size - MIN_LOOKAHEAD) : 0;
int nice_match = this.nice_match;
// Stop when cur_match becomes <= limit. To simplify the code,
// we prevent matches with the string of window index 0.
int wmask = w_mask;
int strend = strstart + MAX_MATCH;
byte scan_end1 = window[scan + best_len - 1];
byte scan_end = window[scan + best_len];
// The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of
// 16.
// It is easy to get rid of this optimization if necessary.
// Do not waste too much time if we already have a good match:
if (prev_length >= good_match) {
chain_length >>= 2;
}
// Do not look for matches beyond the end of the input. This is
// necessary
// to make deflate deterministic.
if (nice_match > lookahead)
nice_match = lookahead;
do {
match = cur_match;
// Skip to next match if the match length cannot increase
// or if the match length is less than 2:
if (window[match + best_len] != scan_end
|| window[match + best_len - 1] != scan_end1
|| window[match] != window[scan]
|| window[++match] != window[scan + 1])
continue;
// The check at best_len-1 can be removed because it will be made
// again later. (This heuristic is not always a win.)
// It is not necessary to compare scan[2] and match[2] since they
// are always equal when the other bytes match, given that
// the hash keys are equal and that HASH_BITS >= 8.
scan += 2;
match++;
// We check for insufficient lookahead only every 8th comparison;
// the 256th check will be made at strstart+258.
do {
} while (window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match]
&& window[++scan] == window[++match] && scan < strend);
len = MAX_MATCH - (strend - scan);
scan = strend - MAX_MATCH;
if (len > best_len) {
match_start = cur_match;
best_len = len;
if (len >= nice_match)
break;
scan_end1 = window[scan + best_len - 1];
scan_end = window[scan + best_len];
}
} while ((cur_match = (prev[cur_match & wmask] & 0xffff)) > limit
&& --chain_length != 0);
if (best_len <= lookahead)
return best_len;
return lookahead;
}
// Restore the heap property by moving down the tree starting at node k,
// exchanging a node with the smallest of its two sons if necessary,
// stopping
// when the heap property is re-established (each father smaller than its
// two sons).
void pqdownheap(short[] tree, // the tree to restore
int k // node to move down
) {
int v = heap[k];
int j = k << 1; // left son of k
while (j <= heap_len) {
// Set j to the smallest of the two sons:
if (j < heap_len && smaller(tree, heap[j + 1], heap[j], depth)) {
j++;
}
// Exit if v is smaller than both sons
if (smaller(tree, v, heap[j], depth))
break;
// Exchange v with the smallest son
heap[k] = heap[j];
k = j;
// And continue down the tree, setting j to the left son of k
j <<= 1;
}
heap[k] = v;
}
final void put_byte(byte c) {
pending_buf[pending++] = c;
}
// Output a byte on the stream.
// IN assertion: there is enough room in pending_buf.
final void put_byte(byte[] p, int start, int len) {
System.arraycopy(p, start, pending_buf, pending, len);
pending += len;
}
final void put_short(int w) {
put_byte((byte) (w/* &0xff */));
put_byte((byte) (w >>> 8));
}
final void putShortMSB(int b) {
put_byte((byte) (b >> 8));
put_byte((byte) (b/* &0xff */));
}
// Scan a literal or distance tree to determine the frequencies of the codes
// in the bit length tree.
void scan_tree(short[] tree,// the tree to be scanned
int max_code // and its largest code of non zero frequency
) {
int n; // iterates over all tree elements
int prevlen = -1; // last emitted length
int curlen; // length of current code
int nextlen = tree[0 * 2 + 1]; // length of next code
int count = 0; // repeat count of the current code
int max_count = 7; // max repeat count
int min_count = 4; // min repeat count
if (nextlen == 0) {
max_count = 138;
min_count = 3;
}
tree[(max_code + 1) * 2 + 1] = (short) 0xffff; // guard
for (n = 0; n <= max_code; n++) {
curlen = nextlen;
nextlen = tree[(n + 1) * 2 + 1];
if (++count < max_count && curlen == nextlen) {
continue;
} else if (count < min_count) {
bl_tree[curlen * 2] += count;
} else if (curlen != 0) {
if (curlen != prevlen)
bl_tree[curlen * 2]++;
bl_tree[REP_3_6 * 2]++;
} else if (count <= 10) {
bl_tree[REPZ_3_10 * 2]++;
} else {
bl_tree[REPZ_11_138 * 2]++;
}
count = 0;
prevlen = curlen;
if (nextlen == 0) {
max_count = 138;
min_count = 3;
} else if (curlen == nextlen) {
max_count = 6;
min_count = 3;
} else {
max_count = 7;
min_count = 4;
}
}
}
// Send the header for a block using dynamic Huffman trees: the counts, the
// lengths of the bit length codes, the literal tree and the distance tree.
// IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
void send_all_trees(int lcodes, int dcodes, int blcodes) {
int rank; // index in bl_order
send_bits(lcodes - 257, 5); // not +255 as stated in appnote.txt
send_bits(dcodes - 1, 5);
send_bits(blcodes - 4, 4); // not -3 as stated in appnote.txt
for (rank = 0; rank < blcodes; rank++) {
send_bits(bl_tree[Tree.bl_order[rank] * 2 + 1], 3);
}
send_tree(dyn_ltree, lcodes - 1); // literal tree
send_tree(dyn_dtree, dcodes - 1); // distance tree
}
void send_bits(int value, int length) {
int len = length;
if (bi_valid > Buf_size - len) {
int val = value;
// bi_buf |= (val << bi_valid);
bi_buf |= ((val << bi_valid) & 0xffff);
put_short(bi_buf);
bi_buf = (short) (val >>> (Buf_size - bi_valid));
bi_valid += len - Buf_size;
} else {
// bi_buf |= (value) << bi_valid;
bi_buf |= (((value) << bi_valid) & 0xffff);
bi_valid += len;
}
}
final void send_code(int c, short[] tree) {
int c2 = c * 2;
send_bits((tree[c2] & 0xffff), (tree[c2 + 1] & 0xffff));
}
// Send a literal or distance tree in compressed form, using the codes in
// bl_tree.
void send_tree(short[] tree,// the tree to be sent
int max_code // and its largest code of non zero frequency
) {
int n; // iterates over all tree elements
int prevlen = -1; // last emitted length
int curlen; // length of current code
int nextlen = tree[0 * 2 + 1]; // length of next code
int count = 0; // repeat count of the current code
int max_count = 7; // max repeat count
int min_count = 4; // min repeat count
if (nextlen == 0) {
max_count = 138;
min_count = 3;
}
for (n = 0; n <= max_code; n++) {
curlen = nextlen;
nextlen = tree[(n + 1) * 2 + 1];
if (++count < max_count && curlen == nextlen) {
continue;
} else if (count < min_count) {
do {
send_code(curlen, bl_tree);
} while (--count != 0);
} else if (curlen != 0) {
if (curlen != prevlen) {
send_code(curlen, bl_tree);
count--;
}
send_code(REP_3_6, bl_tree);
send_bits(count - 3, 2);
} else if (count <= 10) {
send_code(REPZ_3_10, bl_tree);
send_bits(count - 3, 3);
} else {
send_code(REPZ_11_138, bl_tree);
send_bits(count - 11, 7);
}
count = 0;
prevlen = curlen;
if (nextlen == 0) {
max_count = 138;
min_count = 3;
} else if (curlen == nextlen) {
max_count = 6;
min_count = 3;
} else {
max_count = 7;
min_count = 4;
}
}
}
// Set the data type to ASCII or BINARY, using a crude approximation:
// binary if more than 20% of the bytes are <= 6 or >= 128, ascii otherwise.
// IN assertion: the fields freq of dyn_ltree are set and the total of all
// frequencies does not exceed 64K (to fit in an int on 16 bit machines).
void set_data_type() {
int n = 0;
int ascii_freq = 0;
int bin_freq = 0;
while (n < 7) {
bin_freq += dyn_ltree[n * 2];
n++;
}
while (n < 128) {
ascii_freq += dyn_ltree[n * 2];
n++;
}
while (n < LITERALS) {
bin_freq += dyn_ltree[n * 2];
n++;
}
data_type = (byte) (bin_freq > (ascii_freq >>> 2) ? Z_BINARY : Z_ASCII);
}
// Initialize the tree data structures for a new zlib stream.
void tr_init() {
l_desc.dyn_tree = dyn_ltree;
l_desc.stat_desc = StaticTree.static_l_desc;
d_desc.dyn_tree = dyn_dtree;
d_desc.stat_desc = StaticTree.static_d_desc;
bl_desc.dyn_tree = bl_tree;
bl_desc.stat_desc = StaticTree.static_bl_desc;
bi_buf = 0;
bi_valid = 0;
last_eob_len = 8; // enough lookahead for inflate
// Initialize the first block of the first file:
init_block();
}
}
| Java |
/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
/*
Copyright (c) 2001 Lapo Luchini.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. 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.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 AUTHORS
OR ANY CONTRIBUTORS TO THIS SOFTWARE 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.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
package com.jcraft.jzlib;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
public class ZInputStream extends FilterInputStream {
protected ZStream z = new ZStream();
protected int bufsize = 512;
protected int flush = JZlib.Z_NO_FLUSH;
protected byte[] buf = new byte[bufsize], buf1 = new byte[1];
protected boolean compress;
protected InputStream in = null;
private boolean nomoreinput = false;
public ZInputStream(InputStream in) {
this(in, false);
}
public ZInputStream(InputStream in, boolean nowrap) {
super(in);
this.in = in;
z.inflateInit(nowrap);
compress = false;
z.next_in = buf;
z.next_in_index = 0;
z.avail_in = 0;
}
/*
* public int available() throws IOException { return inf.finished() ? 0 :
* 1; }
*/
public ZInputStream(InputStream in, int level) {
super(in);
this.in = in;
z.deflateInit(level);
compress = true;
z.next_in = buf;
z.next_in_index = 0;
z.avail_in = 0;
}
@Override
public void close() throws IOException {
in.close();
}
public int getFlushMode() {
return (flush);
}
/**
* Returns the total number of bytes input so far.
*/
public long getTotalIn() {
return z.total_in;
}
/**
* Returns the total number of bytes output so far.
*/
public long getTotalOut() {
return z.total_out;
}
@Override
public int read() throws IOException {
if (read(buf1, 0, 1) == -1)
return (-1);
return (buf1[0] & 0xFF);
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
if (len == 0)
return (0);
int err;
z.next_out = b;
z.next_out_index = off;
z.avail_out = len;
do {
if ((z.avail_in == 0) && (!nomoreinput)) { // if buffer is empty and
// more input is
// avaiable, refill it
z.next_in_index = 0;
z.avail_in = in.read(buf, 0, bufsize);// (bufsize<z.avail_out ?
// bufsize :
// z.avail_out));
if (z.avail_in == -1) {
z.avail_in = 0;
nomoreinput = true;
}
}
if (compress)
err = z.deflate(flush);
else
err = z.inflate(flush);
if (nomoreinput && (err == JZlib.Z_BUF_ERROR))
return (-1);
if (err != JZlib.Z_OK && err != JZlib.Z_STREAM_END)
throw new ZStreamException((compress ? "de" : "in")
+ "flating: " + z.msg);
if ((nomoreinput || err == JZlib.Z_STREAM_END)
&& (z.avail_out == len))
return (-1);
} while (z.avail_out == len && err == JZlib.Z_OK);
// System.err.print("("+(len-z.avail_out)+")");
return (len - z.avail_out);
}
public void setFlushMode(int flush) {
this.flush = flush;
}
@Override
public long skip(long n) throws IOException {
int len = 512;
if (n < len)
len = (int) n;
byte[] tmp = new byte[len];
return read(tmp);
}
}
| Java |
/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
/*
Copyright (c) 2001 Lapo Luchini.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. 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.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 AUTHORS
OR ANY CONTRIBUTORS TO THIS SOFTWARE 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.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
package com.jcraft.jzlib;
import java.io.IOException;
import java.io.OutputStream;
public class ZOutputStream extends OutputStream {
protected ZStream z = new ZStream();
protected int bufsize = 512;
protected int flush = JZlib.Z_NO_FLUSH;
protected byte[] buf = new byte[bufsize], buf1 = new byte[1];
protected boolean compress;
protected OutputStream out;
public ZOutputStream(OutputStream out) {
super();
this.out = out;
z.inflateInit();
compress = false;
}
public ZOutputStream(OutputStream out, int level) {
this(out, level, false);
}
public ZOutputStream(OutputStream out, int level, boolean nowrap) {
super();
this.out = out;
z.deflateInit(level, nowrap);
compress = true;
}
@Override
public void close() throws IOException {
try {
try {
finish();
} catch (IOException ignored) {
}
} finally {
end();
out.close();
out = null;
}
}
public void end() {
if (z == null)
return;
if (compress) {
z.deflateEnd();
} else {
z.inflateEnd();
}
z.free();
z = null;
}
public void finish() throws IOException {
int err;
do {
z.next_out = buf;
z.next_out_index = 0;
z.avail_out = bufsize;
if (compress) {
err = z.deflate(JZlib.Z_FINISH);
} else {
err = z.inflate(JZlib.Z_FINISH);
}
if (err != JZlib.Z_STREAM_END && err != JZlib.Z_OK)
throw new ZStreamException((compress ? "de" : "in")
+ "flating: " + z.msg);
if (bufsize - z.avail_out > 0) {
out.write(buf, 0, bufsize - z.avail_out);
}
} while (z.avail_in > 0 || z.avail_out == 0);
flush();
}
@Override
public void flush() throws IOException {
out.flush();
}
public int getFlushMode() {
return (flush);
}
/**
* Returns the total number of bytes input so far.
*/
public long getTotalIn() {
return z.total_in;
}
/**
* Returns the total number of bytes output so far.
*/
public long getTotalOut() {
return z.total_out;
}
public void setFlushMode(int flush) {
this.flush = flush;
}
@Override
public void write(byte b[], int off, int len) throws IOException {
if (len == 0)
return;
int err;
z.next_in = b;
z.next_in_index = off;
z.avail_in = len;
do {
z.next_out = buf;
z.next_out_index = 0;
z.avail_out = bufsize;
if (compress)
err = z.deflate(flush);
else
err = z.inflate(flush);
if (err != JZlib.Z_OK)
throw new ZStreamException((compress ? "de" : "in")
+ "flating: " + z.msg);
out.write(buf, 0, bufsize - z.avail_out);
} while (z.avail_in > 0 || z.avail_out == 0);
}
@Override
public void write(int b) throws IOException {
buf1[0] = (byte) b;
write(buf1, 0, 1);
}
}
| Java |
/* -*-mode:java; c-basic-offset:2; -*- */
/*
Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,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:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. 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.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
package com.jcraft.jzlib;
final class Inflate {
static final private int MAX_WBITS = 15; // 32K LZ77 window
// preset dictionary flag in zlib header
static final private int PRESET_DICT = 0x20;
static final int Z_NO_FLUSH = 0;
static final int Z_PARTIAL_FLUSH = 1;
static final int Z_SYNC_FLUSH = 2;
static final int Z_FULL_FLUSH = 3;
static final int Z_FINISH = 4;
static final private int Z_DEFLATED = 8;
static final private int Z_OK = 0;
static final private int Z_STREAM_END = 1;
static final private int Z_NEED_DICT = 2;
static final private int Z_ERRNO = -1;
static final private int Z_STREAM_ERROR = -2;
static final private int Z_DATA_ERROR = -3;
static final private int Z_MEM_ERROR = -4;
static final private int Z_BUF_ERROR = -5;
static final private int Z_VERSION_ERROR = -6;
static final private int METHOD = 0; // waiting for method byte
static final private int FLAG = 1; // waiting for flag byte
static final private int DICT4 = 2; // four dictionary check bytes to go
static final private int DICT3 = 3; // three dictionary check bytes to go
static final private int DICT2 = 4; // two dictionary check bytes to go
static final private int DICT1 = 5; // one dictionary check byte to go
static final private int DICT0 = 6; // waiting for inflateSetDictionary
static final private int BLOCKS = 7; // decompressing blocks
static final private int CHECK4 = 8; // four check bytes to go
static final private int CHECK3 = 9; // three check bytes to go
static final private int CHECK2 = 10; // two check bytes to go
static final private int CHECK1 = 11; // one check byte to go
static final private int DONE = 12; // finished check, done
static final private int BAD = 13; // got an error--stay here
int mode; // current inflate mode
// mode dependent information
int method; // if FLAGS, method byte
// if CHECK, check values to compare
long[] was = new long[1]; // computed check value
long need; // stream check value
// if BAD, inflateSync's marker bytes count
int marker;
// mode independent information
int nowrap; // flag for no wrapper
int wbits; // log2(window size) (8..15, defaults to 15)
InfBlocks blocks; // current inflate_blocks state
static private byte[] mark = { (byte) 0, (byte) 0, (byte) 0xff, (byte) 0xff };
int inflate(ZStream z, int f) {
int r;
int b;
if (z == null || z.istate == null || z.next_in == null)
return Z_STREAM_ERROR;
f = f == Z_FINISH ? Z_BUF_ERROR : Z_OK;
r = Z_BUF_ERROR;
while (true) {
// System.out.println("mode: "+z.istate.mode);
switch (z.istate.mode) {
case METHOD:
if (z.avail_in == 0)
return r;
r = f;
z.avail_in--;
z.total_in++;
if (((z.istate.method = z.next_in[z.next_in_index++]) & 0xf) != Z_DEFLATED) {
z.istate.mode = BAD;
z.msg = "unknown compression method";
z.istate.marker = 5; // can't try inflateSync
break;
}
if ((z.istate.method >> 4) + 8 > z.istate.wbits) {
z.istate.mode = BAD;
z.msg = "invalid window size";
z.istate.marker = 5; // can't try inflateSync
break;
}
z.istate.mode = FLAG;
case FLAG:
if (z.avail_in == 0)
return r;
r = f;
z.avail_in--;
z.total_in++;
b = (z.next_in[z.next_in_index++]) & 0xff;
if ((((z.istate.method << 8) + b) % 31) != 0) {
z.istate.mode = BAD;
z.msg = "incorrect header check";
z.istate.marker = 5; // can't try inflateSync
break;
}
if ((b & PRESET_DICT) == 0) {
z.istate.mode = BLOCKS;
break;
}
z.istate.mode = DICT4;
case DICT4:
if (z.avail_in == 0)
return r;
r = f;
z.avail_in--;
z.total_in++;
z.istate.need = ((z.next_in[z.next_in_index++] & 0xff) << 24) & 0xff000000L;
z.istate.mode = DICT3;
case DICT3:
if (z.avail_in == 0)
return r;
r = f;
z.avail_in--;
z.total_in++;
z.istate.need += ((z.next_in[z.next_in_index++] & 0xff) << 16) & 0xff0000L;
z.istate.mode = DICT2;
case DICT2:
if (z.avail_in == 0)
return r;
r = f;
z.avail_in--;
z.total_in++;
z.istate.need += ((z.next_in[z.next_in_index++] & 0xff) << 8) & 0xff00L;
z.istate.mode = DICT1;
case DICT1:
if (z.avail_in == 0)
return r;
r = f;
z.avail_in--;
z.total_in++;
z.istate.need += (z.next_in[z.next_in_index++] & 0xffL);
z.adler = z.istate.need;
z.istate.mode = DICT0;
return Z_NEED_DICT;
case DICT0:
z.istate.mode = BAD;
z.msg = "need dictionary";
z.istate.marker = 0; // can try inflateSync
return Z_STREAM_ERROR;
case BLOCKS:
r = z.istate.blocks.proc(z, r);
if (r == Z_DATA_ERROR) {
z.istate.mode = BAD;
z.istate.marker = 0; // can try inflateSync
break;
}
if (r == Z_OK) {
r = f;
}
if (r != Z_STREAM_END) {
return r;
}
r = f;
z.istate.blocks.reset(z, z.istate.was);
if (z.istate.nowrap != 0) {
z.istate.mode = DONE;
break;
}
z.istate.mode = CHECK4;
case CHECK4:
if (z.avail_in == 0)
return r;
r = f;
z.avail_in--;
z.total_in++;
z.istate.need = ((z.next_in[z.next_in_index++] & 0xff) << 24) & 0xff000000L;
z.istate.mode = CHECK3;
case CHECK3:
if (z.avail_in == 0)
return r;
r = f;
z.avail_in--;
z.total_in++;
z.istate.need += ((z.next_in[z.next_in_index++] & 0xff) << 16) & 0xff0000L;
z.istate.mode = CHECK2;
case CHECK2:
if (z.avail_in == 0)
return r;
r = f;
z.avail_in--;
z.total_in++;
z.istate.need += ((z.next_in[z.next_in_index++] & 0xff) << 8) & 0xff00L;
z.istate.mode = CHECK1;
case CHECK1:
if (z.avail_in == 0)
return r;
r = f;
z.avail_in--;
z.total_in++;
z.istate.need += (z.next_in[z.next_in_index++] & 0xffL);
if (((int) (z.istate.was[0])) != ((int) (z.istate.need))) {
z.istate.mode = BAD;
z.msg = "incorrect data check";
z.istate.marker = 5; // can't try inflateSync
break;
}
z.istate.mode = DONE;
case DONE:
return Z_STREAM_END;
case BAD:
return Z_DATA_ERROR;
default:
return Z_STREAM_ERROR;
}
}
}
int inflateEnd(ZStream z) {
if (blocks != null)
blocks.free(z);
blocks = null;
// ZFREE(z, z->state);
return Z_OK;
}
int inflateInit(ZStream z, int w) {
z.msg = null;
blocks = null;
// handle undocumented nowrap option (no zlib header or check)
nowrap = 0;
if (w < 0) {
w = -w;
nowrap = 1;
}
// set window size
if (w < 8 || w > 15) {
inflateEnd(z);
return Z_STREAM_ERROR;
}
wbits = w;
z.istate.blocks = new InfBlocks(z, z.istate.nowrap != 0 ? null : this,
1 << w);
// reset state
inflateReset(z);
return Z_OK;
}
int inflateReset(ZStream z) {
if (z == null || z.istate == null)
return Z_STREAM_ERROR;
z.total_in = z.total_out = 0;
z.msg = null;
z.istate.mode = z.istate.nowrap != 0 ? BLOCKS : METHOD;
z.istate.blocks.reset(z, null);
return Z_OK;
}
int inflateSetDictionary(ZStream z, byte[] dictionary, int dictLength) {
int index = 0;
int length = dictLength;
if (z == null || z.istate == null || z.istate.mode != DICT0)
return Z_STREAM_ERROR;
if (z._adler.adler32(1L, dictionary, 0, dictLength) != z.adler) {
return Z_DATA_ERROR;
}
z.adler = z._adler.adler32(0, null, 0, 0);
if (length >= (1 << z.istate.wbits)) {
length = (1 << z.istate.wbits) - 1;
index = dictLength - length;
}
z.istate.blocks.set_dictionary(dictionary, index, length);
z.istate.mode = BLOCKS;
return Z_OK;
}
int inflateSync(ZStream z) {
int n; // number of bytes to look at
int p; // pointer to bytes
int m; // number of marker bytes found in a row
long r, w; // temporaries to save total_in and total_out
// set up
if (z == null || z.istate == null)
return Z_STREAM_ERROR;
if (z.istate.mode != BAD) {
z.istate.mode = BAD;
z.istate.marker = 0;
}
if ((n = z.avail_in) == 0)
return Z_BUF_ERROR;
p = z.next_in_index;
m = z.istate.marker;
// search
while (n != 0 && m < 4) {
if (z.next_in[p] == mark[m]) {
m++;
} else if (z.next_in[p] != 0) {
m = 0;
} else {
m = 4 - m;
}
p++;
n--;
}
// restore
z.total_in += p - z.next_in_index;
z.next_in_index = p;
z.avail_in = n;
z.istate.marker = m;
// return no joy or set up to restart on a new block
if (m != 4) {
return Z_DATA_ERROR;
}
r = z.total_in;
w = z.total_out;
inflateReset(z);
z.total_in = r;
z.total_out = w;
z.istate.mode = BLOCKS;
return Z_OK;
}
// Returns true if inflate is currently at the end of a block generated
// by Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
// implementation to provide an additional safety check. PPP uses
// Z_SYNC_FLUSH
// but removes the length bytes of the resulting empty stored block. When
// decompressing, PPP checks that at the end of input packet, inflate is
// waiting for these length bytes.
int inflateSyncPoint(ZStream z) {
if (z == null || z.istate == null || z.istate.blocks == null)
return Z_STREAM_ERROR;
return z.istate.blocks.sync_point();
}
}
| Java |
/* -*-mode:java; c-basic-offset:2; -*- */
/*
Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,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:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. 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.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
package com.jcraft.jzlib;
final class InfCodes {
static final private int[] inflate_mask = { 0x00000000, 0x00000001,
0x00000003, 0x00000007, 0x0000000f, 0x0000001f, 0x0000003f,
0x0000007f, 0x000000ff, 0x000001ff, 0x000003ff, 0x000007ff,
0x00000fff, 0x00001fff, 0x00003fff, 0x00007fff, 0x0000ffff };
static final private int Z_OK = 0;
static final private int Z_STREAM_END = 1;
static final private int Z_NEED_DICT = 2;
static final private int Z_ERRNO = -1;
static final private int Z_STREAM_ERROR = -2;
static final private int Z_DATA_ERROR = -3;
static final private int Z_MEM_ERROR = -4;
static final private int Z_BUF_ERROR = -5;
static final private int Z_VERSION_ERROR = -6;
// waiting for "i:"=input,
// "o:"=output,
// "x:"=nothing
static final private int START = 0; // x: set up for LEN
static final private int LEN = 1; // i: get length/literal/eob next
static final private int LENEXT = 2; // i: getting length extra (have base)
static final private int DIST = 3; // i: get distance next
static final private int DISTEXT = 4;// i: getting distance extra
static final private int COPY = 5; // o: copying bytes in window, waiting
// for space
static final private int LIT = 6; // o: got literal, waiting for output
// space
static final private int WASH = 7; // o: got eob, possibly still output
// waiting
static final private int END = 8; // x: got eob and all data flushed
static final private int BADCODE = 9;// x: got error
int mode; // current inflate_codes mode
// mode dependent information
int len;
int[] tree; // pointer into tree
int tree_index = 0;
int need; // bits needed
int lit;
// if EXT or COPY, where and how much
int get; // bits to get for extra
int dist; // distance back to copy from
byte lbits; // ltree bits decoded per branch
byte dbits; // dtree bits decoder per branch
int[] ltree; // literal/length/eob tree
int ltree_index; // literal/length/eob tree
int[] dtree; // distance tree
int dtree_index; // distance tree
InfCodes() {
}
void free(ZStream z) {
// ZFREE(z, c);
}
int inflate_fast(int bl, int bd, int[] tl, int tl_index, int[] td,
int td_index, InfBlocks s, ZStream z) {
int t; // temporary pointer
int[] tp; // temporary pointer
int tp_index; // temporary pointer
int e; // extra bits or operation
int b; // bit buffer
int k; // bits in bit buffer
int p; // input data pointer
int n; // bytes available there
int q; // output window write pointer
int m; // bytes to end of window or read pointer
int ml; // mask for literal/length tree
int md; // mask for distance tree
int c; // bytes to copy
int d; // distance back to copy from
int r; // copy source pointer
int tp_index_t_3; // (tp_index+t)*3
// load input, output, bit values
p = z.next_in_index;
n = z.avail_in;
b = s.bitb;
k = s.bitk;
q = s.write;
m = q < s.read ? s.read - q - 1 : s.end - q;
// initialize masks
ml = inflate_mask[bl];
md = inflate_mask[bd];
// do until not enough input or output space for fast loop
do { // assume called with m >= 258 && n >= 10
// get literal/length code
while (k < (20)) { // max bits for literal/length code
n--;
b |= (z.next_in[p++] & 0xff) << k;
k += 8;
}
t = b & ml;
tp = tl;
tp_index = tl_index;
tp_index_t_3 = (tp_index + t) * 3;
if ((e = tp[tp_index_t_3]) == 0) {
b >>= (tp[tp_index_t_3 + 1]);
k -= (tp[tp_index_t_3 + 1]);
s.window[q++] = (byte) tp[tp_index_t_3 + 2];
m--;
continue;
}
do {
b >>= (tp[tp_index_t_3 + 1]);
k -= (tp[tp_index_t_3 + 1]);
if ((e & 16) != 0) {
e &= 15;
c = tp[tp_index_t_3 + 2] + (b & inflate_mask[e]);
b >>= e;
k -= e;
// decode distance base of block to copy
while (k < (15)) { // max bits for distance code
n--;
b |= (z.next_in[p++] & 0xff) << k;
k += 8;
}
t = b & md;
tp = td;
tp_index = td_index;
tp_index_t_3 = (tp_index + t) * 3;
e = tp[tp_index_t_3];
do {
b >>= (tp[tp_index_t_3 + 1]);
k -= (tp[tp_index_t_3 + 1]);
if ((e & 16) != 0) {
// get extra bits to add to distance base
e &= 15;
while (k < (e)) { // get extra bits (up to 13)
n--;
b |= (z.next_in[p++] & 0xff) << k;
k += 8;
}
d = tp[tp_index_t_3 + 2] + (b & inflate_mask[e]);
b >>= (e);
k -= (e);
// do the copy
m -= c;
if (q >= d) { // offset before dest
// just copy
r = q - d;
if (q - r > 0 && 2 > (q - r)) {
s.window[q++] = s.window[r++]; // minimum
// count is
// three,
s.window[q++] = s.window[r++]; // so unroll
// loop a
// little
c -= 2;
} else {
System.arraycopy(s.window, r, s.window, q,
2);
q += 2;
r += 2;
c -= 2;
}
} else { // else offset after destination
r = q - d;
do {
r += s.end; // force pointer in window
} while (r < 0); // covers invalid distances
e = s.end - r;
if (c > e) { // if source crosses,
c -= e; // wrapped copy
if (q - r > 0 && e > (q - r)) {
do {
s.window[q++] = s.window[r++];
} while (--e != 0);
} else {
System.arraycopy(s.window, r, s.window,
q, e);
q += e;
r += e;
e = 0;
}
r = 0; // copy rest from start of window
}
}
// copy all or what's left
if (q - r > 0 && c > (q - r)) {
do {
s.window[q++] = s.window[r++];
} while (--c != 0);
} else {
System.arraycopy(s.window, r, s.window, q, c);
q += c;
r += c;
c = 0;
}
break;
} else if ((e & 64) == 0) {
t += tp[tp_index_t_3 + 2];
t += (b & inflate_mask[e]);
tp_index_t_3 = (tp_index + t) * 3;
e = tp[tp_index_t_3];
} else {
z.msg = "invalid distance code";
c = z.avail_in - n;
c = (k >> 3) < c ? k >> 3 : c;
n += c;
p -= c;
k -= c << 3;
s.bitb = b;
s.bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
s.write = q;
return Z_DATA_ERROR;
}
} while (true);
break;
}
if ((e & 64) == 0) {
t += tp[tp_index_t_3 + 2];
t += (b & inflate_mask[e]);
tp_index_t_3 = (tp_index + t) * 3;
if ((e = tp[tp_index_t_3]) == 0) {
b >>= (tp[tp_index_t_3 + 1]);
k -= (tp[tp_index_t_3 + 1]);
s.window[q++] = (byte) tp[tp_index_t_3 + 2];
m--;
break;
}
} else if ((e & 32) != 0) {
c = z.avail_in - n;
c = (k >> 3) < c ? k >> 3 : c;
n += c;
p -= c;
k -= c << 3;
s.bitb = b;
s.bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
s.write = q;
return Z_STREAM_END;
} else {
z.msg = "invalid literal/length code";
c = z.avail_in - n;
c = (k >> 3) < c ? k >> 3 : c;
n += c;
p -= c;
k -= c << 3;
s.bitb = b;
s.bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
s.write = q;
return Z_DATA_ERROR;
}
} while (true);
} while (m >= 258 && n >= 10);
// not enough input or output--restore pointers and return
c = z.avail_in - n;
c = (k >> 3) < c ? k >> 3 : c;
n += c;
p -= c;
k -= c << 3;
s.bitb = b;
s.bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
s.write = q;
return Z_OK;
}
void init(int bl, int bd, int[] tl, int tl_index, int[] td, int td_index,
ZStream z) {
mode = START;
lbits = (byte) bl;
dbits = (byte) bd;
ltree = tl;
ltree_index = tl_index;
dtree = td;
dtree_index = td_index;
tree = null;
}
// Called with number of bytes left to write in window at least 258
// (the maximum string length) and number of input bytes available
// at least ten. The ten bytes are six bytes for the longest length/
// distance pair plus four bytes for overloading the bit buffer.
int proc(InfBlocks s, ZStream z, int r) {
int j; // temporary storage
int[] t; // temporary pointer
int tindex; // temporary pointer
int e; // extra bits or operation
int b = 0; // bit buffer
int k = 0; // bits in bit buffer
int p = 0; // input data pointer
int n; // bytes available there
int q; // output window write pointer
int m; // bytes to end of window or read pointer
int f; // pointer to copy strings from
// copy input/output information to locals (UPDATE macro restores)
p = z.next_in_index;
n = z.avail_in;
b = s.bitb;
k = s.bitk;
q = s.write;
m = q < s.read ? s.read - q - 1 : s.end - q;
// process input and output based on current state
while (true) {
switch (mode) {
// waiting for "i:"=input, "o:"=output, "x:"=nothing
case START: // x: set up for LEN
if (m >= 258 && n >= 10) {
s.bitb = b;
s.bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
s.write = q;
r = inflate_fast(lbits, dbits, ltree, ltree_index, dtree,
dtree_index, s, z);
p = z.next_in_index;
n = z.avail_in;
b = s.bitb;
k = s.bitk;
q = s.write;
m = q < s.read ? s.read - q - 1 : s.end - q;
if (r != Z_OK) {
mode = r == Z_STREAM_END ? WASH : BADCODE;
break;
}
}
need = lbits;
tree = ltree;
tree_index = ltree_index;
mode = LEN;
case LEN: // i: get length/literal/eob next
j = need;
while (k < (j)) {
if (n != 0)
r = Z_OK;
else {
s.bitb = b;
s.bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
s.write = q;
return s.inflate_flush(z, r);
}
n--;
b |= (z.next_in[p++] & 0xff) << k;
k += 8;
}
tindex = (tree_index + (b & inflate_mask[j])) * 3;
b >>>= (tree[tindex + 1]);
k -= (tree[tindex + 1]);
e = tree[tindex];
if (e == 0) { // literal
lit = tree[tindex + 2];
mode = LIT;
break;
}
if ((e & 16) != 0) { // length
get = e & 15;
len = tree[tindex + 2];
mode = LENEXT;
break;
}
if ((e & 64) == 0) { // next table
need = e;
tree_index = tindex / 3 + tree[tindex + 2];
break;
}
if ((e & 32) != 0) { // end of block
mode = WASH;
break;
}
mode = BADCODE; // invalid code
z.msg = "invalid literal/length code";
r = Z_DATA_ERROR;
s.bitb = b;
s.bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
s.write = q;
return s.inflate_flush(z, r);
case LENEXT: // i: getting length extra (have base)
j = get;
while (k < (j)) {
if (n != 0)
r = Z_OK;
else {
s.bitb = b;
s.bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
s.write = q;
return s.inflate_flush(z, r);
}
n--;
b |= (z.next_in[p++] & 0xff) << k;
k += 8;
}
len += (b & inflate_mask[j]);
b >>= j;
k -= j;
need = dbits;
tree = dtree;
tree_index = dtree_index;
mode = DIST;
case DIST: // i: get distance next
j = need;
while (k < (j)) {
if (n != 0)
r = Z_OK;
else {
s.bitb = b;
s.bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
s.write = q;
return s.inflate_flush(z, r);
}
n--;
b |= (z.next_in[p++] & 0xff) << k;
k += 8;
}
tindex = (tree_index + (b & inflate_mask[j])) * 3;
b >>= tree[tindex + 1];
k -= tree[tindex + 1];
e = (tree[tindex]);
if ((e & 16) != 0) { // distance
get = e & 15;
dist = tree[tindex + 2];
mode = DISTEXT;
break;
}
if ((e & 64) == 0) { // next table
need = e;
tree_index = tindex / 3 + tree[tindex + 2];
break;
}
mode = BADCODE; // invalid code
z.msg = "invalid distance code";
r = Z_DATA_ERROR;
s.bitb = b;
s.bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
s.write = q;
return s.inflate_flush(z, r);
case DISTEXT: // i: getting distance extra
j = get;
while (k < (j)) {
if (n != 0)
r = Z_OK;
else {
s.bitb = b;
s.bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
s.write = q;
return s.inflate_flush(z, r);
}
n--;
b |= (z.next_in[p++] & 0xff) << k;
k += 8;
}
dist += (b & inflate_mask[j]);
b >>= j;
k -= j;
mode = COPY;
case COPY: // o: copying bytes in window, waiting for space
f = q - dist;
while (f < 0) { // modulo window size-"while" instead
f += s.end; // of "if" handles invalid distances
}
while (len != 0) {
if (m == 0) {
if (q == s.end && s.read != 0) {
q = 0;
m = q < s.read ? s.read - q - 1 : s.end - q;
}
if (m == 0) {
s.write = q;
r = s.inflate_flush(z, r);
q = s.write;
m = q < s.read ? s.read - q - 1 : s.end - q;
if (q == s.end && s.read != 0) {
q = 0;
m = q < s.read ? s.read - q - 1 : s.end - q;
}
if (m == 0) {
s.bitb = b;
s.bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
s.write = q;
return s.inflate_flush(z, r);
}
}
}
s.window[q++] = s.window[f++];
m--;
if (f == s.end)
f = 0;
len--;
}
mode = START;
break;
case LIT: // o: got literal, waiting for output space
if (m == 0) {
if (q == s.end && s.read != 0) {
q = 0;
m = q < s.read ? s.read - q - 1 : s.end - q;
}
if (m == 0) {
s.write = q;
r = s.inflate_flush(z, r);
q = s.write;
m = q < s.read ? s.read - q - 1 : s.end - q;
if (q == s.end && s.read != 0) {
q = 0;
m = q < s.read ? s.read - q - 1 : s.end - q;
}
if (m == 0) {
s.bitb = b;
s.bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
s.write = q;
return s.inflate_flush(z, r);
}
}
}
r = Z_OK;
s.window[q++] = (byte) lit;
m--;
mode = START;
break;
case WASH: // o: got eob, possibly more output
if (k > 7) { // return unused byte, if any
k -= 8;
n++;
p--; // can always return one
}
s.write = q;
r = s.inflate_flush(z, r);
q = s.write;
m = q < s.read ? s.read - q - 1 : s.end - q;
if (s.read != s.write) {
s.bitb = b;
s.bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
s.write = q;
return s.inflate_flush(z, r);
}
mode = END;
case END:
r = Z_STREAM_END;
s.bitb = b;
s.bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
s.write = q;
return s.inflate_flush(z, r);
case BADCODE: // x: got error
r = Z_DATA_ERROR;
s.bitb = b;
s.bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
s.write = q;
return s.inflate_flush(z, r);
default:
r = Z_STREAM_ERROR;
s.bitb = b;
s.bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
s.write = q;
return s.inflate_flush(z, r);
}
}
}
}
| Java |
/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
/*
Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,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:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. 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.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
package com.jcraft.jzlib;
final public class ZStream {
static final private int MAX_WBITS = 15; // 32K LZ77 window
static final private int DEF_WBITS = MAX_WBITS;
static final private int Z_NO_FLUSH = 0;
static final private int Z_PARTIAL_FLUSH = 1;
static final private int Z_SYNC_FLUSH = 2;
static final private int Z_FULL_FLUSH = 3;
static final private int Z_FINISH = 4;
static final private int MAX_MEM_LEVEL = 9;
static final private int Z_OK = 0;
static final private int Z_STREAM_END = 1;
static final private int Z_NEED_DICT = 2;
static final private int Z_ERRNO = -1;
static final private int Z_STREAM_ERROR = -2;
static final private int Z_DATA_ERROR = -3;
static final private int Z_MEM_ERROR = -4;
static final private int Z_BUF_ERROR = -5;
static final private int Z_VERSION_ERROR = -6;
public byte[] next_in; // next input byte
public int next_in_index;
public int avail_in; // number of bytes available at next_in
public long total_in; // total nb of input bytes read so far
public byte[] next_out; // next output byte should be put there
public int next_out_index;
public int avail_out; // remaining free space at next_out
public long total_out; // total nb of bytes output so far
public String msg;
Deflate dstate;
Inflate istate;
int data_type; // best guess about the data type: ascii or binary
public long adler;
Adler32 _adler = new Adler32();
public int deflate(int flush) {
if (dstate == null) {
return Z_STREAM_ERROR;
}
return dstate.deflate(this, flush);
}
public int deflateEnd() {
if (dstate == null)
return Z_STREAM_ERROR;
int ret = dstate.deflateEnd();
dstate = null;
return ret;
}
public int deflateInit(int level) {
return deflateInit(level, MAX_WBITS);
}
public int deflateInit(int level, boolean nowrap) {
return deflateInit(level, MAX_WBITS, nowrap);
}
public int deflateInit(int level, int bits) {
return deflateInit(level, bits, false);
}
public int deflateInit(int level, int bits, boolean nowrap) {
dstate = new Deflate();
return dstate.deflateInit(this, level, nowrap ? -bits : bits);
}
public int deflateParams(int level, int strategy) {
if (dstate == null)
return Z_STREAM_ERROR;
return dstate.deflateParams(this, level, strategy);
}
public int deflateSetDictionary(byte[] dictionary, int dictLength) {
if (dstate == null)
return Z_STREAM_ERROR;
return dstate.deflateSetDictionary(this, dictionary, dictLength);
}
// Flush as much pending output as possible. All deflate() output goes
// through this function so some applications may wish to modify it
// to avoid allocating a large strm->next_out buffer and copying into it.
// (See also read_buf()).
void flush_pending() {
int len = dstate.pending;
if (len > avail_out)
len = avail_out;
if (len == 0)
return;
if (dstate.pending_buf.length <= dstate.pending_out
|| next_out.length <= next_out_index
|| dstate.pending_buf.length < (dstate.pending_out + len)
|| next_out.length < (next_out_index + len)) {
System.out.println(dstate.pending_buf.length + ", "
+ dstate.pending_out + ", " + next_out.length + ", "
+ next_out_index + ", " + len);
System.out.println("avail_out=" + avail_out);
}
System.arraycopy(dstate.pending_buf, dstate.pending_out, next_out,
next_out_index, len);
next_out_index += len;
dstate.pending_out += len;
total_out += len;
avail_out -= len;
dstate.pending -= len;
if (dstate.pending == 0) {
dstate.pending_out = 0;
}
}
public void free() {
next_in = null;
next_out = null;
msg = null;
_adler = null;
}
public int inflate(int f) {
if (istate == null)
return Z_STREAM_ERROR;
return istate.inflate(this, f);
}
public int inflateEnd() {
if (istate == null)
return Z_STREAM_ERROR;
int ret = istate.inflateEnd(this);
istate = null;
return ret;
}
public int inflateInit() {
return inflateInit(DEF_WBITS);
}
public int inflateInit(boolean nowrap) {
return inflateInit(DEF_WBITS, nowrap);
}
public int inflateInit(int w) {
return inflateInit(w, false);
}
public int inflateInit(int w, boolean nowrap) {
istate = new Inflate();
return istate.inflateInit(this, nowrap ? -w : w);
}
public int inflateSetDictionary(byte[] dictionary, int dictLength) {
if (istate == null)
return Z_STREAM_ERROR;
return istate.inflateSetDictionary(this, dictionary, dictLength);
}
public int inflateSync() {
if (istate == null)
return Z_STREAM_ERROR;
return istate.inflateSync(this);
}
// Read a new buffer from the current input stream, update the adler32
// and total number of bytes read. All deflate() input goes through
// this function so some applications may wish to modify it to avoid
// allocating a large strm->next_in buffer and copying from it.
// (See also flush_pending()).
int read_buf(byte[] buf, int start, int size) {
int len = avail_in;
if (len > size)
len = size;
if (len == 0)
return 0;
avail_in -= len;
if (dstate.noheader == 0) {
adler = _adler.adler32(adler, next_in, next_in_index, len);
}
System.arraycopy(next_in, next_in_index, buf, start, len);
next_in_index += len;
total_in += len;
return len;
}
}
| Java |
/* -*-mode:java; c-basic-offset:2; indent-tabs-mode:nil -*- */
/*
Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,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:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. 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.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
package com.jcraft.jzlib;
final class InfTree {
static final private int MANY = 1440;
static final private int Z_OK = 0;
static final private int Z_STREAM_END = 1;
static final private int Z_NEED_DICT = 2;
static final private int Z_ERRNO = -1;
static final private int Z_STREAM_ERROR = -2;
static final private int Z_DATA_ERROR = -3;
static final private int Z_MEM_ERROR = -4;
static final private int Z_BUF_ERROR = -5;
static final private int Z_VERSION_ERROR = -6;
static final int fixed_bl = 9;
static final int fixed_bd = 5;
static final int[] fixed_tl = { 96, 7, 256, 0, 8, 80, 0, 8, 16, 84, 8, 115,
82, 7, 31, 0, 8, 112, 0, 8, 48, 0, 9, 192, 80, 7, 10, 0, 8, 96, 0,
8, 32, 0, 9, 160, 0, 8, 0, 0, 8, 128, 0, 8, 64, 0, 9, 224, 80, 7,
6, 0, 8, 88, 0, 8, 24, 0, 9, 144, 83, 7, 59, 0, 8, 120, 0, 8, 56,
0, 9, 208, 81, 7, 17, 0, 8, 104, 0, 8, 40, 0, 9, 176, 0, 8, 8, 0,
8, 136, 0, 8, 72, 0, 9, 240, 80, 7, 4, 0, 8, 84, 0, 8, 20, 85, 8,
227, 83, 7, 43, 0, 8, 116, 0, 8, 52, 0, 9, 200, 81, 7, 13, 0, 8,
100, 0, 8, 36, 0, 9, 168, 0, 8, 4, 0, 8, 132, 0, 8, 68, 0, 9, 232,
80, 7, 8, 0, 8, 92, 0, 8, 28, 0, 9, 152, 84, 7, 83, 0, 8, 124, 0,
8, 60, 0, 9, 216, 82, 7, 23, 0, 8, 108, 0, 8, 44, 0, 9, 184, 0, 8,
12, 0, 8, 140, 0, 8, 76, 0, 9, 248, 80, 7, 3, 0, 8, 82, 0, 8, 18,
85, 8, 163, 83, 7, 35, 0, 8, 114, 0, 8, 50, 0, 9, 196, 81, 7, 11,
0, 8, 98, 0, 8, 34, 0, 9, 164, 0, 8, 2, 0, 8, 130, 0, 8, 66, 0, 9,
228, 80, 7, 7, 0, 8, 90, 0, 8, 26, 0, 9, 148, 84, 7, 67, 0, 8, 122,
0, 8, 58, 0, 9, 212, 82, 7, 19, 0, 8, 106, 0, 8, 42, 0, 9, 180, 0,
8, 10, 0, 8, 138, 0, 8, 74, 0, 9, 244, 80, 7, 5, 0, 8, 86, 0, 8,
22, 192, 8, 0, 83, 7, 51, 0, 8, 118, 0, 8, 54, 0, 9, 204, 81, 7,
15, 0, 8, 102, 0, 8, 38, 0, 9, 172, 0, 8, 6, 0, 8, 134, 0, 8, 70,
0, 9, 236, 80, 7, 9, 0, 8, 94, 0, 8, 30, 0, 9, 156, 84, 7, 99, 0,
8, 126, 0, 8, 62, 0, 9, 220, 82, 7, 27, 0, 8, 110, 0, 8, 46, 0, 9,
188, 0, 8, 14, 0, 8, 142, 0, 8, 78, 0, 9, 252, 96, 7, 256, 0, 8,
81, 0, 8, 17, 85, 8, 131, 82, 7, 31, 0, 8, 113, 0, 8, 49, 0, 9,
194, 80, 7, 10, 0, 8, 97, 0, 8, 33, 0, 9, 162, 0, 8, 1, 0, 8, 129,
0, 8, 65, 0, 9, 226, 80, 7, 6, 0, 8, 89, 0, 8, 25, 0, 9, 146, 83,
7, 59, 0, 8, 121, 0, 8, 57, 0, 9, 210, 81, 7, 17, 0, 8, 105, 0, 8,
41, 0, 9, 178, 0, 8, 9, 0, 8, 137, 0, 8, 73, 0, 9, 242, 80, 7, 4,
0, 8, 85, 0, 8, 21, 80, 8, 258, 83, 7, 43, 0, 8, 117, 0, 8, 53, 0,
9, 202, 81, 7, 13, 0, 8, 101, 0, 8, 37, 0, 9, 170, 0, 8, 5, 0, 8,
133, 0, 8, 69, 0, 9, 234, 80, 7, 8, 0, 8, 93, 0, 8, 29, 0, 9, 154,
84, 7, 83, 0, 8, 125, 0, 8, 61, 0, 9, 218, 82, 7, 23, 0, 8, 109, 0,
8, 45, 0, 9, 186, 0, 8, 13, 0, 8, 141, 0, 8, 77, 0, 9, 250, 80, 7,
3, 0, 8, 83, 0, 8, 19, 85, 8, 195, 83, 7, 35, 0, 8, 115, 0, 8, 51,
0, 9, 198, 81, 7, 11, 0, 8, 99, 0, 8, 35, 0, 9, 166, 0, 8, 3, 0, 8,
131, 0, 8, 67, 0, 9, 230, 80, 7, 7, 0, 8, 91, 0, 8, 27, 0, 9, 150,
84, 7, 67, 0, 8, 123, 0, 8, 59, 0, 9, 214, 82, 7, 19, 0, 8, 107, 0,
8, 43, 0, 9, 182, 0, 8, 11, 0, 8, 139, 0, 8, 75, 0, 9, 246, 80, 7,
5, 0, 8, 87, 0, 8, 23, 192, 8, 0, 83, 7, 51, 0, 8, 119, 0, 8, 55,
0, 9, 206, 81, 7, 15, 0, 8, 103, 0, 8, 39, 0, 9, 174, 0, 8, 7, 0,
8, 135, 0, 8, 71, 0, 9, 238, 80, 7, 9, 0, 8, 95, 0, 8, 31, 0, 9,
158, 84, 7, 99, 0, 8, 127, 0, 8, 63, 0, 9, 222, 82, 7, 27, 0, 8,
111, 0, 8, 47, 0, 9, 190, 0, 8, 15, 0, 8, 143, 0, 8, 79, 0, 9, 254,
96, 7, 256, 0, 8, 80, 0, 8, 16, 84, 8, 115, 82, 7, 31, 0, 8, 112,
0, 8, 48, 0, 9, 193,
80, 7, 10, 0, 8, 96, 0, 8, 32, 0, 9, 161, 0, 8, 0, 0, 8, 128, 0, 8,
64, 0, 9, 225, 80, 7, 6, 0, 8, 88, 0, 8, 24, 0, 9, 145, 83, 7, 59,
0, 8, 120, 0, 8, 56, 0, 9, 209, 81, 7, 17, 0, 8, 104, 0, 8, 40, 0,
9, 177, 0, 8, 8, 0, 8, 136, 0, 8, 72, 0, 9, 241, 80, 7, 4, 0, 8,
84, 0, 8, 20, 85, 8, 227, 83, 7, 43, 0, 8, 116, 0, 8, 52, 0, 9,
201, 81, 7, 13, 0, 8, 100, 0, 8, 36, 0, 9, 169, 0, 8, 4, 0, 8, 132,
0, 8, 68, 0, 9, 233, 80, 7, 8, 0, 8, 92, 0, 8, 28, 0, 9, 153, 84,
7, 83, 0, 8, 124, 0, 8, 60, 0, 9, 217, 82, 7, 23, 0, 8, 108, 0, 8,
44, 0, 9, 185, 0, 8, 12, 0, 8, 140, 0, 8, 76, 0, 9, 249, 80, 7, 3,
0, 8, 82, 0, 8, 18, 85, 8, 163, 83, 7, 35, 0, 8, 114, 0, 8, 50, 0,
9, 197, 81, 7, 11, 0, 8, 98, 0, 8, 34, 0, 9, 165, 0, 8, 2, 0, 8,
130, 0, 8, 66, 0, 9, 229, 80, 7, 7, 0, 8, 90, 0, 8, 26, 0, 9, 149,
84, 7, 67, 0, 8, 122, 0, 8, 58, 0, 9, 213, 82, 7, 19, 0, 8, 106, 0,
8, 42, 0, 9, 181, 0, 8, 10, 0, 8, 138, 0, 8, 74, 0, 9, 245, 80, 7,
5, 0, 8, 86, 0, 8, 22, 192, 8, 0, 83, 7, 51, 0, 8, 118, 0, 8, 54,
0, 9, 205, 81, 7, 15, 0, 8, 102, 0, 8, 38, 0, 9, 173, 0, 8, 6, 0,
8, 134, 0, 8, 70, 0, 9, 237, 80, 7, 9, 0, 8, 94, 0, 8, 30, 0, 9,
157, 84, 7, 99, 0, 8, 126, 0, 8, 62, 0, 9, 221, 82, 7, 27, 0, 8,
110, 0, 8, 46, 0, 9, 189, 0, 8, 14, 0, 8, 142, 0, 8, 78, 0, 9, 253,
96, 7, 256, 0, 8, 81, 0, 8, 17, 85, 8, 131, 82, 7, 31, 0, 8, 113,
0, 8, 49, 0, 9, 195, 80, 7, 10, 0, 8, 97, 0, 8, 33, 0, 9, 163, 0,
8, 1, 0, 8, 129, 0, 8, 65, 0, 9, 227, 80, 7, 6, 0, 8, 89, 0, 8, 25,
0, 9, 147, 83, 7, 59, 0, 8, 121, 0, 8, 57, 0, 9, 211, 81, 7, 17, 0,
8, 105, 0, 8, 41, 0, 9, 179, 0, 8, 9, 0, 8, 137, 0, 8, 73, 0, 9,
243, 80, 7, 4, 0, 8, 85, 0, 8, 21, 80, 8, 258, 83, 7, 43, 0, 8,
117, 0, 8, 53, 0, 9, 203, 81, 7, 13, 0, 8, 101, 0, 8, 37, 0, 9,
171, 0, 8, 5, 0, 8, 133, 0, 8, 69, 0, 9, 235, 80, 7, 8, 0, 8, 93,
0, 8, 29, 0, 9, 155, 84, 7, 83, 0, 8, 125, 0, 8, 61, 0, 9, 219, 82,
7, 23, 0, 8, 109, 0, 8, 45, 0, 9, 187, 0, 8, 13, 0, 8, 141, 0, 8,
77, 0, 9, 251, 80, 7, 3, 0, 8, 83, 0, 8, 19, 85, 8, 195, 83, 7, 35,
0, 8, 115, 0, 8, 51, 0, 9, 199, 81, 7, 11, 0, 8, 99, 0, 8, 35, 0,
9, 167, 0, 8, 3, 0, 8, 131, 0, 8, 67, 0, 9, 231, 80, 7, 7, 0, 8,
91, 0, 8, 27, 0, 9, 151, 84, 7, 67, 0, 8, 123, 0, 8, 59, 0, 9, 215,
82, 7, 19, 0, 8, 107, 0, 8, 43, 0, 9, 183, 0, 8, 11, 0, 8, 139, 0,
8, 75, 0, 9, 247, 80, 7, 5, 0, 8, 87, 0, 8, 23, 192, 8, 0, 83, 7,
51, 0, 8, 119, 0, 8, 55, 0, 9, 207, 81, 7, 15, 0, 8, 103, 0, 8, 39,
0, 9, 175, 0, 8, 7, 0, 8, 135, 0, 8, 71, 0, 9, 239, 80, 7, 9, 0, 8,
95, 0, 8, 31, 0, 9, 159, 84, 7, 99, 0, 8, 127, 0, 8, 63, 0, 9, 223,
82, 7, 27, 0, 8, 111, 0, 8, 47, 0, 9, 191, 0, 8, 15, 0, 8, 143, 0,
8, 79, 0, 9, 255 };
static final int[] fixed_td = { 80, 5, 1, 87, 5, 257, 83, 5, 17, 91, 5,
4097, 81, 5, 5, 89, 5, 1025, 85, 5, 65, 93, 5, 16385, 80, 5, 3, 88,
5, 513, 84, 5, 33, 92, 5, 8193, 82, 5, 9, 90, 5, 2049, 86, 5, 129,
192, 5, 24577, 80, 5, 2, 87, 5, 385, 83, 5, 25, 91, 5, 6145, 81, 5,
7, 89, 5, 1537, 85, 5, 97, 93, 5, 24577, 80, 5, 4, 88, 5, 769, 84,
5, 49, 92, 5, 12289, 82, 5, 13, 90, 5, 3073, 86, 5, 193, 192, 5,
24577 };
// Tables for deflate from PKZIP's appnote.txt.
static final int[] cplens = { // Copy lengths for literal codes 257..285
3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59,
67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 };
// see note #13 above about 258
static final int[] cplext = { // Extra bits for literal codes 257..285
0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5,
5, 5, 5, 0, 112, 112 // 112==invalid
};
static final int[] cpdist = { // Copy offsets for distance codes 0..29
1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513,
769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577 };
static final int[] cpdext = { // Extra bits for distance codes
0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10,
11, 11, 12, 12, 13, 13 };
// If BMAX needs to be larger than 16, then h and x[] should be uLong.
static final int BMAX = 15; // maximum bit length of any code
static int inflate_trees_fixed(int[] bl, // literal desired/actual bit depth
int[] bd, // distance desired/actual bit depth
int[][] tl,// literal/length tree result
int[][] td,// distance tree result
ZStream z // for memory allocation
) {
bl[0] = fixed_bl;
bd[0] = fixed_bd;
tl[0] = fixed_tl;
td[0] = fixed_td;
return Z_OK;
}
int[] hn = null; // hufts used in space
int[] v = null; // work area for huft_build
int[] c = null; // bit length count table
int[] r = null; // table entry for structure assignment
int[] u = null; // table stack
int[] x = null; // bit offsets, then code stack
private int huft_build(int[] b, // code lengths in bits (all assumed <=
// BMAX)
int bindex, int n, // number of codes (assumed <= 288)
int s, // number of simple-valued codes (0..s-1)
int[] d, // list of base values for non-simple codes
int[] e, // list of extra bits for non-simple codes
int[] t, // result: starting table
int[] m, // maximum lookup bits, returns actual
int[] hp,// space for trees
int[] hn,// hufts used in space
int[] v // working area: values in order of bit length
) {
// Given a list of code lengths and a maximum table size, make a set of
// tables to decode that set of codes. Return Z_OK on success,
// Z_BUF_ERROR
// if the given code set is incomplete (the tables are still built in
// this
// case), Z_DATA_ERROR if the input is invalid (an over-subscribed set
// of
// lengths), or Z_MEM_ERROR if not enough memory.
int a; // counter for codes of length k
int f; // i repeats in table every f entries
int g; // maximum code length
int h; // table level
int i; // counter, current code
int j; // counter
int k; // number of bits in current code
int l; // bits per table (returned in m)
int mask; // (1 << w) - 1, to avoid cc -O bug on HP
int p; // pointer into c[], b[], or v[]
int q; // points to current table
int w; // bits before this table == (l * h)
int xp; // pointer into x
int y; // number of dummy codes added
int z; // number of entries in current table
// Generate counts for each bit length
p = 0;
i = n;
do {
c[b[bindex + p]]++;
p++;
i--; // assume all entries <= BMAX
} while (i != 0);
if (c[0] == n) { // null input--all zero length codes
t[0] = -1;
m[0] = 0;
return Z_OK;
}
// Find minimum and maximum length, bound *m by those
l = m[0];
for (j = 1; j <= BMAX; j++)
if (c[j] != 0)
break;
k = j; // minimum code length
if (l < j) {
l = j;
}
for (i = BMAX; i != 0; i--) {
if (c[i] != 0)
break;
}
g = i; // maximum code length
if (l > i) {
l = i;
}
m[0] = l;
// Adjust last length count to fill out codes, if needed
for (y = 1 << j; j < i; j++, y <<= 1) {
if ((y -= c[j]) < 0) {
return Z_DATA_ERROR;
}
}
if ((y -= c[i]) < 0) {
return Z_DATA_ERROR;
}
c[i] += y;
// Generate starting offsets into the value table for each length
x[1] = j = 0;
p = 1;
xp = 2;
while (--i != 0) { // note that i == g from above
x[xp] = (j += c[p]);
xp++;
p++;
}
// Make a table of values in order of bit lengths
i = 0;
p = 0;
do {
if ((j = b[bindex + p]) != 0) {
v[x[j]++] = i;
}
p++;
} while (++i < n);
n = x[g]; // set n to length of v
// Generate the Huffman codes and for each, make the table entries
x[0] = i = 0; // first Huffman code is zero
p = 0; // grab values in bit order
h = -1; // no tables yet--level -1
w = -l; // bits decoded == (l * h)
u[0] = 0; // just to keep compilers happy
q = 0; // ditto
z = 0; // ditto
// go through the bit lengths (k already is bits in shortest code)
for (; k <= g; k++) {
a = c[k];
while (a-- != 0) {
// here i is the Huffman code of length k bits for value *p
// make tables up to required level
while (k > w + l) {
h++;
w += l; // previous table always l bits
// compute minimum size table less than or equal to l bits
z = g - w;
z = (z > l) ? l : z; // table size upper limit
if ((f = 1 << (j = k - w)) > a + 1) { // try a k-w bit table
// too few codes for
// k-w bit table
f -= a + 1; // deduct codes from patterns left
xp = k;
if (j < z) {
while (++j < z) { // try smaller tables up to z bits
if ((f <<= 1) <= c[++xp])
break; // enough codes to use up j bits
f -= c[xp]; // else deduct codes from patterns
}
}
}
z = 1 << j; // table entries for j-bit table
// allocate new table
if (hn[0] + z > MANY) { // (note: doesn't matter for fixed)
return Z_DATA_ERROR; // overflow of MANY
}
u[h] = q = /* hp+ */hn[0]; // DEBUG
hn[0] += z;
// connect to last table, if there is one
if (h != 0) {
x[h] = i; // save pattern for backing up
r[0] = (byte) j; // bits in this table
r[1] = (byte) l; // bits to dump before this table
j = i >>> (w - l);
r[2] = (q - u[h - 1] - j); // offset to this table
System.arraycopy(r, 0, hp, (u[h - 1] + j) * 3, 3); // connect
// to
// last
// table
} else {
t[0] = q; // first table is returned result
}
}
// set up table entry in r
r[1] = (byte) (k - w);
if (p >= n) {
r[0] = 128 + 64; // out of values--invalid code
} else if (v[p] < s) {
r[0] = (byte) (v[p] < 256 ? 0 : 32 + 64); // 256 is
// end-of-block
r[2] = v[p++]; // simple code is just the value
} else {
r[0] = (byte) (e[v[p] - s] + 16 + 64); // non-simple--look
// up in lists
r[2] = d[v[p++] - s];
}
// fill code-like entries with r
f = 1 << (k - w);
for (j = i >>> w; j < z; j += f) {
System.arraycopy(r, 0, hp, (q + j) * 3, 3);
}
// backwards increment the k-bit code i
for (j = 1 << (k - 1); (i & j) != 0; j >>>= 1) {
i ^= j;
}
i ^= j;
// backup over finished tables
mask = (1 << w) - 1; // needed on HP, cc -O bug
while ((i & mask) != x[h]) {
h--; // don't need to update q
w -= l;
mask = (1 << w) - 1;
}
}
}
// Return Z_BUF_ERROR if we were given an incomplete table
return y != 0 && g != 1 ? Z_BUF_ERROR : Z_OK;
}
int inflate_trees_bits(int[] c, // 19 code lengths
int[] bb, // bits tree desired/actual depth
int[] tb, // bits tree result
int[] hp, // space for trees
ZStream z // for messages
) {
int result;
initWorkArea(19);
hn[0] = 0;
result = huft_build(c, 0, 19, 19, null, null, tb, bb, hp, hn, v);
if (result == Z_DATA_ERROR) {
z.msg = "oversubscribed dynamic bit lengths tree";
} else if (result == Z_BUF_ERROR || bb[0] == 0) {
z.msg = "incomplete dynamic bit lengths tree";
result = Z_DATA_ERROR;
}
return result;
}
int inflate_trees_dynamic(int nl, // number of literal/length codes
int nd, // number of distance codes
int[] c, // that many (total) code lengths
int[] bl, // literal desired/actual bit depth
int[] bd, // distance desired/actual bit depth
int[] tl, // literal/length tree result
int[] td, // distance tree result
int[] hp, // space for trees
ZStream z // for messages
) {
int result;
// build literal/length tree
initWorkArea(288);
hn[0] = 0;
result = huft_build(c, 0, nl, 257, cplens, cplext, tl, bl, hp, hn, v);
if (result != Z_OK || bl[0] == 0) {
if (result == Z_DATA_ERROR) {
z.msg = "oversubscribed literal/length tree";
} else if (result != Z_MEM_ERROR) {
z.msg = "incomplete literal/length tree";
result = Z_DATA_ERROR;
}
return result;
}
// build distance tree
initWorkArea(288);
result = huft_build(c, nl, nd, 0, cpdist, cpdext, td, bd, hp, hn, v);
if (result != Z_OK || (bd[0] == 0 && nl > 257)) {
if (result == Z_DATA_ERROR) {
z.msg = "oversubscribed distance tree";
} else if (result == Z_BUF_ERROR) {
z.msg = "incomplete distance tree";
result = Z_DATA_ERROR;
} else if (result != Z_MEM_ERROR) {
z.msg = "empty distance tree with lengths";
result = Z_DATA_ERROR;
}
return result;
}
return Z_OK;
}
private void initWorkArea(int vsize) {
if (hn == null) {
hn = new int[1];
v = new int[vsize];
c = new int[BMAX + 1];
r = new int[3];
u = new int[BMAX];
x = new int[BMAX + 1];
}
if (v.length < vsize) {
v = new int[vsize];
}
for (int i = 0; i < vsize; i++) {
v[i] = 0;
}
for (int i = 0; i < BMAX + 1; i++) {
c[i] = 0;
}
for (int i = 0; i < 3; i++) {
r[i] = 0;
}
// for(int i=0; i<BMAX; i++){u[i]=0;}
System.arraycopy(c, 0, u, 0, BMAX);
// for(int i=0; i<BMAX+1; i++){x[i]=0;}
System.arraycopy(c, 0, x, 0, BMAX + 1);
}
}
| Java |
/* -*-mode:java; c-basic-offset:2; -*- */
/*
Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,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:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. 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.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
package com.jcraft.jzlib;
final class Adler32 {
// largest prime smaller than 65536
static final private int BASE = 65521;
// NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1
static final private int NMAX = 5552;
long adler32(long adler, byte[] buf, int index, int len) {
if (buf == null) {
return 1L;
}
long s1 = adler & 0xffff;
long s2 = (adler >> 16) & 0xffff;
int k;
while (len > 0) {
k = len < NMAX ? len : NMAX;
len -= k;
while (k >= 16) {
s1 += buf[index++] & 0xff;
s2 += s1;
s1 += buf[index++] & 0xff;
s2 += s1;
s1 += buf[index++] & 0xff;
s2 += s1;
s1 += buf[index++] & 0xff;
s2 += s1;
s1 += buf[index++] & 0xff;
s2 += s1;
s1 += buf[index++] & 0xff;
s2 += s1;
s1 += buf[index++] & 0xff;
s2 += s1;
s1 += buf[index++] & 0xff;
s2 += s1;
s1 += buf[index++] & 0xff;
s2 += s1;
s1 += buf[index++] & 0xff;
s2 += s1;
s1 += buf[index++] & 0xff;
s2 += s1;
s1 += buf[index++] & 0xff;
s2 += s1;
s1 += buf[index++] & 0xff;
s2 += s1;
s1 += buf[index++] & 0xff;
s2 += s1;
s1 += buf[index++] & 0xff;
s2 += s1;
s1 += buf[index++] & 0xff;
s2 += s1;
k -= 16;
}
if (k != 0) {
do {
s1 += buf[index++] & 0xff;
s2 += s1;
} while (--k != 0);
}
s1 %= BASE;
s2 %= BASE;
}
return (s2 << 16) | s1;
}
/*
* private java.util.zip.Adler32 adler=new java.util.zip.Adler32(); long
* adler32(long value, byte[] buf, int index, int len){ if(value==1)
* {adler.reset();} if(buf==null) {adler.reset();} else{adler.update(buf,
* index, len);} return adler.getValue(); }
*/
}
| Java |
/**
* Kitchen Timer
* Copyright (C) 2010 Roberto Leinardi
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.leinardi.kitchentimer.customtypes;
import java.io.Serializable;
public class Food implements Serializable {
/**
*
*/
private static final long serialVersionUID = -1377135485835288101L;
public static class FoodMetaData {
public static final String ID = "_id";
public static final String NAME = "name";
public static final String HOURS = "hours";
public static final String MINUTES = "minutes";
public static final String SECONDS = "seconds";
public static String[] COLUMNS = new String[] { ID, NAME, HOURS, MINUTES, SECONDS };
}
public long id;
public String name;
public int hours;
public int minutes;
public int seconds;
public Food() {
hours = 0;
minutes = 0;
seconds = 0;
}
public Food(String name, int hours, int minutes, int seconds) {
this.name=name;
this.hours=hours;
this.minutes=minutes;
this.seconds=seconds;
}
public boolean isTimeSet(){
return hours != 0 || minutes != 0 || seconds != 0;
}
public boolean isNameSet() {
return !name.equals("") && name != null;
}
}
| Java |
/**
* Kitchen Timer
* Copyright (C) 2010 Roberto Leinardi
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.leinardi.kitchentimer.database;
import com.leinardi.kitchentimer.customtypes.Food;
import com.leinardi.kitchentimer.customtypes.Food.FoodMetaData;
import com.leinardi.kitchentimer.misc.Log;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DbTool {
SQLiteDatabase db;
Context context;
DatabaseHelper dbHelper;
static final String DB_NAME="DB_FOODS";
static final String TABLE="FOOD";
static final int DB_VERSION=2;
public DbTool(Context context) {
this.context=context;
this.dbHelper=new DatabaseHelper(context);
}
public static class DatabaseHelper extends SQLiteOpenHelper{
public DatabaseHelper(Context context){
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS " +
TABLE + " ("+
FoodMetaData.ID +" INTEGER PRIMARY KEY AUTOINCREMENT," +
FoodMetaData.NAME +" TEXT NOT NULL," +
FoodMetaData.HOURS +" INTEGER NOT NULL," +
FoodMetaData.MINUTES +" INTEGER NOT NULL," +
FoodMetaData.SECONDS +" INTEGER NOT NULL)"
);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.d("DbTool.onUpgrade", "old:"+oldVersion+" new:"+newVersion);
if(db.getVersion()==1){
db.execSQL("ALTER TABLE " + TABLE + " RENAME TO tmp_"+ TABLE);
onCreate(db);
db.execSQL("INSERT INTO " +
TABLE + "("+
FoodMetaData.NAME +", " +
FoodMetaData.HOURS +", " +
FoodMetaData.MINUTES +", " +
FoodMetaData.SECONDS +") " +
"SELECT " +
"nome, " +
FoodMetaData.HOURS +", " +
FoodMetaData.MINUTES +", " +
FoodMetaData.SECONDS + " " +
"FROM tmp_" + TABLE
);
db.execSQL("DROP TABLE IF EXISTS tmp_"+TABLE);
}else{
db.execSQL("DROP TABLE IF EXISTS "+TABLE);
onCreate(db);
}
}
}
public void open(){
db=dbHelper.getWritableDatabase();
}
public void close(){
dbHelper.close();
}
public void insert(Food record){
ContentValues values = new ContentValues();
values.put(FoodMetaData.NAME, record.name);
values.put(FoodMetaData.HOURS, record.hours);
values.put(FoodMetaData.MINUTES, record.minutes);
values.put(FoodMetaData.SECONDS, record.seconds);
db.insert(TABLE, null, values);
}
public void update(Food record){
ContentValues values = new ContentValues();
values.put(FoodMetaData.NAME, record.name);
values.put(FoodMetaData.HOURS, record.hours);
values.put(FoodMetaData.MINUTES, record.minutes);
values.put(FoodMetaData.SECONDS, record.seconds);
db.update(TABLE, values, "_id="+record.id, null);
}
public void delete(long examId){
db.delete(TABLE, "_id=" + examId, null);
}
public void truncate(){
db.delete(TABLE, null, null);
}
public Cursor query(long examId){
return db.query(TABLE, FoodMetaData.COLUMNS, "_id=" + examId, null, null, null,null);
}
public Cursor getRecords(){
return db.rawQuery("SELECT * FROM "+ TABLE + " ORDER BY " + FoodMetaData.NAME, null);
}
}
| Java |
/**
* Kitchen Timer
* Copyright (C) 2010 Roberto Leinardi
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.leinardi.kitchentimer.misc;
import com.leinardi.kitchentimer.R;
import com.leinardi.kitchentimer.utils.Utils;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
public class Changelog {
private static final String TAG = "Changelog";
public static boolean show(Activity activity) {
SharedPreferences preferences = activity.getSharedPreferences(Constants.PREF_CHANGELOG, Activity.MODE_PRIVATE);
int prefVersion = preferences.getInt(Constants.PREF_APP_VERSION, 0);
int currentVersion;
try {
PackageInfo pi = activity.getPackageManager().getPackageInfo(activity.getPackageName(), 0);
currentVersion = pi.versionCode;
} catch (NameNotFoundException e) {
Log.e(TAG, "Package name not found", e);
return false;
}
if (prefVersion != 0) {
if (currentVersion > prefVersion) {
showChangelogDialog(activity);
}
}
preferences.edit().putInt(Constants.PREF_APP_VERSION, currentVersion).commit();
return true;
}
protected static void showChangelogDialog(Activity activity) {
new AlertDialog.Builder(activity)
.setIcon(android.R.drawable.ic_dialog_info)
.setTitle(R.string.changelog_title)
.setView(Utils.dialogWebView(activity, activity.getString(R.string.changelog_filename)))
.setPositiveButton(R.string.ok, null)
.show();
}
}
| Java |
/**
* Kitchen Timer
* Copyright (C) 2010 Roberto Leinardi
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.leinardi.kitchentimer.misc;
import android.util.Config;
public class Log
{
private final static String LOGTAG = "kitchentimer";
//static final boolean DEBUG = false;
//public static final boolean LOGV = DEBUG ? Config.LOGD : Config.LOGV;
//Replace all Log.d with if(Log.LOGV) Log.v() to prevent Strings to be builded and to save memory
public static void v(String TAG, String logMe)
{
if(Config.LOGV) android.util.Log.v(LOGTAG, TAG + ": " + logMe);
}
public static void d(String TAG, String logMe)
{
if(Config.LOGD) android.util.Log.d(LOGTAG, TAG + ": " + logMe);
}
public static void e(String TAG, String logMe)
{
android.util.Log.e(LOGTAG, TAG + ": " + logMe);
}
public static void e(String TAG, String logMe, Throwable ex)
{
android.util.Log.e(LOGTAG, TAG + ": " + logMe, ex);
}
public static void i(String TAG, String logMe)
{
if(Config.LOGD) android.util.Log.i(LOGTAG, TAG + ": " + logMe);
}
} | Java |
/**
* Kitchen Timer
* Copyright (C) 2010 Roberto Leinardi
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.leinardi.kitchentimer.misc;
import com.leinardi.kitchentimer.R;
import com.leinardi.kitchentimer.utils.Utils;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
/**
* Displays an EULA ("End User License Agreement") that the user has to accept
* before using the application. Your application should call
* {@link Eula#show(android.app.Activity)} in the onCreate() method of the first
* activity. If the user accepts the EULA, it will never be shown again. If the
* user refuses, {@link android.app.Activity#finish()} is invoked on your
* activity.
*/
public class Eula {
/**
* callback to let the activity know when the user has accepted the EULA.
*/
static interface OnEulaAgreedTo {
/**
* Called when the user has accepted the eula and the dialog closes.
*/
void onEulaAgreedTo();
}
/**
* Displays the EULA if necessary. This method should be called from the
* onCreate() method of your main Activity.
*
* @param activity
* The Activity to finish if the user rejects the EULA.
* @return Whether the user has agreed already.
*/
public static boolean show(final Activity activity) {
final SharedPreferences preferences = activity.getSharedPreferences(Constants.PREF_EULA, Activity.MODE_PRIVATE);
// preferences.edit().putBoolean(Constants.PREF_EULA_ACCEPTED, false).commit();
if (!preferences.getBoolean(Constants.PREF_EULA_ACCEPTED, false)) {
final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle(R.string.eula_title);
builder.setCancelable(true);
builder.setPositiveButton(R.string.eula_accept, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
accept(preferences);
if (activity instanceof OnEulaAgreedTo) {
((OnEulaAgreedTo) activity).onEulaAgreedTo();
}
}
});
builder.setNegativeButton(R.string.eula_refuse, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
refuse(activity);
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
refuse(activity);
}
});
builder.setView(Utils.dialogWebView(activity, activity.getString(R.string.eula_filename)));
builder.create().show();
return false;
}
return true;
}
private static void accept(SharedPreferences preferences) {
preferences.edit().putBoolean(Constants.PREF_EULA_ACCEPTED, true).commit();
}
private static void refuse(Activity activity) {
activity.finish();
}
}
| Java |
/**
* Kitchen Timer
* Copyright (C) 2010 Roberto Leinardi
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.leinardi.kitchentimer.misc;
import java.io.File;
import android.os.Environment;
public class Constants
{
public static final String CSV_FILENAME = "KitchenTimer.csv";
public static File SD_PATH = Environment.getExternalStorageDirectory();
public static File CSV_FILE = new File(SD_PATH, CSV_FILENAME);
public static final String INTENT_TIMER_ENDED = "kitchentimer.custom.intent.action.TIMER_ENDED";
public static final int APP_NOTIF_ID = 99;
public static final String TIMER = "timer";
public static final String TIMER_NAME = "timer_name";
public static final int REQUEST_PRESETS = 1;
// Symbolic names for the keys used for preference lookup
public static final String PREF_HOURS = "Hours";
public static final String PREF_MINUTES = "Minutes";
public static final String PREF_SECONDS = "Seconds";
public static final String[] PREF_TIMERS_NAMES = {
"pref_timer_name_0",
"pref_timer_name_1",
"pref_timer_name_2" };
public static final String[] PREF_TIMERS_SECONDS = {
"timer_seconds_0",
"timer_seconds_1",
"timer_seconds_2" };
public static final String[] PREF_START_TIMES = {
"start_time_0",
"start_time_1",
"start_time_2" };
public static final int NUM_TIMERS = 3;
public static final long WAKELOCK_TIMEOUT = 5000;
public static final String PREF_CHANGELOG = "changelog";
public static final String PREF_APP_VERSION = "app.version";
public static final String PREF_EULA = "eula";
public static final String PREF_EULA_ACCEPTED = "eula.accepted";
public static final String APP_NAMESPACE = "http://schemas.android.com/apk/res/com.leinardi.kitchentimer";
} | Java |
/**
* Kitchen Timer
* Copyright (C) 2010 Roberto Leinardi
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.leinardi.kitchentimer.receivers;
import java.util.ArrayList;
import com.leinardi.kitchentimer.R;
import com.leinardi.kitchentimer.misc.Constants;
import com.leinardi.kitchentimer.ui.MainActivity;
//import com.leinardi.kitchentimer.R.drawable;
//import com.leinardi.kitchentimer.R.raw;
//import com.leinardi.kitchentimer.R.string;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.PowerManager;
import android.preference.PreferenceManager;
import android.view.Gravity;
import android.widget.Toast;
public class AlarmReceiver extends BroadcastReceiver {
private PowerManager.WakeLock mWakeLock = null;
private NotificationManager mNotificationManager;
private SharedPreferences mPrefs;
private Context mContext;
private String timerName;
@Override
public void onReceive(Context context, Intent intent) {
// Hold a wake lock for 5 seconds, enough to give any
// services we start time to take their own wake locks.
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, MainActivity.TAG);
mWakeLock.acquire(Constants.WAKELOCK_TIMEOUT);
mContext = context;
mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mPrefs = PreferenceManager.getDefaultSharedPreferences(context);
Bundle b = intent.getExtras();
int timer = b.getInt(Constants.TIMER);
timerName = b.getString(Constants.TIMER_NAME);
sendTimeIsOverNotification(timer);
if (mPrefs.getBoolean(mContext.getString(R.string.pref_clear_timer_label_key), false)){
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString(Constants.PREF_TIMERS_NAMES[timer], mContext.getString(R.string.timer) + " " + timer);
editor.commit();
}
if (mPrefs.getBoolean(mContext.getString(R.string.pref_show_tips_key), true)){
Toast toast = Toast.makeText(mContext, mContext.getString(R.string.tip1), Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP, 0, 0);
toast.show();
}
Intent mIntent = new Intent(mContext, MainActivity.class);
mIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
// La lanciamo
mContext.startActivity(mIntent);
}
/**
*
* @param timer
* @param tickerText
* @param contentTitle
* @param contentText
*/
private void sendTimeIsOverNotification(int timer) {
int icon;
String ns = Context.NOTIFICATION_SERVICE;
mNotificationManager = (NotificationManager) mContext.getSystemService(ns);
icon = R.drawable.notify_alarm_default;
CharSequence mTickerText = timerName + " - " + mContext.getResources().getString(R.string.app_name);
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, mTickerText, when);
notification.number = timer + 1;
CharSequence mContentTitle = timerName;
CharSequence mContentText = mContext.getResources().getString(R.string.countdown_ended);
Intent clickIntent = new Intent(mContext, MainActivity.class);
clickIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP
| Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(mContext, 0, clickIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
notification.setLatestEventInfo(mContext, mContentTitle, mContentText, contentIntent);
String defaultNotification = "android.resource://com.leinardi.kitchentimer/" + R.raw.mynotification;
if (mPrefs.getBoolean(mContext.getString(R.string.pref_notification_sound_key), true)) {
if (mPrefs.getBoolean(mContext.getString(R.string.pref_notification_custom_sound_key), false)) {
String customNotification = mPrefs.getString(mContext
.getString(R.string.pref_notification_ringtone_key), defaultNotification);
if (!customNotification.equals(defaultNotification)) {
notification.sound = Uri.parse(customNotification);
}
} else {
notification.sound = Uri.parse(defaultNotification);
}
}
if (mPrefs.getBoolean(mContext.getString(R.string.pref_notification_insistent_key), true))
notification.flags |= Notification.FLAG_INSISTENT;
if (mPrefs.getBoolean(mContext.getString(R.string.pref_notification_vibrate_key), true)) {
String mVibratePattern = mPrefs.getString(mContext
.getString(R.string.pref_notification_vibrate_pattern_key), "");
if (!mVibratePattern.equals("")) {
notification.vibrate = parseVibratePattern(mVibratePattern);
} else {
notification.defaults |= Notification.DEFAULT_VIBRATE;
}
}
if (mPrefs.getBoolean(mContext.getString(R.string.pref_notification_led_key), true)) {
notification.flags |= Notification.FLAG_SHOW_LIGHTS;
notification.ledARGB = Color.parseColor(mPrefs.getString(mContext
.getString(R.string.pref_notification_led_color_key), "red"));
int mLedBlinkRate = Integer.parseInt(mPrefs.getString(mContext
.getString(R.string.pref_notification_led_blink_rate_key), "2"));
notification.ledOnMS = 500;
notification.ledOffMS = mLedBlinkRate * 1000;
}
notification.flags |= Notification.FLAG_AUTO_CANCEL;
mNotificationManager.notify(timer + 10, notification);
}
/**
* Parse the user provided custom vibrate pattern into a long[] Borrowed
* from SMSPopup
*/
public static long[] parseVibratePattern(String stringPattern) {
ArrayList<Long> arrayListPattern = new ArrayList<Long>();
Long l;
String[] splitPattern = stringPattern.split(",");
int VIBRATE_PATTERN_MAX_SECONDS = 60000;
int VIBRATE_PATTERN_MAX_PATTERN = 100;
for (int i = 0; i < splitPattern.length; i++) {
try {
l = Long.parseLong(splitPattern[i].trim());
} catch (NumberFormatException e) {
return null;
}
if (l > VIBRATE_PATTERN_MAX_SECONDS) {
return null;
}
arrayListPattern.add(l);
}
int size = arrayListPattern.size();
if (size > 0 && size < VIBRATE_PATTERN_MAX_PATTERN) {
long[] pattern = new long[size];
for (int i = 0; i < pattern.length; i++) {
pattern[i] = arrayListPattern.get(i);
}
return pattern;
}
return null;
}
}
| Java |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* 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.leinardi.kitchentimer.customviews;
import com.leinardi.kitchentimer.R;
import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.widget.ImageButton;
/**
* This class exists purely to cancel long click events.
*/
public class NumberPickerButton extends ImageButton {
private NumberPicker mNumberPicker;
public NumberPickerButton(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
}
public NumberPickerButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
public NumberPickerButton(Context context) {
super(context);
}
public void setNumberPicker(NumberPicker picker) {
mNumberPicker = picker;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
cancelLongpressIfRequired(event);
return super.onTouchEvent(event);
}
@Override
public boolean onTrackballEvent(MotionEvent event) {
cancelLongpressIfRequired(event);
return super.onTrackballEvent(event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_DPAD_CENTER)
|| (keyCode == KeyEvent.KEYCODE_ENTER)) {
cancelLongpress();
}
return super.onKeyUp(keyCode, event);
}
private void cancelLongpressIfRequired(MotionEvent event) {
if ((event.getAction() == MotionEvent.ACTION_CANCEL)
|| (event.getAction() == MotionEvent.ACTION_UP)) {
cancelLongpress();
}
}
private void cancelLongpress() {
if (R.id.increment == getId()) {
mNumberPicker.cancelIncrement();
} else if (R.id.decrement == getId()) {
mNumberPicker.cancelDecrement();
}
}
}
| Java |
/**
* Kitchen Timer
* Copyright (C) 2010 Roberto Leinardi
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.leinardi.kitchentimer.customviews;
import com.leinardi.kitchentimer.R;
import com.leinardi.kitchentimer.ui.ConfigActivity;
import com.leinardi.kitchentimer.ui.PresetsActivity;
import com.leinardi.kitchentimer.utils.Utils;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.preference.DialogPreference;
import android.util.AttributeSet;
public class DonateDialogPreference extends DialogPreference {
Context mContext;
String fileName;
public DonateDialogPreference(Context context, AttributeSet attrs) {
super(context, attrs);
mContext= context;
TypedArray a = mContext.obtainStyledAttributes(attrs, R.styleable.MyDialogPreference);
fileName = a.getString(R.styleable.MyDialogPreference_fileName);
}
// protected void onPrepareDialogBuilder(Builder builder) {
// builder.setView(Utils.dialogWebView(mContext, fileName));
// }
@Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
if (positiveResult) {
Utils.donate(mContext);
}
}
}
| Java |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* 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.leinardi.kitchentimer.customviews;
import com.leinardi.kitchentimer.R;
import android.content.Context;
import android.os.Handler;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Spanned;
import android.text.method.NumberKeyListener;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnLongClickListener;
import android.widget.TextView;
import android.widget.LinearLayout;
import android.widget.EditText;
public class NumberPicker extends LinearLayout implements OnClickListener,
OnFocusChangeListener, OnLongClickListener {
public interface OnChangedListener {
void onChanged(NumberPicker picker, int oldVal, int newVal);
}
public interface Formatter {
String toString(int value);
}
/*
* Use a custom NumberPicker formatting callback to use two-digit
* minutes strings like "01". Keeping a static formatter etc. is the
* most efficient way to do this; it avoids creating temporary objects
* on every call to format().
*/
public static final NumberPicker.Formatter TWO_DIGIT_FORMATTER =
new NumberPicker.Formatter() {
final StringBuilder mBuilder = new StringBuilder();
final java.util.Formatter mFmt = new java.util.Formatter(mBuilder);
final Object[] mArgs = new Object[1];
public String toString(int value) {
mArgs[0] = value;
mBuilder.delete(0, mBuilder.length());
mFmt.format("%02d", mArgs);
return mFmt.toString();
}
};
private final Handler mHandler;
private final Runnable mRunnable = new Runnable() {
public void run() {
if (mIncrement) {
changeCurrent(mCurrent + 1);
mHandler.postDelayed(this, mSpeed);
} else if (mDecrement) {
changeCurrent(mCurrent - 1);
mHandler.postDelayed(this, mSpeed);
}
}
};
private final EditText mText;
private final InputFilter mNumberInputFilter;
private String[] mDisplayedValues;
private int mStart;
private int mEnd;
private int mCurrent;
private int mPrevious;
private OnChangedListener mListener;
private Formatter mFormatter;
private long mSpeed = 300;
private boolean mIncrement;
private boolean mDecrement;
public NumberPicker(Context context) {
this(context, null);
}
public NumberPicker(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
//@SuppressWarnings({"UnusedDeclaration"})
public NumberPicker(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs);
setOrientation(VERTICAL);
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.number_picker, this, true);
mHandler = new Handler();
InputFilter inputFilter = new NumberPickerInputFilter();
mNumberInputFilter = new NumberRangeKeyListener();
mIncrementButton = (NumberPickerButton) findViewById(R.id.increment);
mIncrementButton.setOnClickListener(this);
mIncrementButton.setOnLongClickListener(this);
mIncrementButton.setNumberPicker(this);
mDecrementButton = (NumberPickerButton) findViewById(R.id.decrement);
mDecrementButton.setOnClickListener(this);
mDecrementButton.setOnLongClickListener(this);
mDecrementButton.setNumberPicker(this);
mText = (EditText) findViewById(R.id.timepicker_input);
mText.setOnFocusChangeListener(this);
mText.setFilters(new InputFilter[] {inputFilter});
mText.setRawInputType(InputType.TYPE_CLASS_NUMBER);
if (!isEnabled()) {
setEnabled(false);
}
}
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
mIncrementButton.setEnabled(enabled);
mDecrementButton.setEnabled(enabled);
mText.setEnabled(enabled);
}
public void setOnChangeListener(OnChangedListener listener) {
mListener = listener;
}
public void setFormatter(Formatter formatter) {
mFormatter = formatter;
}
/**
* Set the range of numbers allowed for the number picker. The current
* value will be automatically set to the start.
*
* @param start the start of the range (inclusive)
* @param end the end of the range (inclusive)
*/
public void setRange(int start, int end) {
mStart = start;
mEnd = end;
mCurrent = start;
updateView();
}
/**
* Set the range of numbers allowed for the number picker. The current
* value will be automatically set to the start. Also provide a mapping
* for values used to display to the user.
*
* @param start the start of the range (inclusive)
* @param end the end of the range (inclusive)
* @param displayedValues the values displayed to the user.
*/
public void setRange(int start, int end, String[] displayedValues) {
mDisplayedValues = displayedValues;
mStart = start;
mEnd = end;
mCurrent = start;
updateView();
}
public void setCurrent(int current) {
mCurrent = current;
updateView();
}
/**
* The speed (in milliseconds) at which the numbers will scroll
* when the the +/- buttons are longpressed. Default is 300ms.
*/
public void setSpeed(long speed) {
mSpeed = speed;
}
public void onClick(View v) {
validateInput(mText);
if (!mText.hasFocus()) mText.requestFocus();
// now perform the increment/decrement
if (R.id.increment == v.getId()) {
changeCurrent(mCurrent + 1);
} else if (R.id.decrement == v.getId()) {
changeCurrent(mCurrent - 1);
}
}
private String formatNumber(int value) {
return (mFormatter != null)
? mFormatter.toString(value)
: String.valueOf(value);
}
private void changeCurrent(int current) {
// Wrap around the values if we go past the start or end
if (current > mEnd) {
current = mStart;
} else if (current < mStart) {
current = mEnd;
}
mPrevious = mCurrent;
mCurrent = current;
notifyChange();
updateView();
}
private void notifyChange() {
if (mListener != null) {
mListener.onChanged(this, mPrevious, mCurrent);
}
}
private void updateView() {
/* If we don't have displayed values then use the
* current number else find the correct value in the
* displayed values for the current number.
*/
if (mDisplayedValues == null) {
mText.setText(formatNumber(mCurrent));
} else {
mText.setText(mDisplayedValues[mCurrent - mStart]);
}
//mText.setSelection(mText.getText().length());
}
private void validateCurrentView(CharSequence str) {
int val = getSelectedPos(str.toString());
if ((val >= mStart) && (val <= mEnd)) {
if (mCurrent != val) {
mPrevious = mCurrent;
mCurrent = val;
notifyChange();
}
}
updateView();
}
public void onFocusChange(View v, boolean hasFocus) {
/* When focus is lost check that the text field
* has valid values.
*/
if (!hasFocus) {
validateInput(v);
}
}
private void validateInput(View v) {
String str = String.valueOf(((TextView) v).getText());
if ("".equals(str)) {
// Restore to the old value as we don't allow empty values
updateView();
} else {
// Check the new value and ensure it's in range
validateCurrentView(str);
}
}
/**
* We start the long click here but rely on the {@link NumberPickerButton}
* to inform us when the long click has ended.
*/
public boolean onLongClick(View v) {
/* The text view may still have focus so clear it's focus which will
* trigger the on focus changed and any typed values to be pulled.
*/
mText.clearFocus();
if (R.id.increment == v.getId()) {
mIncrement = true;
mHandler.post(mRunnable);
} else if (R.id.decrement == v.getId()) {
mDecrement = true;
mHandler.post(mRunnable);
}
return true;
}
public void cancelIncrement() {
mIncrement = false;
}
public void cancelDecrement() {
mDecrement = false;
}
private static final char[] DIGIT_CHARACTERS = new char[] {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'
};
private NumberPickerButton mIncrementButton;
private NumberPickerButton mDecrementButton;
private class NumberPickerInputFilter implements InputFilter {
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
if (mDisplayedValues == null) {
return mNumberInputFilter.filter(source, start, end, dest, dstart, dend);
}
CharSequence filtered = String.valueOf(source.subSequence(start, end));
String result = String.valueOf(dest.subSequence(0, dstart))
+ filtered
+ dest.subSequence(dend, dest.length());
String str = String.valueOf(result).toLowerCase();
for (String val : mDisplayedValues) {
val = val.toLowerCase();
if (val.startsWith(str)) {
return filtered;
}
}
return "";
}
}
private class NumberRangeKeyListener extends NumberKeyListener {
// XXX This doesn't allow for range limits when controlled by a
// soft input method!
public int getInputType() {
return InputType.TYPE_CLASS_NUMBER;
}
@Override
protected char[] getAcceptedChars() {
return DIGIT_CHARACTERS;
}
@Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
CharSequence filtered = super.filter(source, start, end, dest, dstart, dend);
if (filtered == null) {
filtered = source.subSequence(start, end);
}
String result = String.valueOf(dest.subSequence(0, dstart))
+ filtered
+ dest.subSequence(dend, dest.length());
if ("".equals(result)) {
return result;
}
int val = getSelectedPos(result);
/* Ensure the user can't type in a value greater
* than the max allowed. We have to allow less than min
* as the user might want to delete some numbers
* and then type a new number.
*/
if (val > mEnd) {
return "";
} else {
return filtered;
}
}
}
private int getSelectedPos(String str) {
if (mDisplayedValues == null) {
return Integer.parseInt(str);
} else {
for (int i = 0; i < mDisplayedValues.length; i++) {
/* Don't force the user to type in jan when ja will do */
str = str.toLowerCase();
if (mDisplayedValues[i].toLowerCase().startsWith(str)) {
return mStart + i;
}
}
/* The user might have typed in a number into the month field i.e.
* 10 instead of OCT so support that too.
*/
try {
return Integer.parseInt(str);
} catch (NumberFormatException e) {
/* Ignore as if it's not a number we don't care */
}
}
return mStart;
}
/**
* @return the current value.
*/
public int getCurrent() {
return mCurrent;
}
} | Java |
/**
* Kitchen Timer
* Copyright (C) 2010 Roberto Leinardi
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.leinardi.kitchentimer.customviews;
import com.leinardi.kitchentimer.R;
import com.leinardi.kitchentimer.utils.Utils;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.res.TypedArray;
import android.preference.DialogPreference;
import android.util.AttributeSet;
public class MyDialogPreference extends DialogPreference {
Context mContext;
String fileName;
public MyDialogPreference(Context context, AttributeSet attrs) {
super(context, attrs);
mContext= context;
TypedArray a = mContext.obtainStyledAttributes(attrs, R.styleable.MyDialogPreference);
fileName = a.getString(R.styleable.MyDialogPreference_fileName);
}
protected void onPrepareDialogBuilder(Builder builder) {
builder.setView(Utils.dialogWebView(mContext, fileName));
}
}
| Java |
/**
* Kitchen Timer
* Copyright (C) 2010 Roberto Leinardi
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.leinardi.kitchentimer.utils;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import com.leinardi.kitchentimer.R;
import com.leinardi.kitchentimer.customtypes.Food;
import com.leinardi.kitchentimer.customtypes.Food.FoodMetaData;
import com.leinardi.kitchentimer.database.DbTool;
import com.leinardi.kitchentimer.misc.Constants;
import com.leinardi.kitchentimer.misc.Log;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.view.View;
import android.webkit.WebView;
import au.com.bytecode.opencsv.CSVReader;
import au.com.bytecode.opencsv.CSVWriter;
public class Utils {
/**
*
* @param totalSeconds
* @param timer
* @return
*/
public static String formatTime(long totalSeconds, int timer) {
if (timer == 0) {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT+0"));
return sdf.format(new Date(totalSeconds * 1000));
} else {
String seconds = Integer.toString((int) (totalSeconds % 60));
String minutes = Integer.toString((int) (totalSeconds / 60));
if (seconds.length() < 2) {
seconds = "0" + seconds;
}
if (minutes.length() < 2) {
minutes = "0" + minutes;
}
return minutes + ":" + seconds;
}
}
public static float dp2px(int dip, Context context){
float scale = context.getResources().getDisplayMetrics().density;
return dip * scale + 0.5f;
}
public static View dialogWebView(Context context, String fileName) {
View view = View.inflate(context, R.layout.dialog_webview, null);
// TextView textView = (TextView) view.findViewById(R.id.message);
// textView.setMovementMethod(LinkMovementMethod.getInstance());
// CharSequence cs = readTextFile(context, fileName);
//
// SpannableString s = new SpannableString(Html.fromHtml(cs.toString()));
// Linkify.addLinks(s, Linkify.WEB_URLS | Linkify.EMAIL_ADDRESSES);
// textView.setText(s);
WebView web = (WebView) view.findViewById(R.id.wv_dialog);
web.loadUrl("file:///android_asset/"+fileName);
return view;
}
public static CharSequence readTextFile(Context context, String fileName) {
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(context.getAssets().open(fileName)));
String line;
StringBuilder buffer = new StringBuilder();
while ((line = in.readLine()) != null) buffer.append(line).append('\n');
return buffer;
} catch (IOException e) {
Log.e("readTextFile", "Error readind file " + fileName, e);
return "";
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// Ignore
}
}
}
}
public static boolean exportCSV(Context context, Cursor cursor) {
if( cursor.getCount()==0) return true;
// An array to hold the rows that will be written to the CSV file.
final int rowLenght = FoodMetaData.COLUMNS.length-1;
String[] row = new String[rowLenght];
System.arraycopy(FoodMetaData.COLUMNS, 1, row, 0, rowLenght);
CSVWriter writer = null;
boolean success = false;
try {
writer = new CSVWriter(new FileWriter(Constants.CSV_FILE));
// Write descriptive headers.
writer.writeNext(row);
int nameIndex = cursor.getColumnIndex(FoodMetaData.NAME);
int hoursIndex = cursor.getColumnIndex(FoodMetaData.HOURS);
int minutesIndex = cursor.getColumnIndex(FoodMetaData.MINUTES);
int secondsIndex = cursor.getColumnIndex(FoodMetaData.SECONDS);
if(cursor.requery()){
while (cursor.moveToNext()) {
row[0] = cursor.getString(nameIndex);
row[1] = cursor.getInt(hoursIndex)+"";
row[2] = cursor.getInt(minutesIndex)+"";
row[3] = cursor.getInt(secondsIndex)+"";
// NOTE: writeNext() handles nulls in row[] gracefully.
writer.writeNext(row);
}
}
success = true;
} catch (Exception ex) {
Log.e("Utils", "exportCSV", ex);
} finally {
try {
if (null != writer) writer.close();
} catch (IOException ex) {
}
}
return success;
}
public static boolean importCSV(Context context, DbTool dbTool) {
CSVReader reader = null;
Food food = new Food();
try {
reader = new CSVReader(new FileReader(Constants.CSV_FILE));
} catch (FileNotFoundException ex) {
//Log.e("Utils", "importCSV - File Not Found", ex);
return false;
}
try {
// Use the first line to determine the type of csv file. Secrets will
// output 5 columns, with the names as used in the exportSecrets()
// function. OI Safe 1.1.0 is also detected.
reader.readNext();
// Read all the rest of the lines as secrets.
String[] row;
while ((row = reader.readNext()) != null) {
if(row.length==4){
food.name = row[0];
try{
food.hours = Integer.parseInt(row[1]);
food.minutes = Integer.parseInt(row[2]);
food.seconds = Integer.parseInt(row[3]);
}catch(NumberFormatException nFE) {
food.hours = 0;
food.minutes = 0;
food.seconds = 0;
Log.e("importCSV", "NumberFormat Error", nFE);
}
dbTool.open();
dbTool.insert(food);
}
}
} catch (Exception ex) {
Log.e("Utils", "importCSV", ex);
} finally {
try {
if (null != reader) reader.close();
} catch (IOException ex) {
}
}
return true;
}
public static boolean isSdPresent() {
return Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
}
public static void donate(Context mContext) {
Intent intent = new Intent( Intent.ACTION_VIEW,
Uri.parse("market://search?q=Donation%20pub:%22Roberto%20Leinardi%22") );
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
}
}
| Java |
package com.leinardi.kitchentimer.ui;
import com.leinardi.kitchentimer.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
public class InfoActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.info);
WebView web = (WebView) findViewById(R.id.wv_info);
web.loadUrl("file:///android_asset/" + getString(R.string.info_filename));
findViewById(R.id.btn_back).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
}
| Java |
/**
* Kitchen Timer
* Copyright (C) 2010 Roberto Leinardi
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.leinardi.kitchentimer.ui;
import com.leinardi.kitchentimer.R;
import com.leinardi.kitchentimer.misc.Log;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.Preference.OnPreferenceClickListener;
public class ConfigActivity extends PreferenceActivity {
private final String REPORT_A_BUG_URL = "http://code.google.com/p/kitchentimer/issues/list";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource (R.xml.preferences);
String version;
try {
PackageInfo pi = getPackageManager().getPackageInfo(getPackageName(), 0);
version = pi.versionName;
} catch (NameNotFoundException e) {
Log.e(MainActivity.TAG, "Package name not found", e);
version = getString(R.string.pref_info_version_error);
}
findPreference(getString(R.string.pref_info_version_key)).setSummary(version);
Preference reportABug = findPreference(getString(R.string.pref_report_a_bug_key));
reportABug.setOnPreferenceClickListener(new OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference preference) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(REPORT_A_BUG_URL));
startActivity(browserIntent);
return false;
}
});
}
} | Java |
/**
* Kitchen Timer
* Copyright (C) 2010 Roberto Leinardi
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.leinardi.kitchentimer.ui;
import com.leinardi.kitchentimer.R;
import com.leinardi.kitchentimer.customtypes.Food;
import com.leinardi.kitchentimer.customtypes.Food.FoodMetaData;
import com.leinardi.kitchentimer.customviews.NumberPicker;
import com.leinardi.kitchentimer.database.DbTool;
import com.leinardi.kitchentimer.misc.Constants;
import com.leinardi.kitchentimer.utils.Utils;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;
public class PresetsActivity extends ListActivity {
// Identificatore delle voci del Menu Contestuale
private final static int DELETE_MENU_OPTION = 1;
private final static int UPDATE_MENU_OPTION = 2;
private DbTool dbTool;
private Cursor cursor;
private FoodCursorAdapter myAdapter;
private NumberPicker npHours;
private NumberPicker npMinutes;
private NumberPicker npSeconds;
private EditText etPresetName;
private Button btnSave;
private Food food;
private boolean isEdit;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.presets);
dbTool = new DbTool(getApplicationContext());
dbTool.open();
cursor = dbTool.getRecords();
startManagingCursor(cursor);
myAdapter=new FoodCursorAdapter(cursor);
setListAdapter(myAdapter);
registerForContextMenu(getListView());
getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v,int position, long id) {
Cursor tmpCursor = dbTool.query(id);
startManagingCursor(tmpCursor);
if (tmpCursor.moveToNext()) {
food.hours = tmpCursor.getInt(tmpCursor.getColumnIndex(FoodMetaData.HOURS));
food.minutes = tmpCursor.getInt(tmpCursor.getColumnIndex(FoodMetaData.MINUTES));
food.seconds = tmpCursor.getInt(tmpCursor.getColumnIndex(FoodMetaData.SECONDS));
food.name = tmpCursor.getString(tmpCursor.getColumnIndex(FoodMetaData.NAME));
//System.out.println(food.name + "=" + food.hours + ":" + food.minutes + ":" + food.seconds);
Bundle bundle = new Bundle();
bundle.putInt("hours", food.hours);
bundle.putInt("minutes", food.minutes);
bundle.putInt("seconds", food.seconds);
bundle.putString("name", food.name);
Intent intent = new Intent();
intent.putExtras(bundle);
setResult(RESULT_OK, intent);
finish();
}
}
});
isEdit=false;
food = new Food();
initWidgets();
}
/** Get references to UI widgets and initialize them if needed */
private void initWidgets() {
npHours = (NumberPicker)findViewById(R.id.npHours);
npMinutes = (NumberPicker)findViewById(R.id.npMinutes);
npSeconds= (NumberPicker)findViewById(R.id.npSeconds);
npHours.setFormatter(NumberPicker.TWO_DIGIT_FORMATTER);
npMinutes.setFormatter(NumberPicker.TWO_DIGIT_FORMATTER);
npSeconds.setFormatter(NumberPicker.TWO_DIGIT_FORMATTER);
npHours.setRange(0, 23);
npMinutes.setRange(0, 59);
npSeconds.setRange(0, 59);
btnSave = (Button)findViewById(R.id.btnSave);
etPresetName = (EditText)findViewById(R.id.etPresetName);
btnSave.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
btnSave.requestFocusFromTouch();
food.name = etPresetName.getText().toString();
food.hours = npHours.getCurrent();
food.minutes = npMinutes.getCurrent();
food.seconds = npSeconds.getCurrent();
boolean validato=true;
StringBuffer validationFailMessage = new StringBuffer();
if(!food.isTimeSet()){
validationFailMessage.append(getString(R.string.error_time));
validato=false;
}
if(!food.isNameSet()){
if (validato==false) validationFailMessage.append("\n");
validationFailMessage.append(getString(R.string.error_name));
validato=false;
}
if(!validato){
Toast.makeText(getApplicationContext(), validationFailMessage.toString(), Toast.LENGTH_LONG).show();
}else{
if(isEdit){
dbTool.open();
dbTool.update(food);
isEdit=false;
btnSave.setText(R.string.save);
}else{
dbTool.open();
dbTool.insert(food);
}
updateListView();
etPresetName.setText("");
// Hide Soft Keyboard
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(etPresetName.getWindowToken(), 0);
}
}
});
}
class FoodCursorAdapter extends BaseAdapter {
Cursor c;
LayoutInflater mInflater;
public FoodCursorAdapter(Cursor c) {
this.c = c;
this.mInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return c.getCount();
}
@Override
public Object getItem(int position) {
// Auto-generated method stub
return null;
}
@Override
public long getItemId(int position) {
c.moveToPosition(position);
return c.getInt(c.getColumnIndex(Food.FoodMetaData.ID));
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row_layout, null);
}
TextView tvName = (TextView) convertView.findViewById(R.id.name);
TextView tvTime = (TextView) convertView.findViewById(R.id.time);
if (c.moveToFirst()) {
StringBuffer time = new StringBuffer();
c.moveToPosition(position);
food.name = c.getString(c.getColumnIndex(Food.FoodMetaData.NAME));
food.hours = c.getInt(c.getColumnIndex(Food.FoodMetaData.HOURS));
food.minutes =c.getInt(c.getColumnIndex(Food.FoodMetaData.MINUTES));
food.seconds =c.getInt(c.getColumnIndex(Food.FoodMetaData.SECONDS));
String str;
if(food.hours != 0){
str = food.hours+"";
if (str.length() < 2) str = "0" + food.hours;
time.append(str+":");
}
str = food.minutes+"";
if (str.length() < 2) str = "0" + food.minutes;
time.append(str+":");
str = food.seconds+"";
if (str.length() < 2) str = "0" + food.seconds;
time.append(str);
tvName.setText(food.name);
tvTime.setText(time.toString());
}
return convertView;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
dbTool.close();
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
int group = Menu.FIRST;
menu.add(group, UPDATE_MENU_OPTION, Menu.FIRST, R.string.edit);
menu.add(group, DELETE_MENU_OPTION, Menu.FIRST + 1, R.string.delete);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
long examId = info.id;
switch (item.getItemId()) {
case UPDATE_MENU_OPTION:
Cursor tmpCursor = dbTool.query(examId);
if (tmpCursor.moveToNext()) {
food.id = examId;
food.hours = tmpCursor.getInt(tmpCursor.getColumnIndex(FoodMetaData.HOURS));
food.minutes = tmpCursor.getInt(tmpCursor.getColumnIndex(FoodMetaData.MINUTES));
food.seconds = tmpCursor.getInt(tmpCursor.getColumnIndex(FoodMetaData.SECONDS));
food.name = tmpCursor.getString(tmpCursor.getColumnIndex(FoodMetaData.NAME));
npHours.setCurrent(food.hours);
npMinutes.setCurrent(food.minutes);
npSeconds.setCurrent(food.seconds);
etPresetName.setText(food.name);
isEdit=true;
btnSave.setText(R.string.edit);
}
return true;
case DELETE_MENU_OPTION:
dbTool.open();
dbTool.delete(examId);
updateListView();
return true;
default:
return super.onContextItemSelected(item);
}
}
/*
* Metodo di utilità che permettedi aggiornare il contenuto della ListView
*/
private void updateListView() {
cursor.requery();
myAdapter.notifyDataSetChanged();
}
/*
* (non-Javadoc)
*
* @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.presets_menu, menu);
return true;
}
/*
* (non-Javadoc)
*
* @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_import:
if(Utils.isSdPresent()){
if(!Utils.importCSV(this, dbTool)){
Toast.makeText(getApplicationContext(), getString(R.string.unable_to_read_file) + " " + Constants.CSV_FILENAME, Toast.LENGTH_LONG)
.show();
}
updateListView();
}else{
Toast.makeText(getApplicationContext(), getString(R.string.sd_not_mounted), Toast.LENGTH_LONG)
.show();
}
return true;
case R.id.menu_export:
if(cursor.getCount()>0){
if(Utils.isSdPresent()){
if(Utils.exportCSV(this, cursor)){
Toast.makeText(getApplicationContext(), getString(R.string.presets_saved) + " " + Constants.CSV_FILENAME, Toast.LENGTH_LONG)
.show();
}else{
Toast.makeText(getApplicationContext(), getString(R.string.presets_export_error), Toast.LENGTH_LONG)
.show();
}
}else{
Toast.makeText(getApplicationContext(), getString(R.string.sd_not_mounted), Toast.LENGTH_LONG)
.show();
}
}else{
Toast.makeText(getApplicationContext(), getString(R.string.preset_list_empty), Toast.LENGTH_LONG)
.show();
}
return true;
case R.id.menu_truncate:
new AlertDialog.Builder(this)
.setIcon(R.drawable.ic_dialog_alert)
.setTitle(R.string.delete_preset_title)
.setMessage(R.string.delete_preset_message)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dbTool.open();
dbTool.truncate();
updateListView();
}
})
.setNegativeButton(R.string.cancel, null)
.show();
return true;
}
return super.onOptionsItemSelected(item);
}
}
| Java |
/**
* Kitchen Timer
* Copyright (C) 2010 Roberto Leinardi
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.leinardi.kitchentimer.ui;
/*
* TODO:
* Opzione per far suonare anche quando silenziato
* Rendere modificabile il nome dei Timers
*/
import com.leinardi.kitchentimer.R;
import com.leinardi.kitchentimer.customviews.NumberPicker;
import com.leinardi.kitchentimer.misc.Changelog;
import com.leinardi.kitchentimer.misc.Constants;
import com.leinardi.kitchentimer.misc.Eula;
import com.leinardi.kitchentimer.utils.Utils;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.ColorStateList;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.text.InputFilter;
import android.text.InputType;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
public final static String TAG = "MainActivity";
private final static int[] TIMERS = { 0, 1, 2 };
private PowerManager.WakeLock mWakeLock = null;
private AlarmManager mAlarmManager;
private PendingIntent[] mPendingIntent;
private Handler mHandler = new Handler();
NotificationManager mNotificationManager;
private SharedPreferences mPrefs;
private MyRunnable[] countdownRunnable;
private boolean[] timerIsRunning;
private int[] timerSeconds;
private long[] timerStartTime;
private String[] timerDefaultName;
private NumberPicker npHours;
private NumberPicker npMinutes;
private NumberPicker npSeconds;
private Button[] btnTimer;
private TextView[] tvTimer;
private TextView[] tvTimerLabel;
private String presetName;
ColorStateList timerDefaultColor;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Eula.show(this);
Changelog.show(this);
timerSeconds = new int[Constants.NUM_TIMERS];
timerStartTime = new long[Constants.NUM_TIMERS];
timerIsRunning = new boolean[Constants.NUM_TIMERS];
timerDefaultName = new String[Constants.NUM_TIMERS];
timerDefaultName[0]=getString(R.string.timer1);
timerDefaultName[1]=getString(R.string.timer2);
timerDefaultName[2]=getString(R.string.timer3);
mPendingIntent = new PendingIntent[Constants.NUM_TIMERS];
mAlarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, TAG);
mWakeLock.setReferenceCounted(false);
countdownRunnable = new MyRunnable[Constants.NUM_TIMERS];
for (int timer = 0; timer < Constants.NUM_TIMERS; timer++) {
timerIsRunning[timer] = false;
countdownRunnable[timer] = new MyRunnable(timer);
Intent intent = new Intent(Constants.INTENT_TIMER_ENDED);
intent.putExtra(Constants.TIMER, timer);
// intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
mPendingIntent[timer] = PendingIntent.getBroadcast(this, timer,
intent, 0);
}
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
acquireWakeLock();
initWidgets();
if (mPrefs.getBoolean(getString(R.string.pref_show_tips_key), true)){
Toast toast = Toast.makeText(this, getString(R.string.tip1), Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP, 0, 0);
toast.show();
}
}
/** Get references to UI widgets and initialize them if needed */
private void initWidgets() {
npHours = (NumberPicker) findViewById(R.id.npHours);
npMinutes = (NumberPicker) findViewById(R.id.npMinutes);
npSeconds = (NumberPicker) findViewById(R.id.npSeconds);
npHours.setFormatter(NumberPicker.TWO_DIGIT_FORMATTER);
npMinutes.setFormatter(NumberPicker.TWO_DIGIT_FORMATTER);
npSeconds.setFormatter(NumberPicker.TWO_DIGIT_FORMATTER);
npHours.setRange(0, 23);
npMinutes.setRange(0, 59);
npSeconds.setRange(0, 59);
npHours.setSpeed(50);
npMinutes.setSpeed(50);
npSeconds.setSpeed(50);
npHours.setCurrent(mPrefs.getInt(Constants.PREF_HOURS, 0));
npMinutes.setCurrent(mPrefs.getInt(Constants.PREF_MINUTES, 0));
npSeconds.setCurrent(mPrefs.getInt(Constants.PREF_SECONDS, 0));
btnTimer = new Button[Constants.NUM_TIMERS];
btnTimer[0] = (Button) findViewById(R.id.btnTimer0);
btnTimer[1] = (Button) findViewById(R.id.btnTimer1);
btnTimer[2] = (Button) findViewById(R.id.btnTimer2);
tvTimer = new TextView[Constants.NUM_TIMERS];
tvTimer[0] = (TextView) this.findViewById(R.id.tvTimer0);
tvTimer[1] = (TextView) this.findViewById(R.id.tvTimer1);
tvTimer[2] = (TextView) this.findViewById(R.id.tvTimer2);
tvTimerLabel = new TextView[Constants.NUM_TIMERS];
tvTimerLabel[0] = (TextView) this.findViewById(R.id.tvTimer0_label);
tvTimerLabel[1] = (TextView) this.findViewById(R.id.tvTimer1_label);
tvTimerLabel[2] = (TextView) this.findViewById(R.id.tvTimer2_label);
timerDefaultColor = tvTimer[0].getTextColors();
for (int timer = 0; timer < Constants.NUM_TIMERS; timer++) {
tvTimerLabel[timer].setText(mPrefs.getString(Constants.PREF_TIMERS_NAMES[timer], timerDefaultName[timer]));
btnTimer[timer].setOnClickListener(this.clickListener);
tvTimerLabel[timer].setOnClickListener(this.clickListener);
tvTimer[timer].setOnClickListener(this.clickListener);
}
}
@Override
protected void onStop() {
super.onStop();
SharedPreferences.Editor editor = mPrefs.edit();
editor.putInt(Constants.PREF_HOURS, npHours.getCurrent());
editor.putInt(Constants.PREF_MINUTES, npMinutes.getCurrent());
editor.putInt(Constants.PREF_SECONDS, npSeconds.getCurrent());
editor.commit();
for (int timer = 0; timer < Constants.NUM_TIMERS; timer++) {
if (timerIsRunning[timer])
mHandler.removeCallbacks(countdownRunnable[timer]);
}
}
@Override
protected void onStart() {
super.onStart();
for (int timer = 0; timer < Constants.NUM_TIMERS; timer++) {
timerSeconds[timer] = mPrefs.getInt(Constants.PREF_TIMERS_SECONDS[timer], 0);
timerStartTime[timer] = mPrefs.getLong(Constants.PREF_START_TIMES[timer], 0L);
timerIsRunning[timer] = (timerStartTime[timer] != 0L);
startRunnable(timerIsRunning[timer], timer);
tvTimerLabel[timer].setText(mPrefs.getString(Constants.PREF_TIMERS_NAMES[timer], timerDefaultName[timer]));
}
}
@Override
public void onResume() {
super.onResume();
acquireWakeLock();
}
@Override
public void onPause() {
super.onPause();
releaseWakeLock();
}
private void acquireWakeLock() {
// It's okay to double-acquire this because we are not using it
// in reference-counted mode.
if (mPrefs.getBoolean(getString(R.string.pref_keep_screen_on_key), false))
mWakeLock.acquire();
}
private void releaseWakeLock() {
// Don't release the wake lock if it hasn't been created and acquired.
if (mWakeLock != null && mWakeLock.isHeld()) {
mWakeLock.release();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Constants.REQUEST_PRESETS) {
if (resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
npHours.setCurrent(extras.getInt("hours"));
npMinutes.setCurrent(extras.getInt("minutes"));
npSeconds.setCurrent(extras.getInt("seconds"));
presetName=extras.getString("name");
}
}
}
private OnClickListener clickListener = new OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.tvTimer0_label:
setTimerName(TIMERS[0]);
break;
case R.id.tvTimer1_label:
setTimerName(TIMERS[1]);
break;
case R.id.tvTimer2_label:
setTimerName(TIMERS[2]);
break;
case R.id.tvTimer0:
cancelTimeIsOverNotification(TIMERS[0]);
break;
case R.id.tvTimer1:
cancelTimeIsOverNotification(TIMERS[1]);
break;
case R.id.tvTimer2:
cancelTimeIsOverNotification(TIMERS[2]);
break;
case R.id.btnTimer0:
startTimer(TIMERS[0]);
break;
case R.id.btnTimer1:
startTimer(TIMERS[1]);
break;
case R.id.btnTimer2:
startTimer(TIMERS[2]);
break;
}
}
};
private void setTimerName(final int timer) {
AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
alt_bld.setTitle(R.string.edit_timer_name);
alt_bld.setIcon(R.drawable.icon);
FrameLayout frameLayout = new FrameLayout(this);
frameLayout.setPadding((int)Utils.dp2px(10, this), 0, (int)Utils.dp2px(10, this), 0);
final EditText etTimerName = new EditText(this);
etTimerName.setHint(R.string.timer_name);
etTimerName.setMaxLines(1);
etTimerName.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
etTimerName.setFilters(new InputFilter[] {
new InputFilter.LengthFilter(50) });
etTimerName.setText(mPrefs.getString(Constants.PREF_TIMERS_NAMES[timer], timerDefaultName[timer]));
frameLayout.addView(etTimerName);
alt_bld.setView(frameLayout);
alt_bld.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String timerName = (etTimerName.getText().toString());
if(timerName.length()>0){
tvTimerLabel[timer].setText(timerName);
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString(Constants.PREF_TIMERS_NAMES[timer], timerName);
editor.commit();
}
}
});
alt_bld.setNeutralButton(R.string.default_text, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
tvTimerLabel[timer].setText(timerDefaultName[timer]);
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString(Constants.PREF_TIMERS_NAMES[timer], timerDefaultName[timer]);
editor.commit();
}
});
alt_bld.setNegativeButton(R.string.cancel, null);
AlertDialog alert = alt_bld.create();
alert.show();
}
private void startTimer(int timer) {
if (mNotificationManager != null) {
mNotificationManager.cancel(timer + 10);
}
mPendingIntent[timer].cancel();
Intent intent = new Intent(Constants.INTENT_TIMER_ENDED);
intent.putExtra(Constants.TIMER, timer);
SharedPreferences.Editor editor = mPrefs.edit();
if(presetName!=null){
intent.putExtra(Constants.TIMER_NAME, presetName);
tvTimerLabel[timer].setText(presetName);
editor.putString(Constants.PREF_TIMERS_NAMES[timer], presetName);
}else{
intent.putExtra(Constants.TIMER_NAME, mPrefs.getString(Constants.PREF_TIMERS_NAMES[timer], timerDefaultName[timer]));
}
editor.commit();
mPendingIntent[timer] = PendingIntent.getBroadcast(this, timer, intent, 0);
btnTimer[timer].requestFocusFromTouch();
if (timerIsRunning[timer])
setTimerState(false, timer);
else {
timerSeconds[timer] = npHours.getCurrent() * 3600
+ npMinutes.getCurrent() * 60 + npSeconds.getCurrent();
if (timerSeconds[timer] > 0){
setTimerState(true, timer);
if (mPrefs.getBoolean(getString(R.string.pref_show_tips_key), true)){
Toast toast = Toast.makeText(this, getString(R.string.tip1), Toast.LENGTH_LONG);
toast.setGravity(Gravity.TOP, 0, 0);
toast.show();
}
}else{
Toast.makeText(this, getString(R.string.error_time), Toast.LENGTH_LONG).show();
}
}
}
private void cancelTimeIsOverNotification(int timer) {
if (!timerIsRunning[timer]) {
tvTimer[timer].setTextColor(timerDefaultColor);
tvTimer[timer].setShadowLayer(0f, 0f, 0f, 0);
if (mNotificationManager != null) {
mNotificationManager.cancel(timer + 10);
}
}
}
/**
*
* @author jd
*
*/
class MyRunnable implements Runnable {
private int timer;
public MyRunnable(int timer) {
this.timer = timer;
}
@Override
public void run() {
long remainingSeconds = timerSeconds[timer] - (SystemClock.elapsedRealtime() - timerStartTime[timer]) / 1000;
tvTimer[timer].setText(Utils.formatTime(Math.max(remainingSeconds, 0L), timer));
if (remainingSeconds <= 0) {
setTimerState(false, timer);
if (mPrefs.getBoolean(getString(R.string.pref_clear_timer_label_key), false)){
tvTimerLabel[timer].setText(timerDefaultName[timer]);
}
tvTimer[timer].setTextColor(getResources().getColor(R.color.indian_red_1));
tvTimer[timer].setShadowLayer(Utils.dp2px(7, getApplicationContext()), 0f, 0f, getResources().getColor(R.color.indian_red_1));
}
if (timerIsRunning[timer]) {
mHandler.postDelayed(this, 1000);
}
}
}
/**
* Sets the timer on or off
*
* @param timer
*/
private void setTimerState(boolean state, int timer) {
timerIsRunning[timer] = state;
setAlarmState(state, timer);
startRunnable(state, timer);
sendTimerIsRunningNotification(state, timer);
}
/**
* Sets the alarm on or off This makes use of the alarm system service
*
* @param timer
*/
private void setAlarmState(boolean state, int timer) {
// Log.d(TAG, String.format("SetAlarmOn(on=%b)", on));
if (state) {
timerStartTime[timer] = SystemClock.elapsedRealtime();
mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock
.elapsedRealtime()
+ timerSeconds[timer] * 1000, mPendingIntent[timer]);
} else {
timerStartTime[timer] = 0L;
mAlarmManager.cancel(mPendingIntent[timer]);
}
presetName=null;
SharedPreferences.Editor editor = mPrefs.edit();
editor.putInt(Constants.PREF_TIMERS_SECONDS[timer], timerSeconds[timer]);
editor.putLong(Constants.PREF_START_TIMES[timer], timerStartTime[timer]);
editor.commit();
}
/**
*
* @param start
* @param timer
*/
private void startRunnable(boolean start, int timer) {
// Log.d(TAG, String.format("SetCountDownVisible(visible=%b)",
// visible));
if (start) {
tvTimer[timer].setTextColor(getResources().getColor(R.color.white));
tvTimer[timer].setShadowLayer(Utils.dp2px(4, this), 0f, 0f, getResources().getColor(R.color.white));
btnTimer[timer].setText(R.string.stop);
mHandler.removeCallbacks(countdownRunnable[timer]);
countdownRunnable[timer].run();
} else {
tvTimer[timer].setTextColor(timerDefaultColor);
tvTimer[timer].setShadowLayer(0f, 0f, 0f, 0);
tvTimer[timer].setText(timer == 0 ? R.string.sixzeros
: R.string.fourzeros);
btnTimer[timer].setText(R.string.start);
mHandler.removeCallbacks(countdownRunnable[timer]);
}
}
/**
*
* @param running
* @param timer
*/
private void sendTimerIsRunningNotification(boolean running, int timer) {
if (running) {
int icon = R.drawable.stat_notify_alarm;
CharSequence mTickerText = getString(R.string.timer_started);
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, mTickerText,
when);
Context context = getApplicationContext();
CharSequence mContentTitle = getString(R.string.app_name);
CharSequence mContentText = getString(R.string.click_to_open);
Intent clickIntent = new Intent(this, MainActivity.class);
clickIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_SINGLE_TOP
| Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
clickIntent, PendingIntent.FLAG_UPDATE_CURRENT);
notification.setLatestEventInfo(context, mContentTitle,
mContentText, contentIntent);
notification.ledARGB = 0x00000000;
notification.ledOnMS = 0;
notification.ledOffMS = 0;
notification.flags |= Notification.FLAG_SHOW_LIGHTS;
notification.flags |= Notification.FLAG_ONGOING_EVENT;
notification.flags |= Notification.FLAG_NO_CLEAR;
mNotificationManager.notify(Constants.APP_NOTIF_ID, notification);
} else {
boolean thereAreTimersRunning = false;
for (int i = 0; i < timerIsRunning.length; i++) {
thereAreTimersRunning = thereAreTimersRunning || timerIsRunning[i];
}
if (!thereAreTimersRunning) {
mNotificationManager.cancel(Constants.APP_NOTIF_ID);
}
}
}
/*
* (non-Javadoc)
*
* @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
/*
* (non-Javadoc)
*
* @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent;
AlertDialog.Builder alt_bld;
AlertDialog alert;
switch (item.getItemId()) {
case R.id.menu_info:
intent = new Intent(this, InfoActivity.class);
startActivity(intent);
return true;
case R.id.menu_donate:
alt_bld = new AlertDialog.Builder(this);
alt_bld.setTitle(R.string.pref_donate);
alt_bld.setMessage(R.string.donate_message);
alt_bld.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Utils.donate(getApplicationContext());
}
});
alt_bld.setNegativeButton(R.string.no, null);
alert = alt_bld.create();
alert.show();
return true;
case R.id.menu_presets:
intent = new Intent(this, PresetsActivity.class);
startActivityForResult(intent, Constants.REQUEST_PRESETS);
return true;
case R.id.menu_preferences:
intent = new Intent(this, ConfigActivity.class);
startActivity(intent);
return true;
case R.id.menu_exit:
alt_bld = new AlertDialog.Builder(this);
alt_bld.setTitle(R.string.exit_title);
alt_bld.setIcon(R.drawable.ic_dialog_alert);
alt_bld.setMessage(R.string.exit_message);
alt_bld.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
boolean flag = false;
for (int i = 0; i < timerIsRunning.length; i++) {
if (timerIsRunning[i]) {
mAlarmManager.cancel(mPendingIntent[i]);
mHandler.removeCallbacks(countdownRunnable[i]);
flag = true;
}
SharedPreferences.Editor editor = mPrefs.edit();
editor.putInt(Constants.PREF_TIMERS_SECONDS[i], 0);
editor.putLong(Constants.PREF_START_TIMES[i], 0L);
editor.commit();
timerSeconds[i] = 0;
timerStartTime[i] = 0L;
timerIsRunning[i] = false;
}
if (flag) {
mNotificationManager.cancel(Constants.APP_NOTIF_ID);
}
finish();
}
});
alt_bld.setNeutralButton(R.string.cancel, null);
alt_bld.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
finish();
}
});
alert = alt_bld.create();
alert.show();
return true;
}
return super.onOptionsItemSelected(item);
}
} | Java |
package au.com.bytecode.opencsv;
/**
Copyright 2005 Bytecode Pty Ltd.
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.
*/
import java.io.Closeable;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
/**
* A very simple CSV writer released under a commercial-friendly license.
*
* @author Glen Smith
*
*/
public class CSVWriter implements Closeable {
public static final int INITIAL_STRING_SIZE = 128;
private Writer rawWriter;
private PrintWriter pw;
private char separator;
private char quotechar;
private char escapechar;
private String lineEnd;
/** The character used for escaping quotes. */
public static final char DEFAULT_ESCAPE_CHARACTER = '"';
/** The default separator to use if none is supplied to the constructor. */
public static final char DEFAULT_SEPARATOR = ',';
/**
* The default quote character to use if none is supplied to the
* constructor.
*/
public static final char DEFAULT_QUOTE_CHARACTER = '"';
/** The quote constant to use when you wish to suppress all quoting. */
public static final char NO_QUOTE_CHARACTER = '\u0000';
/** The escape constant to use when you wish to suppress all escaping. */
public static final char NO_ESCAPE_CHARACTER = '\u0000';
/** Default line terminator uses platform encoding. */
public static final String DEFAULT_LINE_END = "\n";
/**
* Constructs CSVWriter using a comma for the separator.
*
* @param writer
* the writer to an underlying CSV source.
*/
public CSVWriter(Writer writer) {
this(writer, DEFAULT_SEPARATOR);
}
/**
* Constructs CSVWriter with supplied separator.
*
* @param writer
* the writer to an underlying CSV source.
* @param separator
* the delimiter to use for separating entries.
*/
public CSVWriter(Writer writer, char separator) {
this(writer, separator, DEFAULT_QUOTE_CHARACTER);
}
/**
* Constructs CSVWriter with supplied separator and quote char.
*
* @param writer
* the writer to an underlying CSV source.
* @param separator
* the delimiter to use for separating entries
* @param quotechar
* the character to use for quoted elements
*/
public CSVWriter(Writer writer, char separator, char quotechar) {
this(writer, separator, quotechar, DEFAULT_ESCAPE_CHARACTER);
}
/**
* Constructs CSVWriter with supplied separator and quote char.
*
* @param writer
* the writer to an underlying CSV source.
* @param separator
* the delimiter to use for separating entries
* @param quotechar
* the character to use for quoted elements
* @param escapechar
* the character to use for escaping quotechars or escapechars
*/
public CSVWriter(Writer writer, char separator, char quotechar, char escapechar) {
this(writer, separator, quotechar, escapechar, DEFAULT_LINE_END);
}
/**
* Constructs CSVWriter with supplied separator and quote char.
*
* @param writer
* the writer to an underlying CSV source.
* @param separator
* the delimiter to use for separating entries
* @param quotechar
* the character to use for quoted elements
* @param lineEnd
* the line feed terminator to use
*/
public CSVWriter(Writer writer, char separator, char quotechar, String lineEnd) {
this(writer, separator, quotechar, DEFAULT_ESCAPE_CHARACTER, lineEnd);
}
/**
* Constructs CSVWriter with supplied separator, quote char, escape char and line ending.
*
* @param writer
* the writer to an underlying CSV source.
* @param separator
* the delimiter to use for separating entries
* @param quotechar
* the character to use for quoted elements
* @param escapechar
* the character to use for escaping quotechars or escapechars
* @param lineEnd
* the line feed terminator to use
*/
public CSVWriter(Writer writer, char separator, char quotechar, char escapechar, String lineEnd) {
this.rawWriter = writer;
this.pw = new PrintWriter(writer);
this.separator = separator;
this.quotechar = quotechar;
this.escapechar = escapechar;
this.lineEnd = lineEnd;
}
/**
* Writes the next line to the file.
*
* @param nextLine
* a string array with each comma-separated element as a separate
* entry.
*/
public void writeNext(String[] nextLine) {
if (nextLine == null)
return;
StringBuilder sb = new StringBuilder(INITIAL_STRING_SIZE);
for (int i = 0; i < nextLine.length; i++) {
if (i != 0) {
sb.append(separator);
}
String nextElement = nextLine[i];
if (nextElement == null)
continue;
if (quotechar != NO_QUOTE_CHARACTER)
sb.append(quotechar);
sb.append(stringContainsSpecialCharacters(nextElement) ? processLine(nextElement) : nextElement);
if (quotechar != NO_QUOTE_CHARACTER)
sb.append(quotechar);
}
sb.append(lineEnd);
pw.write(sb.toString());
}
private boolean stringContainsSpecialCharacters(String line) {
return line.indexOf(quotechar) != -1 || line.indexOf(escapechar) != -1;
}
private StringBuilder processLine(String nextElement)
{
StringBuilder sb = new StringBuilder(INITIAL_STRING_SIZE);
for (int j = 0; j < nextElement.length(); j++) {
char nextChar = nextElement.charAt(j);
if (escapechar != NO_ESCAPE_CHARACTER && nextChar == quotechar) {
sb.append(escapechar).append(nextChar);
} else if (escapechar != NO_ESCAPE_CHARACTER && nextChar == escapechar) {
sb.append(escapechar).append(nextChar);
} else {
sb.append(nextChar);
}
}
return sb;
}
/**
* Flush underlying stream to writer.
*
* @throws IOException if bad things happen
*/
public void flush() throws IOException {
pw.flush();
}
/**
* Close the underlying stream writer flushing any buffered content.
*
* @throws IOException if bad things happen
*
*/
public void close() throws IOException {
pw.flush();
pw.close();
rawWriter.close();
}
}
| Java |
package au.com.bytecode.opencsv;
/**
Copyright 2005 Bytecode Pty Ltd.
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.
*/
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
/**
* A very simple CSV reader released under a commercial-friendly license.
*
* @author Glen Smith
*
*/
public class CSVReader implements Closeable {
private BufferedReader br;
private boolean hasNext = true;
private final char separator;
private final char quotechar;
private final char escape;
private int skipLines;
private boolean linesSkiped;
/** The default separator to use if none is supplied to the constructor. */
public static final char DEFAULT_SEPARATOR = ',';
public static final int INITIAL_READ_SIZE = 64;
/**
* The default quote character to use if none is supplied to the
* constructor.
*/
public static final char DEFAULT_QUOTE_CHARACTER = '"';
/**
* The default escape character to use if none is supplied to the
* constructor.
*/
public static final char DEFAULT_ESCAPE_CHARACTER = '\\';
/**
* The default line to start reading.
*/
public static final int DEFAULT_SKIP_LINES = 0;
/**
* Constructs CSVReader using a comma for the separator.
*
* @param reader
* the reader to an underlying CSV source.
*/
public CSVReader(Reader reader) {
this(reader, DEFAULT_SEPARATOR);
}
/**
* Constructs CSVReader with supplied separator.
*
* @param reader
* the reader to an underlying CSV source.
* @param separator
* the delimiter to use for separating entries.
*/
public CSVReader(Reader reader, char separator) {
this(reader, separator, DEFAULT_QUOTE_CHARACTER, DEFAULT_ESCAPE_CHARACTER);
}
/**
* Constructs CSVReader with supplied separator and quote char.
*
* @param reader
* the reader to an underlying CSV source.
* @param separator
* the delimiter to use for separating entries
* @param quotechar
* the character to use for quoted elements
*/
public CSVReader(Reader reader, char separator, char quotechar) {
this(reader, separator, quotechar, DEFAULT_ESCAPE_CHARACTER, DEFAULT_SKIP_LINES);
}
public CSVReader(Reader reader, char separator,
char quotechar, char escape) {
this(reader, separator, quotechar, escape, DEFAULT_SKIP_LINES);
}
/**
* Constructs CSVReader with supplied separator and quote char.
*
* @param reader
* the reader to an underlying CSV source.
* @param separator
* the delimiter to use for separating entries
* @param quotechar
* the character to use for quoted elements
* @param line
* the line number to skip for start reading
*/
public CSVReader(Reader reader, char separator, char quotechar, int line) {
this(reader, separator, quotechar, DEFAULT_ESCAPE_CHARACTER, line);
}
/**
* Constructs CSVReader with supplied separator and quote char.
*
* @param reader
* the reader to an underlying CSV source.
* @param separator
* the delimiter to use for separating entries
* @param quotechar
* the character to use for quoted elements
* @param escape
* the character to use for escaping a separator or quote
* @param line
* the line number to skip for start reading
*/
public CSVReader(Reader reader, char separator, char quotechar, char escape, int line) {
this.br = new BufferedReader(reader);
this.separator = separator;
this.quotechar = quotechar;
this.escape = escape;
this.skipLines = line;
}
/**
* Reads the next line from the buffer and converts to a string array.
*
* @return a string array with each comma-separated element as a separate
* entry.
*
* @throws IOException
* if bad things happen during the read
*/
public String[] readNext() throws IOException {
String nextLine = getNextLine();
return hasNext ? parseLine(nextLine) : null;
}
/**
* Reads the next line from the file.
*
* @return the next line from the file without trailing newline
* @throws IOException
* if bad things happen during the read
*/
private String getNextLine() throws IOException {
if (!this.linesSkiped) {
for (int i = 0; i < skipLines; i++) {
br.readLine();
}
this.linesSkiped = true;
}
String nextLine = br.readLine();
if (nextLine == null) {
hasNext = false;
}
return hasNext ? nextLine : null;
}
/**
* Parses an incoming String and returns an array of elements.
*
* @param nextLine
* the string to parse
* @return the comma-tokenized list of elements, or null if nextLine is null
* @throws IOException if bad things happen during the read
*/
private String[] parseLine(String nextLine) throws IOException {
if (nextLine == null) {
return null;
}
List<String>tokensOnThisLine = new ArrayList<String>();
StringBuilder sb = new StringBuilder(INITIAL_READ_SIZE);
boolean inQuotes = false;
do {
if (inQuotes) {
// continuing a quoted section, reappend newline
sb.append("\n");
nextLine = getNextLine();
if (nextLine == null)
break;
}
for (int i = 0; i < nextLine.length(); i++) {
char c = nextLine.charAt(i);
if (c == this.escape) {
if( isEscapable(nextLine, inQuotes, i) ){
sb.append(nextLine.charAt(i+1));
i++;
}
} else if (c == quotechar) {
if( isEscapedQuote(nextLine, inQuotes, i) ){
sb.append(nextLine.charAt(i+1));
i++;
}else{
inQuotes = !inQuotes;
// the tricky case of an embedded quote in the middle: a,bc"d"ef,g
if(i>2 //not on the beginning of the line
&& nextLine.charAt(i-1) != this.separator //not at the beginning of an escape sequence
&& nextLine.length()>(i+1) &&
nextLine.charAt(i+1) != this.separator //not at the end of an escape sequence
){
sb.append(c);
}
}
} else if (c == separator && !inQuotes) {
tokensOnThisLine.add(sb.toString());
sb = new StringBuilder(INITIAL_READ_SIZE); // start work on next token
} else {
sb.append(c);
}
}
} while (inQuotes);
tokensOnThisLine.add(sb.toString());
return tokensOnThisLine.toArray(new String[0]);
}
/**
* precondition: the current character is a quote or an escape
* @param nextLine the current line
* @param inQuotes true if the current context is quoted
* @param i current index in line
* @return true if the following character is a quote
*/
private boolean isEscapedQuote(String nextLine, boolean inQuotes, int i) {
return inQuotes // we are in quotes, therefore there can be escaped quotes in here.
&& nextLine.length() > (i+1) // there is indeed another character to check.
&& nextLine.charAt(i+1) == quotechar;
}
/**
* precondition: the current character is an escape
* @param nextLine the current line
* @param inQuotes true if the current context is quoted
* @param i current index in line
* @return true if the following character is a quote
*/
private boolean isEscapable(String nextLine, boolean inQuotes, int i) {
return inQuotes // we are in quotes, therefore there can be escaped quotes in here.
&& nextLine.length() > (i+1) // there is indeed another character to check.
&& ( nextLine.charAt(i+1) == quotechar || nextLine.charAt(i+1) == this.escape);
}
/**
* Closes the underlying reader.
*
* @throws IOException if the close fails
*/
public void close() throws IOException{
br.close();
}
}
| Java |
/*
* Copyright 2013 Google 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.google.android.gcm.demo.app;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Main UI for the demo app.
*/
public class DemoActivity extends Activity {
public static final String EXTRA_MESSAGE = "message";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
/**
* Substitute you own sender ID here. This is the project number you got
* from the API Console, as described in "Getting Started."
*/
String SENDER_ID = "Your-Sender-ID";
/**
* Tag used on log messages.
*/
static final String TAG = "GCM Demo";
TextView mDisplay;
GoogleCloudMessaging gcm;
AtomicInteger msgId = new AtomicInteger();
Context context;
String regid;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mDisplay = (TextView) findViewById(R.id.display);
context = getApplicationContext();
// Check device for Play Services APK. If check succeeds, proceed with GCM registration.
if (checkPlayServices()) {
gcm = GoogleCloudMessaging.getInstance(this);
regid = getRegistrationId(context);
if (regid.isEmpty()) {
registerInBackground();
}
} else {
Log.i(TAG, "No valid Google Play Services APK found.");
}
}
@Override
protected void onResume() {
super.onResume();
// Check device for Play Services APK.
checkPlayServices();
}
/**
* Check the device to make sure it has the Google Play Services APK. If
* it doesn't, display a dialog that allows users to download the APK from
* the Google Play Store or enable it in the device's system settings.
*/
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Log.i(TAG, "This device is not supported.");
finish();
}
return false;
}
return true;
}
/**
* Stores the registration ID and the app versionCode in the application's
* {@code SharedPreferences}.
*
* @param context application's context.
* @param regId registration ID
*/
private void storeRegistrationId(Context context, String regId) {
final SharedPreferences prefs = getGcmPreferences(context);
int appVersion = getAppVersion(context);
Log.i(TAG, "Saving regId on app version " + appVersion);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(PROPERTY_REG_ID, regId);
editor.putInt(PROPERTY_APP_VERSION, appVersion);
editor.commit();
}
/**
* Gets the current registration ID for application on GCM service, if there is one.
* <p>
* If result is empty, the app needs to register.
*
* @return registration ID, or empty string if there is no existing
* registration ID.
*/
private String getRegistrationId(Context context) {
final SharedPreferences prefs = getGcmPreferences(context);
String registrationId = prefs.getString(PROPERTY_REG_ID, "");
if (registrationId.isEmpty()) {
Log.i(TAG, "Registration not found.");
return "";
}
// Check if app was updated; if so, it must clear the registration ID
// since the existing regID is not guaranteed to work with the new
// app version.
int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
int currentVersion = getAppVersion(context);
if (registeredVersion != currentVersion) {
Log.i(TAG, "App version changed.");
return "";
}
return registrationId;
}
/**
* Registers the application with GCM servers asynchronously.
* <p>
* Stores the registration ID and the app versionCode in the application's
* shared preferences.
*/
private void registerInBackground() {
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
regid = gcm.register(SENDER_ID);
msg = "Device registered, registration ID=" + regid;
// You should send the registration ID to your server over HTTP, so it
// can use GCM/HTTP or CCS to send messages to your app.
sendRegistrationIdToBackend();
// For this demo: we don't need to send it because the device will send
// upstream messages to a server that echo back the message using the
// 'from' address in the message.
// Persist the regID - no need to register again.
storeRegistrationId(context, regid);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
// If there is an error, don't just keep trying to register.
// Require the user to click a button again, or perform
// exponential back-off.
}
return msg;
}
@Override
protected void onPostExecute(String msg) {
mDisplay.append(msg + "\n");
}
}.execute(null, null, null);
}
// Send an upstream message.
public void onClick(final View view) {
if (view == findViewById(R.id.send)) {
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
String msg = "";
try {
Bundle data = new Bundle();
data.putString("my_message", "Hello World");
data.putString("my_action", "com.google.android.gcm.demo.app.ECHO_NOW");
String id = Integer.toString(msgId.incrementAndGet());
gcm.send(SENDER_ID + "@gcm.googleapis.com", id, data);
msg = "Sent message";
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
return msg;
}
@Override
protected void onPostExecute(String msg) {
mDisplay.append(msg + "\n");
}
}.execute(null, null, null);
} else if (view == findViewById(R.id.clear)) {
mDisplay.setText("");
}
}
@Override
protected void onDestroy() {
super.onDestroy();
}
/**
* @return Application's version code from the {@code PackageManager}.
*/
private static int getAppVersion(Context context) {
try {
PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode;
} catch (NameNotFoundException e) {
// should never happen
throw new RuntimeException("Could not get package name: " + e);
}
}
/**
* @return Application's {@code SharedPreferences}.
*/
private SharedPreferences getGcmPreferences(Context context) {
// This sample app persists the registration ID in shared preferences, but
// how you store the regID in your app is up to you.
return getSharedPreferences(DemoActivity.class.getSimpleName(),
Context.MODE_PRIVATE);
}
/**
* Sends the registration ID to your server over HTTP, so it can use GCM/HTTP or CCS to send
* messages to your app. Not needed for this demo since the device sends upstream messages
* to a server that echoes back the message using the 'from' address in the message.
*/
private void sendRegistrationIdToBackend() {
// Your implementation here.
}
}
| Java |
/*
* Copyright 2013 Google 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.google.android.gcm.demo.app;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;
/**
* This {@code WakefulBroadcastReceiver} takes care of creating and managing a
* partial wake lock for your app. It passes off the work of processing the GCM
* message to an {@code IntentService}, while ensuring that the device does not
* go back to sleep in the transition. The {@code IntentService} calls
* {@code GcmBroadcastReceiver.completeWakefulIntent()} when it is ready to
* release the wake lock.
*/
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// Explicitly specify that GcmIntentService will handle the intent.
ComponentName comp = new ComponentName(context.getPackageName(),
GcmIntentService.class.getName());
// Start the service, keeping the device awake while it is launching.
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
| Java |
/*
* Copyright (C) 2013 The Android Open Source Project
*
* 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.google.android.gcm.demo.app;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
/**
* This {@code IntentService} does the actual handling of the GCM message.
* {@code GcmBroadcastReceiver} (a {@code WakefulBroadcastReceiver}) holds a
* partial wake lock for this service while the service does its work. When the
* service is finished, it calls {@code completeWakefulIntent()} to release the
* wake lock.
*/
public class GcmIntentService extends IntentService {
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
public GcmIntentService() {
super("GcmIntentService");
}
public static final String TAG = "GCM Demo";
@Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
// The getMessageType() intent parameter must be the intent you received
// in your BroadcastReceiver.
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) { // has effect of unparcelling Bundle
/*
* Filter messages based on message type. Since it is likely that GCM will be
* extended in the future with new message types, just ignore any message types you're
* not interested in, or that you don't recognize.
*/
if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
sendNotification("Send error: " + extras.toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
sendNotification("Deleted messages on server: " + extras.toString());
// If it's a regular GCM message, do some work.
} else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
// This loop represents the service doing some work.
for (int i = 0; i < 5; i++) {
Log.i(TAG, "Working... " + (i + 1)
+ "/5 @ " + SystemClock.elapsedRealtime());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
}
Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
// Post notification of received message.
sendNotification("Received: " + extras.toString());
Log.i(TAG, "Received: " + extras.toString());
}
}
// Release the wake lock provided by the WakefulBroadcastReceiver.
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
// Put the message into a notification and post it.
// This is just one simple example of what you might choose to do with
// a GCM message.
private void sendNotification(String msg) {
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, DemoActivity.class), 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_gcm)
.setContentTitle("GCM Notification")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
}
| Java |
/*
* Copyright 2012 Google 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.google.android.gcm.server;
import java.io.IOException;
/**
* Exception thrown when GCM returned an error due to an invalid request.
* <p>
* This is equivalent to GCM posts that return an HTTP error different of 200.
*/
public final class InvalidRequestException extends IOException {
private final int status;
private final String description;
public InvalidRequestException(int status) {
this(status, null);
}
public InvalidRequestException(int status, String description) {
super(getMessage(status, description));
this.status = status;
this.description = description;
}
private static String getMessage(int status, String description) {
StringBuilder base = new StringBuilder("HTTP Status Code: ").append(status);
if (description != null) {
base.append("(").append(description).append(")");
}
return base.toString();
}
/**
* Gets the HTTP Status Code.
*/
public int getHttpStatusCode() {
return status;
}
/**
* Gets the error description.
*/
public String getDescription() {
return description;
}
}
| Java |
/*
* Copyright 2012 Google 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.google.android.gcm.server;
import java.io.Serializable;
/**
* Result of a GCM message request that returned HTTP status code 200.
*
* <p>
* If the message is successfully created, the {@link #getMessageId()} returns
* the message id and {@link #getErrorCodeName()} returns {@literal null};
* otherwise, {@link #getMessageId()} returns {@literal null} and
* {@link #getErrorCodeName()} returns the code of the error.
*
* <p>
* There are cases when a request is accept and the message successfully
* created, but GCM has a canonical registration id for that device. In this
* case, the server should update the registration id to avoid rejected requests
* in the future.
*
* <p>
* In a nutshell, the workflow to handle a result is:
* <pre>
* - Call {@link #getMessageId()}:
* - {@literal null} means error, call {@link #getErrorCodeName()}
* - non-{@literal null} means the message was created:
* - Call {@link #getCanonicalRegistrationId()}
* - if it returns {@literal null}, do nothing.
* - otherwise, update the server datastore with the new id.
* </pre>
*/
public final class Result implements Serializable {
private final String messageId;
private final String canonicalRegistrationId;
private final String errorCode;
public static final class Builder {
// optional parameters
private String messageId;
private String canonicalRegistrationId;
private String errorCode;
public Builder canonicalRegistrationId(String value) {
canonicalRegistrationId = value;
return this;
}
public Builder messageId(String value) {
messageId = value;
return this;
}
public Builder errorCode(String value) {
errorCode = value;
return this;
}
public Result build() {
return new Result(this);
}
}
private Result(Builder builder) {
canonicalRegistrationId = builder.canonicalRegistrationId;
messageId = builder.messageId;
errorCode = builder.errorCode;
}
/**
* Gets the message id, if any.
*/
public String getMessageId() {
return messageId;
}
/**
* Gets the canonical registration id, if any.
*/
public String getCanonicalRegistrationId() {
return canonicalRegistrationId;
}
/**
* Gets the error code, if any.
*/
public String getErrorCodeName() {
return errorCode;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder("[");
if (messageId != null) {
builder.append(" messageId=").append(messageId);
}
if (canonicalRegistrationId != null) {
builder.append(" canonicalRegistrationId=")
.append(canonicalRegistrationId);
}
if (errorCode != null) {
builder.append(" errorCode=").append(errorCode);
}
return builder.append(" ]").toString();
}
}
| Java |
/*
* Copyright 2012 Google 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.google.android.gcm.server;
import static com.google.android.gcm.server.Constants.GCM_SEND_ENDPOINT;
import static com.google.android.gcm.server.Constants.JSON_CANONICAL_IDS;
import static com.google.android.gcm.server.Constants.JSON_ERROR;
import static com.google.android.gcm.server.Constants.JSON_FAILURE;
import static com.google.android.gcm.server.Constants.JSON_MESSAGE_ID;
import static com.google.android.gcm.server.Constants.JSON_MULTICAST_ID;
import static com.google.android.gcm.server.Constants.JSON_PAYLOAD;
import static com.google.android.gcm.server.Constants.JSON_REGISTRATION_IDS;
import static com.google.android.gcm.server.Constants.JSON_RESULTS;
import static com.google.android.gcm.server.Constants.JSON_SUCCESS;
import static com.google.android.gcm.server.Constants.PARAM_COLLAPSE_KEY;
import static com.google.android.gcm.server.Constants.PARAM_DELAY_WHILE_IDLE;
import static com.google.android.gcm.server.Constants.PARAM_DRY_RUN;
import static com.google.android.gcm.server.Constants.PARAM_PAYLOAD_PREFIX;
import static com.google.android.gcm.server.Constants.PARAM_REGISTRATION_ID;
import static com.google.android.gcm.server.Constants.PARAM_RESTRICTED_PACKAGE_NAME;
import static com.google.android.gcm.server.Constants.PARAM_TIME_TO_LIVE;
import static com.google.android.gcm.server.Constants.TOKEN_CANONICAL_REG_ID;
import static com.google.android.gcm.server.Constants.TOKEN_ERROR;
import static com.google.android.gcm.server.Constants.TOKEN_MESSAGE_ID;
import com.google.android.gcm.server.Result.Builder;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Helper class to send messages to the GCM service using an API Key.
*/
public class Sender {
protected static final String UTF8 = "UTF-8";
/**
* Initial delay before first retry, without jitter.
*/
protected static final int BACKOFF_INITIAL_DELAY = 1000;
/**
* Maximum delay before a retry.
*/
protected static final int MAX_BACKOFF_DELAY = 1024000;
protected final Random random = new Random();
protected static final Logger logger =
Logger.getLogger(Sender.class.getName());
private final String key;
/**
* Default constructor.
*
* @param key API key obtained through the Google API Console.
*/
public Sender(String key) {
this.key = nonNull(key);
}
/**
* Sends a message to one device, retrying in case of unavailability.
*
* <p>
* <strong>Note: </strong> this method uses exponential back-off to retry in
* case of service unavailability and hence could block the calling thread
* for many seconds.
*
* @param message message to be sent, including the device's registration id.
* @param registrationId device where the message will be sent.
* @param retries number of retries in case of service unavailability errors.
*
* @return result of the request (see its javadoc for more details).
*
* @throws IllegalArgumentException if registrationId is {@literal null}.
* @throws InvalidRequestException if GCM didn't returned a 200 or 5xx status.
* @throws IOException if message could not be sent.
*/
public Result send(Message message, String registrationId, int retries)
throws IOException {
int attempt = 0;
Result result = null;
int backoff = BACKOFF_INITIAL_DELAY;
boolean tryAgain;
do {
attempt++;
if (logger.isLoggable(Level.FINE)) {
logger.fine("Attempt #" + attempt + " to send message " +
message + " to regIds " + registrationId);
}
result = sendNoRetry(message, registrationId);
tryAgain = result == null && attempt <= retries;
if (tryAgain) {
int sleepTime = backoff / 2 + random.nextInt(backoff);
sleep(sleepTime);
if (2 * backoff < MAX_BACKOFF_DELAY) {
backoff *= 2;
}
}
} while (tryAgain);
if (result == null) {
throw new IOException("Could not send message after " + attempt +
" attempts");
}
return result;
}
/**
* Sends a message without retrying in case of service unavailability. See
* {@link #send(Message, String, int)} for more info.
*
* @return result of the post, or {@literal null} if the GCM service was
* unavailable or any network exception caused the request to fail.
*
* @throws InvalidRequestException if GCM didn't returned a 200 or 5xx status.
* @throws IllegalArgumentException if registrationId is {@literal null}.
*/
public Result sendNoRetry(Message message, String registrationId)
throws IOException {
StringBuilder body = newBody(PARAM_REGISTRATION_ID, registrationId);
Boolean delayWhileIdle = message.isDelayWhileIdle();
if (delayWhileIdle != null) {
addParameter(body, PARAM_DELAY_WHILE_IDLE, delayWhileIdle ? "1" : "0");
}
Boolean dryRun = message.isDryRun();
if (dryRun != null) {
addParameter(body, PARAM_DRY_RUN, dryRun ? "1" : "0");
}
String collapseKey = message.getCollapseKey();
if (collapseKey != null) {
addParameter(body, PARAM_COLLAPSE_KEY, collapseKey);
}
String restrictedPackageName = message.getRestrictedPackageName();
if (restrictedPackageName != null) {
addParameter(body, PARAM_RESTRICTED_PACKAGE_NAME, restrictedPackageName);
}
Integer timeToLive = message.getTimeToLive();
if (timeToLive != null) {
addParameter(body, PARAM_TIME_TO_LIVE, Integer.toString(timeToLive));
}
for (Entry<String, String> entry : message.getData().entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if (key == null || value == null) {
logger.warning("Ignoring payload entry thas has null: " + entry);
} else {
key = PARAM_PAYLOAD_PREFIX + key;
addParameter(body, key, URLEncoder.encode(value, UTF8));
}
}
String requestBody = body.toString();
logger.finest("Request body: " + requestBody);
HttpURLConnection conn;
int status;
try {
conn = post(GCM_SEND_ENDPOINT, requestBody);
status = conn.getResponseCode();
} catch (IOException e) {
logger.log(Level.FINE, "IOException posting to GCM", e);
return null;
}
if (status / 100 == 5) {
logger.fine("GCM service is unavailable (status " + status + ")");
return null;
}
String responseBody;
if (status != 200) {
try {
responseBody = getAndClose(conn.getErrorStream());
logger.finest("Plain post error response: " + responseBody);
} catch (IOException e) {
// ignore the exception since it will thrown an InvalidRequestException
// anyways
responseBody = "N/A";
logger.log(Level.FINE, "Exception reading response: ", e);
}
throw new InvalidRequestException(status, responseBody);
} else {
try {
responseBody = getAndClose(conn.getInputStream());
} catch (IOException e) {
logger.log(Level.WARNING, "Exception reading response: ", e);
// return null so it can retry
return null;
}
}
String[] lines = responseBody.split("\n");
if (lines.length == 0 || lines[0].equals("")) {
throw new IOException("Received empty response from GCM service.");
}
String firstLine = lines[0];
String[] responseParts = split(firstLine);
String token = responseParts[0];
String value = responseParts[1];
if (token.equals(TOKEN_MESSAGE_ID)) {
Builder builder = new Result.Builder().messageId(value);
// check for canonical registration id
if (lines.length > 1) {
String secondLine = lines[1];
responseParts = split(secondLine);
token = responseParts[0];
value = responseParts[1];
if (token.equals(TOKEN_CANONICAL_REG_ID)) {
builder.canonicalRegistrationId(value);
} else {
logger.warning("Invalid response from GCM: " + responseBody);
}
}
Result result = builder.build();
if (logger.isLoggable(Level.FINE)) {
logger.fine("Message created succesfully (" + result + ")");
}
return result;
} else if (token.equals(TOKEN_ERROR)) {
return new Result.Builder().errorCode(value).build();
} else {
throw new IOException("Invalid response from GCM: " + responseBody);
}
}
/**
* Sends a message to many devices, retrying in case of unavailability.
*
* <p>
* <strong>Note: </strong> this method uses exponential back-off to retry in
* case of service unavailability and hence could block the calling thread
* for many seconds.
*
* @param message message to be sent.
* @param regIds registration id of the devices that will receive
* the message.
* @param retries number of retries in case of service unavailability errors.
*
* @return combined result of all requests made.
*
* @throws IllegalArgumentException if registrationIds is {@literal null} or
* empty.
* @throws InvalidRequestException if GCM didn't returned a 200 or 503 status.
* @throws IOException if message could not be sent.
*/
public MulticastResult send(Message message, List<String> regIds, int retries)
throws IOException {
int attempt = 0;
MulticastResult multicastResult;
int backoff = BACKOFF_INITIAL_DELAY;
// Map of results by registration id, it will be updated after each attempt
// to send the messages
Map<String, Result> results = new HashMap<String, Result>();
List<String> unsentRegIds = new ArrayList<String>(regIds);
boolean tryAgain;
List<Long> multicastIds = new ArrayList<Long>();
do {
multicastResult = null;
attempt++;
if (logger.isLoggable(Level.FINE)) {
logger.fine("Attempt #" + attempt + " to send message " +
message + " to regIds " + unsentRegIds);
}
try {
multicastResult = sendNoRetry(message, unsentRegIds);
} catch(IOException e) {
// no need for WARNING since exception might be already logged
logger.log(Level.FINEST, "IOException on attempt " + attempt, e);
}
if (multicastResult != null) {
long multicastId = multicastResult.getMulticastId();
logger.fine("multicast_id on attempt # " + attempt + ": " +
multicastId);
multicastIds.add(multicastId);
unsentRegIds = updateStatus(unsentRegIds, results, multicastResult);
tryAgain = !unsentRegIds.isEmpty() && attempt <= retries;
} else {
tryAgain = attempt <= retries;
}
if (tryAgain) {
int sleepTime = backoff / 2 + random.nextInt(backoff);
sleep(sleepTime);
if (2 * backoff < MAX_BACKOFF_DELAY) {
backoff *= 2;
}
}
} while (tryAgain);
if (multicastIds.isEmpty()) {
// all JSON posts failed due to GCM unavailability
throw new IOException("Could not post JSON requests to GCM after "
+ attempt + " attempts");
}
// calculate summary
int success = 0, failure = 0 , canonicalIds = 0;
for (Result result : results.values()) {
if (result.getMessageId() != null) {
success++;
if (result.getCanonicalRegistrationId() != null) {
canonicalIds++;
}
} else {
failure++;
}
}
// build a new object with the overall result
long multicastId = multicastIds.remove(0);
MulticastResult.Builder builder = new MulticastResult.Builder(success,
failure, canonicalIds, multicastId).retryMulticastIds(multicastIds);
// add results, in the same order as the input
for (String regId : regIds) {
Result result = results.get(regId);
builder.addResult(result);
}
return builder.build();
}
/**
* Updates the status of the messages sent to devices and the list of devices
* that should be retried.
*
* @param unsentRegIds list of devices that are still pending an update.
* @param allResults map of status that will be updated.
* @param multicastResult result of the last multicast sent.
*
* @return updated version of devices that should be retried.
*/
private List<String> updateStatus(List<String> unsentRegIds,
Map<String, Result> allResults, MulticastResult multicastResult) {
List<Result> results = multicastResult.getResults();
if (results.size() != unsentRegIds.size()) {
// should never happen, unless there is a flaw in the algorithm
throw new RuntimeException("Internal error: sizes do not match. " +
"currentResults: " + results + "; unsentRegIds: " + unsentRegIds);
}
List<String> newUnsentRegIds = new ArrayList<String>();
for (int i = 0; i < unsentRegIds.size(); i++) {
String regId = unsentRegIds.get(i);
Result result = results.get(i);
allResults.put(regId, result);
String error = result.getErrorCodeName();
if (error != null && (error.equals(Constants.ERROR_UNAVAILABLE)
|| error.equals(Constants.ERROR_INTERNAL_SERVER_ERROR))) {
newUnsentRegIds.add(regId);
}
}
return newUnsentRegIds;
}
/**
* Sends a message without retrying in case of service unavailability. See
* {@link #send(Message, List, int)} for more info.
*
* @return multicast results if the message was sent successfully,
* {@literal null} if it failed but could be retried.
*
* @throws IllegalArgumentException if registrationIds is {@literal null} or
* empty.
* @throws InvalidRequestException if GCM didn't returned a 200 status.
* @throws IOException if there was a JSON parsing error
*/
public MulticastResult sendNoRetry(Message message,
List<String> registrationIds) throws IOException {
if (nonNull(registrationIds).isEmpty()) {
throw new IllegalArgumentException("registrationIds cannot be empty");
}
Map<Object, Object> jsonRequest = new HashMap<Object, Object>();
setJsonField(jsonRequest, PARAM_TIME_TO_LIVE, message.getTimeToLive());
setJsonField(jsonRequest, PARAM_COLLAPSE_KEY, message.getCollapseKey());
setJsonField(jsonRequest, PARAM_RESTRICTED_PACKAGE_NAME, message.getRestrictedPackageName());
setJsonField(jsonRequest, PARAM_DELAY_WHILE_IDLE,
message.isDelayWhileIdle());
setJsonField(jsonRequest, PARAM_DRY_RUN, message.isDryRun());
jsonRequest.put(JSON_REGISTRATION_IDS, registrationIds);
Map<String, String> payload = message.getData();
if (!payload.isEmpty()) {
jsonRequest.put(JSON_PAYLOAD, payload);
}
String requestBody = JSONValue.toJSONString(jsonRequest);
logger.finest("JSON request: " + requestBody);
HttpURLConnection conn;
int status;
try {
conn = post(GCM_SEND_ENDPOINT, "application/json", requestBody);
status = conn.getResponseCode();
} catch (IOException e) {
logger.log(Level.FINE, "IOException posting to GCM", e);
return null;
}
String responseBody;
if (status != 200) {
try {
responseBody = getAndClose(conn.getErrorStream());
logger.finest("JSON error response: " + responseBody);
} catch (IOException e) {
// ignore the exception since it will thrown an InvalidRequestException
// anyways
responseBody = "N/A";
logger.log(Level.FINE, "Exception reading response: ", e);
}
throw new InvalidRequestException(status, responseBody);
}
try {
responseBody = getAndClose(conn.getInputStream());
} catch(IOException e) {
logger.log(Level.WARNING, "IOException reading response", e);
return null;
}
logger.finest("JSON response: " + responseBody);
JSONParser parser = new JSONParser();
JSONObject jsonResponse;
try {
jsonResponse = (JSONObject) parser.parse(responseBody);
int success = getNumber(jsonResponse, JSON_SUCCESS).intValue();
int failure = getNumber(jsonResponse, JSON_FAILURE).intValue();
int canonicalIds = getNumber(jsonResponse, JSON_CANONICAL_IDS).intValue();
long multicastId = getNumber(jsonResponse, JSON_MULTICAST_ID).longValue();
MulticastResult.Builder builder = new MulticastResult.Builder(success,
failure, canonicalIds, multicastId);
@SuppressWarnings("unchecked")
List<Map<String, Object>> results =
(List<Map<String, Object>>) jsonResponse.get(JSON_RESULTS);
if (results != null) {
for (Map<String, Object> jsonResult : results) {
String messageId = (String) jsonResult.get(JSON_MESSAGE_ID);
String canonicalRegId =
(String) jsonResult.get(TOKEN_CANONICAL_REG_ID);
String error = (String) jsonResult.get(JSON_ERROR);
Result result = new Result.Builder()
.messageId(messageId)
.canonicalRegistrationId(canonicalRegId)
.errorCode(error)
.build();
builder.addResult(result);
}
}
MulticastResult multicastResult = builder.build();
return multicastResult;
} catch (ParseException e) {
throw newIoException(responseBody, e);
} catch (CustomParserException e) {
throw newIoException(responseBody, e);
}
}
private IOException newIoException(String responseBody, Exception e) {
// log exception, as IOException constructor that takes a message and cause
// is only available on Java 6
String msg = "Error parsing JSON response (" + responseBody + ")";
logger.log(Level.WARNING, msg, e);
return new IOException(msg + ":" + e);
}
private static void close(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException e) {
// ignore error
logger.log(Level.FINEST, "IOException closing stream", e);
}
}
}
/**
* Sets a JSON field, but only if the value is not {@literal null}.
*/
private void setJsonField(Map<Object, Object> json, String field,
Object value) {
if (value != null) {
json.put(field, value);
}
}
private Number getNumber(Map<?, ?> json, String field) {
Object value = json.get(field);
if (value == null) {
throw new CustomParserException("Missing field: " + field);
}
if (!(value instanceof Number)) {
throw new CustomParserException("Field " + field +
" does not contain a number: " + value);
}
return (Number) value;
}
class CustomParserException extends RuntimeException {
CustomParserException(String message) {
super(message);
}
}
private String[] split(String line) throws IOException {
String[] split = line.split("=", 2);
if (split.length != 2) {
throw new IOException("Received invalid response line from GCM: " + line);
}
return split;
}
/**
* Make an HTTP post to a given URL.
*
* @return HTTP response.
*/
protected HttpURLConnection post(String url, String body)
throws IOException {
return post(url, "application/x-www-form-urlencoded;charset=UTF-8", body);
}
/**
* Makes an HTTP POST request to a given endpoint.
*
* <p>
* <strong>Note: </strong> the returned connected should not be disconnected,
* otherwise it would kill persistent connections made using Keep-Alive.
*
* @param url endpoint to post the request.
* @param contentType type of request.
* @param body body of the request.
*
* @return the underlying connection.
*
* @throws IOException propagated from underlying methods.
*/
protected HttpURLConnection post(String url, String contentType, String body)
throws IOException {
if (url == null || body == null) {
throw new IllegalArgumentException("arguments cannot be null");
}
if (!url.startsWith("https://")) {
logger.warning("URL does not use https: " + url);
}
logger.fine("Sending POST to " + url);
logger.finest("POST body: " + body);
byte[] bytes = body.getBytes();
HttpURLConnection conn = getConnection(url);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setFixedLengthStreamingMode(bytes.length);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", contentType);
conn.setRequestProperty("Authorization", "key=" + key);
OutputStream out = conn.getOutputStream();
try {
out.write(bytes);
} finally {
close(out);
}
return conn;
}
/**
* Creates a map with just one key-value pair.
*/
protected static final Map<String, String> newKeyValues(String key,
String value) {
Map<String, String> keyValues = new HashMap<String, String>(1);
keyValues.put(nonNull(key), nonNull(value));
return keyValues;
}
/**
* Creates a {@link StringBuilder} to be used as the body of an HTTP POST.
*
* @param name initial parameter for the POST.
* @param value initial value for that parameter.
* @return StringBuilder to be used an HTTP POST body.
*/
protected static StringBuilder newBody(String name, String value) {
return new StringBuilder(nonNull(name)).append('=').append(nonNull(value));
}
/**
* Adds a new parameter to the HTTP POST body.
*
* @param body HTTP POST body.
* @param name parameter's name.
* @param value parameter's value.
*/
protected static void addParameter(StringBuilder body, String name,
String value) {
nonNull(body).append('&')
.append(nonNull(name)).append('=').append(nonNull(value));
}
/**
* Gets an {@link HttpURLConnection} given an URL.
*/
protected HttpURLConnection getConnection(String url) throws IOException {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
return conn;
}
/**
* Convenience method to convert an InputStream to a String.
* <p>
* If the stream ends in a newline character, it will be stripped.
* <p>
* If the stream is {@literal null}, returns an empty string.
*/
protected static String getString(InputStream stream) throws IOException {
if (stream == null) {
return "";
}
BufferedReader reader =
new BufferedReader(new InputStreamReader(stream));
StringBuilder content = new StringBuilder();
String newLine;
do {
newLine = reader.readLine();
if (newLine != null) {
content.append(newLine).append('\n');
}
} while (newLine != null);
if (content.length() > 0) {
// strip last newline
content.setLength(content.length() - 1);
}
return content.toString();
}
private static String getAndClose(InputStream stream) throws IOException {
try {
return getString(stream);
} finally {
if (stream != null) {
close(stream);
}
}
}
static <T> T nonNull(T argument) {
if (argument == null) {
throw new IllegalArgumentException("argument cannot be null");
}
return argument;
}
void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
| Java |
/*
* Copyright 2012 Google 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.google.android.gcm.server;
/**
* Constants used on GCM service communication.
*/
public final class Constants {
/**
* Endpoint for sending messages.
*/
public static final String GCM_SEND_ENDPOINT =
"https://android.googleapis.com/gcm/send";
/**
* HTTP parameter for registration id.
*/
public static final String PARAM_REGISTRATION_ID = "registration_id";
/**
* HTTP parameter for collapse key.
*/
public static final String PARAM_COLLAPSE_KEY = "collapse_key";
/**
* HTTP parameter for delaying the message delivery if the device is idle.
*/
public static final String PARAM_DELAY_WHILE_IDLE = "delay_while_idle";
/**
* HTTP parameter for telling gcm to validate the message without actually sending it.
*/
public static final String PARAM_DRY_RUN = "dry_run";
/**
* HTTP parameter for package name that can be used to restrict message delivery by matching
* against the package name used to generate the registration id.
*/
public static final String PARAM_RESTRICTED_PACKAGE_NAME = "restricted_package_name";
/**
* Prefix to HTTP parameter used to pass key-values in the message payload.
*/
public static final String PARAM_PAYLOAD_PREFIX = "data.";
/**
* Prefix to HTTP parameter used to set the message time-to-live.
*/
public static final String PARAM_TIME_TO_LIVE = "time_to_live";
/**
* Too many messages sent by the sender. Retry after a while.
*/
public static final String ERROR_QUOTA_EXCEEDED = "QuotaExceeded";
/**
* Too many messages sent by the sender to a specific device.
* Retry after a while.
*/
public static final String ERROR_DEVICE_QUOTA_EXCEEDED =
"DeviceQuotaExceeded";
/**
* Missing registration_id.
* Sender should always add the registration_id to the request.
*/
public static final String ERROR_MISSING_REGISTRATION = "MissingRegistration";
/**
* Bad registration_id. Sender should remove this registration_id.
*/
public static final String ERROR_INVALID_REGISTRATION = "InvalidRegistration";
/**
* The sender_id contained in the registration_id does not match the
* sender_id used to register with the GCM servers.
*/
public static final String ERROR_MISMATCH_SENDER_ID = "MismatchSenderId";
/**
* The user has uninstalled the application or turned off notifications.
* Sender should stop sending messages to this device and delete the
* registration_id. The client needs to re-register with the GCM servers to
* receive notifications again.
*/
public static final String ERROR_NOT_REGISTERED = "NotRegistered";
/**
* The payload of the message is too big, see the limitations.
* Reduce the size of the message.
*/
public static final String ERROR_MESSAGE_TOO_BIG = "MessageTooBig";
/**
* Collapse key is required. Include collapse key in the request.
*/
public static final String ERROR_MISSING_COLLAPSE_KEY = "MissingCollapseKey";
/**
* A particular message could not be sent because the GCM servers were not
* available. Used only on JSON requests, as in plain text requests
* unavailability is indicated by a 503 response.
*/
public static final String ERROR_UNAVAILABLE = "Unavailable";
/**
* A particular message could not be sent because the GCM servers encountered
* an error. Used only on JSON requests, as in plain text requests internal
* errors are indicated by a 500 response.
*/
public static final String ERROR_INTERNAL_SERVER_ERROR =
"InternalServerError";
/**
* Time to Live value passed is less than zero or more than maximum.
*/
public static final String ERROR_INVALID_TTL= "InvalidTtl";
/**
* Token returned by GCM when a message was successfully sent.
*/
public static final String TOKEN_MESSAGE_ID = "id";
/**
* Token returned by GCM when the requested registration id has a canonical
* value.
*/
public static final String TOKEN_CANONICAL_REG_ID = "registration_id";
/**
* Token returned by GCM when there was an error sending a message.
*/
public static final String TOKEN_ERROR = "Error";
/**
* JSON-only field representing the registration ids.
*/
public static final String JSON_REGISTRATION_IDS = "registration_ids";
/**
* JSON-only field representing the payload data.
*/
public static final String JSON_PAYLOAD = "data";
/**
* JSON-only field representing the number of successful messages.
*/
public static final String JSON_SUCCESS = "success";
/**
* JSON-only field representing the number of failed messages.
*/
public static final String JSON_FAILURE = "failure";
/**
* JSON-only field representing the number of messages with a canonical
* registration id.
*/
public static final String JSON_CANONICAL_IDS = "canonical_ids";
/**
* JSON-only field representing the id of the multicast request.
*/
public static final String JSON_MULTICAST_ID = "multicast_id";
/**
* JSON-only field representing the result of each individual request.
*/
public static final String JSON_RESULTS = "results";
/**
* JSON-only field representing the error field of an individual request.
*/
public static final String JSON_ERROR = "error";
/**
* JSON-only field sent by GCM when a message was successfully sent.
*/
public static final String JSON_MESSAGE_ID = "message_id";
private Constants() {
throw new UnsupportedOperationException();
}
}
| Java |
/*
* Copyright 2012 Google 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.google.android.gcm.server;
import java.io.Serializable;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* GCM message.
*
* <p>
* Instances of this class are immutable and should be created using a
* {@link Builder}. Examples:
*
* <strong>Simplest message:</strong>
* <pre><code>
* Message message = new Message.Builder().build();
* </pre></code>
*
* <strong>Message with optional attributes:</strong>
* <pre><code>
* Message message = new Message.Builder()
* .collapseKey(collapseKey)
* .timeToLive(3)
* .delayWhileIdle(true)
* .dryRun(true)
* .restrictedPackageName(restrictedPackageName)
* .build();
* </pre></code>
*
* <strong>Message with optional attributes and payload data:</strong>
* <pre><code>
* Message message = new Message.Builder()
* .collapseKey(collapseKey)
* .timeToLive(3)
* .delayWhileIdle(true)
* .dryRun(true)
* .restrictedPackageName(restrictedPackageName)
* .addData("key1", "value1")
* .addData("key2", "value2")
* .build();
* </pre></code>
*/
public final class Message implements Serializable {
private final String collapseKey;
private final Boolean delayWhileIdle;
private final Integer timeToLive;
private final Map<String, String> data;
private final Boolean dryRun;
private final String restrictedPackageName;
public static final class Builder {
private final Map<String, String> data;
// optional parameters
private String collapseKey;
private Boolean delayWhileIdle;
private Integer timeToLive;
private Boolean dryRun;
private String restrictedPackageName;
public Builder() {
this.data = new LinkedHashMap<String, String>();
}
/**
* Sets the collapseKey property.
*/
public Builder collapseKey(String value) {
collapseKey = value;
return this;
}
/**
* Sets the delayWhileIdle property (default value is {@literal false}).
*/
public Builder delayWhileIdle(boolean value) {
delayWhileIdle = value;
return this;
}
/**
* Sets the time to live, in seconds.
*/
public Builder timeToLive(int value) {
timeToLive = value;
return this;
}
/**
* Adds a key/value pair to the payload data.
*/
public Builder addData(String key, String value) {
data.put(key, value);
return this;
}
/**
* Sets the dryRun property (default value is {@literal false}).
*/
public Builder dryRun(boolean value) {
dryRun = value;
return this;
}
/**
* Sets the restrictedPackageName property.
*/
public Builder restrictedPackageName(String value) {
restrictedPackageName = value;
return this;
}
public Message build() {
return new Message(this);
}
}
private Message(Builder builder) {
collapseKey = builder.collapseKey;
delayWhileIdle = builder.delayWhileIdle;
data = Collections.unmodifiableMap(builder.data);
timeToLive = builder.timeToLive;
dryRun = builder.dryRun;
restrictedPackageName = builder.restrictedPackageName;
}
/**
* Gets the collapse key.
*/
public String getCollapseKey() {
return collapseKey;
}
/**
* Gets the delayWhileIdle flag.
*/
public Boolean isDelayWhileIdle() {
return delayWhileIdle;
}
/**
* Gets the time to live (in seconds).
*/
public Integer getTimeToLive() {
return timeToLive;
}
/**
* Gets the dryRun flag.
*/
public Boolean isDryRun() {
return dryRun;
}
/**
* Gets the restricted package name.
*/
public String getRestrictedPackageName() {
return restrictedPackageName;
}
/**
* Gets the payload data, which is immutable.
*/
public Map<String, String> getData() {
return data;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder("Message(");
if (collapseKey != null) {
builder.append("collapseKey=").append(collapseKey).append(", ");
}
if (timeToLive != null) {
builder.append("timeToLive=").append(timeToLive).append(", ");
}
if (delayWhileIdle != null) {
builder.append("delayWhileIdle=").append(delayWhileIdle).append(", ");
}
if (dryRun != null) {
builder.append("dryRun=").append(dryRun).append(", ");
}
if (restrictedPackageName != null) {
builder.append("restrictedPackageName=").append(restrictedPackageName).append(", ");
}
if (!data.isEmpty()) {
builder.append("data: {");
for (Map.Entry<String, String> entry : data.entrySet()) {
builder.append(entry.getKey()).append("=").append(entry.getValue())
.append(",");
}
builder.delete(builder.length() - 1, builder.length());
builder.append("}");
}
if (builder.charAt(builder.length() - 1) == ' ') {
builder.delete(builder.length() - 2, builder.length());
}
builder.append(")");
return builder.toString();
}
}
| Java |
/*
* Copyright 2012 Google 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.google.android.gcm.server;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Result of a GCM multicast message request .
*/
public final class MulticastResult implements Serializable {
private final int success;
private final int failure;
private final int canonicalIds;
private final long multicastId;
private final List<Result> results;
private final List<Long> retryMulticastIds;
public static final class Builder {
private final List<Result> results = new ArrayList<Result>();
// required parameters
private final int success;
private final int failure;
private final int canonicalIds;
private final long multicastId;
// optional parameters
private List<Long> retryMulticastIds;
public Builder(int success, int failure, int canonicalIds,
long multicastId) {
this.success = success;
this.failure = failure;
this.canonicalIds = canonicalIds;
this.multicastId = multicastId;
}
public Builder addResult(Result result) {
results.add(result);
return this;
}
public Builder retryMulticastIds(List<Long> retryMulticastIds) {
this.retryMulticastIds = retryMulticastIds;
return this;
}
public MulticastResult build() {
return new MulticastResult(this);
}
}
private MulticastResult(Builder builder) {
success = builder.success;
failure = builder.failure;
canonicalIds = builder.canonicalIds;
multicastId = builder.multicastId;
results = Collections.unmodifiableList(builder.results);
List<Long> tmpList = builder.retryMulticastIds;
if (tmpList == null) {
tmpList = Collections.emptyList();
}
retryMulticastIds = Collections.unmodifiableList(tmpList);
}
/**
* Gets the multicast id.
*/
public long getMulticastId() {
return multicastId;
}
/**
* Gets the number of successful messages.
*/
public int getSuccess() {
return success;
}
/**
* Gets the total number of messages sent, regardless of the status.
*/
public int getTotal() {
return success + failure;
}
/**
* Gets the number of failed messages.
*/
public int getFailure() {
return failure;
}
/**
* Gets the number of successful messages that also returned a canonical
* registration id.
*/
public int getCanonicalIds() {
return canonicalIds;
}
/**
* Gets the results of each individual message, which is immutable.
*/
public List<Result> getResults() {
return results;
}
/**
* Gets additional ids if more than one multicast message was sent.
*/
public List<Long> getRetryMulticastIds() {
return retryMulticastIds;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder("MulticastResult(")
.append("multicast_id=").append(multicastId).append(",")
.append("total=").append(getTotal()).append(",")
.append("success=").append(success).append(",")
.append("failure=").append(failure).append(",")
.append("canonical_ids=").append(canonicalIds).append(",");
if (!results.isEmpty()) {
builder.append("results: " + results);
}
return builder.toString();
}
}
| Java |
/*
* Copyright 2012 Google 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.google.android.gcm;
import static com.google.android.gcm.GCMConstants.ERROR_SERVICE_NOT_AVAILABLE;
import static com.google.android.gcm.GCMConstants.EXTRA_ERROR;
import static com.google.android.gcm.GCMConstants.EXTRA_REGISTRATION_ID;
import static com.google.android.gcm.GCMConstants.EXTRA_SPECIAL_MESSAGE;
import static com.google.android.gcm.GCMConstants.EXTRA_TOTAL_DELETED;
import static com.google.android.gcm.GCMConstants.EXTRA_UNREGISTERED;
import static com.google.android.gcm.GCMConstants.INTENT_FROM_GCM_LIBRARY_RETRY;
import static com.google.android.gcm.GCMConstants.INTENT_FROM_GCM_MESSAGE;
import static com.google.android.gcm.GCMConstants.INTENT_FROM_GCM_REGISTRATION_CALLBACK;
import static com.google.android.gcm.GCMConstants.VALUE_DELETED_MESSAGES;
import android.app.AlarmManager;
import android.app.IntentService;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.os.SystemClock;
import android.util.Log;
import java.util.Random;
import java.util.concurrent.TimeUnit;
/**
* Skeleton for application-specific {@link IntentService}s responsible for
* handling communication from Google Cloud Messaging service.
* <p>
* The abstract methods in this class are called from its worker thread, and
* hence should run in a limited amount of time. If they execute long
* operations, they should spawn new threads, otherwise the worker thread will
* be blocked.
* <p>
* Subclasses must provide a public no-arg constructor.
*
* @deprecated GCM library has been moved to Google Play Services
* (com.google.android.gms.gcm), and this version is no longer supported.
*/
@Deprecated
public abstract class GCMBaseIntentService extends IntentService {
/**
* Old TAG used for logging. Marked as deprecated since it should have
* been private at first place.
*/
@Deprecated
public static final String TAG = "GCMBaseIntentService";
private final GCMLogger mLogger = new GCMLogger("GCMBaseIntentService",
"[" + getClass().getName() + "]: ");
// wakelock
private static final String WAKELOCK_KEY = "GCM_LIB";
private static PowerManager.WakeLock sWakeLock;
// Java lock used to synchronize access to sWakelock
private static final Object LOCK = GCMBaseIntentService.class;
private final String[] mSenderIds;
// instance counter
private static int sCounter = 0;
private static final Random sRandom = new Random();
private static final int MAX_BACKOFF_MS =
(int) TimeUnit.SECONDS.toMillis(3600); // 1 hour
/**
* Constructor that does not set a sender id, useful when the sender id
* is context-specific.
* <p>
* When using this constructor, the subclass <strong>must</strong>
* override {@link #getSenderIds(Context)}, otherwise methods such as
* {@link #onHandleIntent(Intent)} will throw an
* {@link IllegalStateException} on runtime.
*/
protected GCMBaseIntentService() {
this(getName("DynamicSenderIds"), null);
}
/**
* Constructor used when the sender id(s) is fixed.
*/
protected GCMBaseIntentService(String... senderIds) {
this(getName(senderIds), senderIds);
}
private GCMBaseIntentService(String name, String[] senderIds) {
super(name); // name is used as base name for threads, etc.
mSenderIds = senderIds;
mLogger.log(Log.VERBOSE, "Intent service name: %s", name);
}
private static String getName(String senderId) {
String name = "GCMIntentService-" + senderId + "-" + (++sCounter);
return name;
}
private static String getName(String[] senderIds) {
String flatSenderIds = GCMRegistrar.getFlatSenderIds(senderIds);
return getName(flatSenderIds);
}
/**
* Gets the sender ids.
*
* <p>By default, it returns the sender ids passed in the constructor, but
* it could be overridden to provide a dynamic sender id.
*
* @throws IllegalStateException if sender id was not set on constructor.
*/
protected String[] getSenderIds(Context context) {
if (mSenderIds == null) {
throw new IllegalStateException("sender id not set on constructor");
}
return mSenderIds;
}
/**
* Called when a cloud message has been received.
*
* @param context application's context.
* @param intent intent containing the message payload as extras.
*/
protected abstract void onMessage(Context context, Intent intent);
/**
* Called when the GCM server tells pending messages have been deleted
* because the device was idle.
*
* @param context application's context.
* @param total total number of collapsed messages
*/
protected void onDeletedMessages(Context context, int total) {
}
/**
* Called on a registration error that could be retried.
*
* <p>By default, it does nothing and returns {@literal true}, but could be
* overridden to change that behavior and/or display the error.
*
* @param context application's context.
* @param errorId error id returned by the GCM service.
*
* @return if {@literal true}, failed operation will be retried (using
* exponential backoff).
*/
protected boolean onRecoverableError(Context context, String errorId) {
return true;
}
/**
* Called on registration or unregistration error.
*
* @param context application's context.
* @param errorId error id returned by the GCM service.
*/
protected abstract void onError(Context context, String errorId);
/**
* Called after a device has been registered.
*
* @param context application's context.
* @param registrationId the registration id returned by the GCM service.
*/
protected abstract void onRegistered(Context context,
String registrationId);
/**
* Called after a device has been unregistered.
*
* @param registrationId the registration id that was previously registered.
* @param context application's context.
*/
protected abstract void onUnregistered(Context context,
String registrationId);
@Override
public final void onHandleIntent(Intent intent) {
try {
Context context = getApplicationContext();
String action = intent.getAction();
if (action.equals(INTENT_FROM_GCM_REGISTRATION_CALLBACK)) {
GCMRegistrar.setRetryBroadcastReceiver(context);
handleRegistration(context, intent);
} else if (action.equals(INTENT_FROM_GCM_MESSAGE)) {
// checks for special messages
String messageType =
intent.getStringExtra(EXTRA_SPECIAL_MESSAGE);
if (messageType != null) {
if (messageType.equals(VALUE_DELETED_MESSAGES)) {
String sTotal =
intent.getStringExtra(EXTRA_TOTAL_DELETED);
if (sTotal != null) {
try {
int total = Integer.parseInt(sTotal);
mLogger.log(Log.VERBOSE,
"Received notification for %d deleted"
+ "messages", total);
onDeletedMessages(context, total);
} catch (NumberFormatException e) {
mLogger.log(Log.ERROR, "GCM returned invalid "
+ "number of deleted messages (%d)",
sTotal);
}
}
} else {
// application is not using the latest GCM library
mLogger.log(Log.ERROR,
"Received unknown special message: %s",
messageType);
}
} else {
onMessage(context, intent);
}
} else if (action.equals(INTENT_FROM_GCM_LIBRARY_RETRY)) {
String packageOnIntent = intent.getPackage();
if (packageOnIntent == null || !packageOnIntent.equals(
getApplicationContext().getPackageName())) {
mLogger.log(Log.ERROR,
"Ignoring retry intent from another package (%s)",
packageOnIntent);
return;
}
// retry last call
if (GCMRegistrar.isRegistered(context)) {
GCMRegistrar.internalUnregister(context);
} else {
String[] senderIds = getSenderIds(context);
GCMRegistrar.internalRegister(context, senderIds);
}
}
} finally {
// Release the power lock, so phone can get back to sleep.
// The lock is reference-counted by default, so multiple
// messages are ok.
// If onMessage() needs to spawn a thread or do something else,
// it should use its own lock.
synchronized (LOCK) {
// sanity check for null as this is a public method
if (sWakeLock != null) {
sWakeLock.release();
} else {
// should never happen during normal workflow
mLogger.log(Log.ERROR, "Wakelock reference is null");
}
}
}
}
/**
* Called from the broadcast receiver.
* <p>
* Will process the received intent, call handleMessage(), registered(),
* etc. in background threads, with a wake lock, while keeping the service
* alive.
*/
static void runIntentInService(Context context, Intent intent,
String className) {
synchronized (LOCK) {
if (sWakeLock == null) {
// This is called from BroadcastReceiver, there is no init.
PowerManager pm = (PowerManager)
context.getSystemService(Context.POWER_SERVICE);
sWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
WAKELOCK_KEY);
}
}
sWakeLock.acquire();
intent.setClassName(context, className);
context.startService(intent);
}
private void handleRegistration(final Context context, Intent intent) {
GCMRegistrar.cancelAppPendingIntent();
String registrationId = intent.getStringExtra(EXTRA_REGISTRATION_ID);
String error = intent.getStringExtra(EXTRA_ERROR);
String unregistered = intent.getStringExtra(EXTRA_UNREGISTERED);
mLogger.log(Log.DEBUG, "handleRegistration: registrationId = %s, "
+ "error = %s, unregistered = %s",
registrationId, error, unregistered);
// registration succeeded
if (registrationId != null) {
GCMRegistrar.resetBackoff(context);
GCMRegistrar.setRegistrationId(context, registrationId);
onRegistered(context, registrationId);
return;
}
// unregistration succeeded
if (unregistered != null) {
// Remember we are unregistered
GCMRegistrar.resetBackoff(context);
String oldRegistrationId =
GCMRegistrar.clearRegistrationId(context);
onUnregistered(context, oldRegistrationId);
return;
}
// last operation (registration or unregistration) returned an error;
// Registration failed
if (ERROR_SERVICE_NOT_AVAILABLE.equals(error)) {
boolean retry = onRecoverableError(context, error);
if (retry) {
int backoffTimeMs = GCMRegistrar.getBackoff(context);
int nextAttempt = backoffTimeMs / 2 +
sRandom.nextInt(backoffTimeMs);
mLogger.log(Log.DEBUG,
"Scheduling registration retry, backoff = %d (%d)",
nextAttempt, backoffTimeMs);
Intent retryIntent =
new Intent(INTENT_FROM_GCM_LIBRARY_RETRY);
retryIntent.setPackage(context.getPackageName());
PendingIntent retryPendingIntent = PendingIntent
.getBroadcast(context, 0, retryIntent, 0);
AlarmManager am = (AlarmManager)
context.getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.ELAPSED_REALTIME,
SystemClock.elapsedRealtime() + nextAttempt,
retryPendingIntent);
// Next retry should wait longer.
if (backoffTimeMs < MAX_BACKOFF_MS) {
GCMRegistrar.setBackoff(context, backoffTimeMs * 2);
}
} else {
mLogger.log(Log.VERBOSE, "Not retrying failed operation");
}
} else {
// Unrecoverable error, notify app
onError(context, error);
}
}
}
| Java |
/*
* Copyright 2012 Google 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.google.android.gcm;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.os.Build;
import android.util.Log;
import java.sql.Timestamp;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Utilities for device registration.
* <p>
* <strong>Note:</strong> this class uses a private {@link SharedPreferences}
* object to keep track of the registration token.
*
* @deprecated GCM library has been moved to Google Play Services
* (com.google.android.gms.gcm), and this version is no longer supported.
*/
@Deprecated
public final class GCMRegistrar {
/**
* Default lifespan (7 days) of the {@link #isRegisteredOnServer(Context)}
* flag until it is considered expired.
*/
// NOTE: cannot use TimeUnit.DAYS because it's not available on API Level 8
public static final long DEFAULT_ON_SERVER_LIFESPAN_MS =
1000 * 3600 * 24 * 7;
private static final String TAG = "GCMRegistrar";
private static final String BACKOFF_MS = "backoff_ms";
private static final String GSF_PACKAGE = "com.google.android.gsf";
private static final String PREFERENCES = "com.google.android.gcm";
private static final int DEFAULT_BACKOFF_MS = 3000;
private static final String PROPERTY_REG_ID = "regId";
private static final String PROPERTY_APP_VERSION = "appVersion";
private static final String PROPERTY_ON_SERVER = "onServer";
private static final String PROPERTY_ON_SERVER_EXPIRATION_TIME =
"onServerExpirationTime";
private static final String PROPERTY_ON_SERVER_LIFESPAN =
"onServerLifeSpan";
/**
* {@link GCMBroadcastReceiver} instance used to handle the retry intent.
*
* <p>
* This instance cannot be the same as the one defined in the manifest
* because it needs a different permission.
*/
// guarded by GCMRegistrar.class
private static GCMBroadcastReceiver sRetryReceiver;
// guarded by GCMRegistrar.class
private static Context sRetryReceiverContext;
// guarded by GCMRegistrar.class
private static String sRetryReceiverClassName;
// guarded by GCMRegistrar.class
private static PendingIntent sAppPendingIntent;
/**
* Checks if the device has the proper dependencies installed.
* <p>
* This method should be called when the application starts to verify that
* the device supports GCM.
*
* @param context application context.
* @throws UnsupportedOperationException if the device does not support GCM.
*/
public static void checkDevice(Context context) {
int version = Build.VERSION.SDK_INT;
if (version < 8) {
throw new UnsupportedOperationException("Device must be at least " +
"API Level 8 (instead of " + version + ")");
}
PackageManager packageManager = context.getPackageManager();
try {
packageManager.getPackageInfo(GSF_PACKAGE, 0);
} catch (NameNotFoundException e) {
throw new UnsupportedOperationException(
"Device does not have package " + GSF_PACKAGE);
}
}
/**
* Checks that the application manifest is properly configured.
* <p>
* A proper configuration means:
* <ol>
* <li>It creates a custom permission called
* {@code PACKAGE_NAME.permission.C2D_MESSAGE}.
* <li>It defines at least one {@link BroadcastReceiver} with category
* {@code PACKAGE_NAME}.
* <li>The {@link BroadcastReceiver}(s) uses the
* {@value com.google.android.gcm.GCMConstants#PERMISSION_GCM_INTENTS}
* permission.
* <li>The {@link BroadcastReceiver}(s) handles the 2 GCM intents
* ({@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_MESSAGE}
* and
* {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK}).
* </ol>
* ...where {@code PACKAGE_NAME} is the application package.
* <p>
* This method should be used during development time to verify that the
* manifest is properly set up, but it doesn't need to be called once the
* application is deployed to the users' devices.
*
* @param context application context.
* @throws IllegalStateException if any of the conditions above is not met.
*/
public static void checkManifest(Context context) {
PackageManager packageManager = context.getPackageManager();
String packageName = context.getPackageName();
String permissionName = packageName + ".permission.C2D_MESSAGE";
// check permission
try {
packageManager.getPermissionInfo(permissionName,
PackageManager.GET_PERMISSIONS);
} catch (NameNotFoundException e) {
throw new IllegalStateException(
"Application does not define permission " + permissionName);
}
// check receivers
PackageInfo receiversInfo;
try {
receiversInfo = packageManager.getPackageInfo(
packageName, PackageManager.GET_RECEIVERS);
} catch (NameNotFoundException e) {
throw new IllegalStateException(
"Could not get receivers for package " + packageName);
}
ActivityInfo[] receivers = receiversInfo.receivers;
if (receivers == null || receivers.length == 0) {
throw new IllegalStateException("No receiver for package " +
packageName);
}
log(context, Log.VERBOSE, "number of receivers for %s: %d",
packageName, receivers.length);
Set<String> allowedReceivers = new HashSet<String>();
for (ActivityInfo receiver : receivers) {
if (GCMConstants.PERMISSION_GCM_INTENTS.equals(
receiver.permission)) {
allowedReceivers.add(receiver.name);
}
}
if (allowedReceivers.isEmpty()) {
throw new IllegalStateException("No receiver allowed to receive " +
GCMConstants.PERMISSION_GCM_INTENTS);
}
checkReceiver(context, allowedReceivers,
GCMConstants.INTENT_FROM_GCM_REGISTRATION_CALLBACK);
checkReceiver(context, allowedReceivers,
GCMConstants.INTENT_FROM_GCM_MESSAGE);
}
private static void checkReceiver(Context context,
Set<String> allowedReceivers, String action) {
PackageManager pm = context.getPackageManager();
String packageName = context.getPackageName();
Intent intent = new Intent(action);
intent.setPackage(packageName);
List<ResolveInfo> receivers = pm.queryBroadcastReceivers(intent,
PackageManager.GET_INTENT_FILTERS);
if (receivers.isEmpty()) {
throw new IllegalStateException("No receivers for action " +
action);
}
log(context, Log.VERBOSE, "Found %d receivers for action %s",
receivers.size(), action);
// make sure receivers match
for (ResolveInfo receiver : receivers) {
String name = receiver.activityInfo.name;
if (!allowedReceivers.contains(name)) {
throw new IllegalStateException("Receiver " + name +
" is not set with permission " +
GCMConstants.PERMISSION_GCM_INTENTS);
}
}
}
/**
* Initiate messaging registration for the current application.
* <p>
* The result will be returned as an
* {@link GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK} intent with
* either a {@link GCMConstants#EXTRA_REGISTRATION_ID} or
* {@link GCMConstants#EXTRA_ERROR}.
*
* @param context application context.
* @param senderIds Google Project ID of the accounts authorized to send
* messages to this application.
* @throws IllegalStateException if device does not have all GCM
* dependencies installed.
*/
public static void register(Context context, String... senderIds) {
GCMRegistrar.resetBackoff(context);
internalRegister(context, senderIds);
}
static void internalRegister(Context context, String... senderIds) {
String flatSenderIds = getFlatSenderIds(senderIds);
log(context, Log.VERBOSE, "Registering app for senders %s",
flatSenderIds);
Intent intent = new Intent(GCMConstants.INTENT_TO_GCM_REGISTRATION);
intent.setPackage(GSF_PACKAGE);
setPackageNameExtra(context, intent);
intent.putExtra(GCMConstants.EXTRA_SENDER, flatSenderIds);
context.startService(intent);
}
/**
* Unregister the application.
* <p>
* The result will be returned as an
* {@link GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK} intent with an
* {@link GCMConstants#EXTRA_UNREGISTERED} extra.
*/
public static void unregister(Context context) {
GCMRegistrar.resetBackoff(context);
internalUnregister(context);
}
static void internalUnregister(Context context) {
log(context, Log.VERBOSE, "Unregistering app");
Intent intent = new Intent(GCMConstants.INTENT_TO_GCM_UNREGISTRATION);
intent.setPackage(GSF_PACKAGE);
setPackageNameExtra(context, intent);
context.startService(intent);
}
static String getFlatSenderIds(String... senderIds) {
if (senderIds == null || senderIds.length == 0) {
throw new IllegalArgumentException("No senderIds");
}
StringBuilder builder = new StringBuilder(senderIds[0]);
for (int i = 1; i < senderIds.length; i++) {
builder.append(',').append(senderIds[i]);
}
return builder.toString();
}
/**
* Clear internal resources.
*
* <p>
* This method should be called by the main activity's {@code onDestroy()}
* method.
*/
public static synchronized void onDestroy(Context context) {
if (sRetryReceiver != null) {
log(context, Log.VERBOSE, "Unregistering retry receiver");
sRetryReceiverContext.unregisterReceiver(sRetryReceiver);
sRetryReceiver = null;
sRetryReceiverContext = null;
}
}
static synchronized void cancelAppPendingIntent() {
if (sAppPendingIntent != null) {
sAppPendingIntent.cancel();
sAppPendingIntent = null;
}
}
private synchronized static void setPackageNameExtra(Context context,
Intent intent) {
if (sAppPendingIntent == null) {
log(context, Log.VERBOSE,
"Creating pending intent to get package name");
sAppPendingIntent = PendingIntent.getBroadcast(context, 0,
new Intent(), 0);
}
intent.putExtra(GCMConstants.EXTRA_APPLICATION_PENDING_INTENT,
sAppPendingIntent);
}
/**
* Lazy initializes the {@link GCMBroadcastReceiver} instance.
*/
static synchronized void setRetryBroadcastReceiver(Context context) {
if (sRetryReceiver == null) {
if (sRetryReceiverClassName == null) {
// should never happen
log(context, Log.ERROR,
"internal error: retry receiver class not set yet");
sRetryReceiver = new GCMBroadcastReceiver();
} else {
Class<?> clazz;
try {
clazz = Class.forName(sRetryReceiverClassName);
sRetryReceiver = (GCMBroadcastReceiver) clazz.newInstance();
} catch (Exception e) {
log(context, Log.ERROR, "Could not create instance of %s. "
+ "Using %s directly.", sRetryReceiverClassName,
GCMBroadcastReceiver.class.getName());
sRetryReceiver = new GCMBroadcastReceiver();
}
}
String category = context.getPackageName();
IntentFilter filter = new IntentFilter(
GCMConstants.INTENT_FROM_GCM_LIBRARY_RETRY);
filter.addCategory(category);
log(context, Log.VERBOSE, "Registering retry receiver");
sRetryReceiverContext = context;
sRetryReceiverContext.registerReceiver(sRetryReceiver, filter);
}
}
/**
* Sets the name of the retry receiver class.
*/
static synchronized void setRetryReceiverClassName(Context context,
String className) {
log(context, Log.VERBOSE,
"Setting the name of retry receiver class to %s", className);
sRetryReceiverClassName = className;
}
/**
* Gets the current registration id for application on GCM service.
* <p>
* If result is empty, the registration has failed.
*
* @return registration id, or empty string if the registration is not
* complete.
*/
public static String getRegistrationId(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
String registrationId = prefs.getString(PROPERTY_REG_ID, "");
// check if app was updated; if so, it must clear registration id to
// avoid a race condition if GCM sends a message
int oldVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
int newVersion = getAppVersion(context);
if (oldVersion != Integer.MIN_VALUE && oldVersion != newVersion) {
log(context, Log.VERBOSE, "App version changed from %d to %d;"
+ "resetting registration id", oldVersion, newVersion);
clearRegistrationId(context);
registrationId = "";
}
return registrationId;
}
/**
* Checks whether the application was successfully registered on GCM
* service.
*/
public static boolean isRegistered(Context context) {
return getRegistrationId(context).length() > 0;
}
/**
* Clears the registration id in the persistence store.
*
* <p>As a side-effect, it also expires the registeredOnServer property.
*
* @param context application's context.
* @return old registration id.
*/
static String clearRegistrationId(Context context) {
setRegisteredOnServer(context, null, 0);
return setRegistrationId(context, "");
}
/**
* Sets the registration id in the persistence store.
*
* @param context application's context.
* @param regId registration id
*/
static String setRegistrationId(Context context, String regId) {
final SharedPreferences prefs = getGCMPreferences(context);
String oldRegistrationId = prefs.getString(PROPERTY_REG_ID, "");
int appVersion = getAppVersion(context);
log(context, Log.VERBOSE, "Saving regId on app version %d", appVersion);
Editor editor = prefs.edit();
editor.putString(PROPERTY_REG_ID, regId);
editor.putInt(PROPERTY_APP_VERSION, appVersion);
editor.commit();
return oldRegistrationId;
}
/**
* Sets whether the device was successfully registered in the server side.
*/
public static void setRegisteredOnServer(Context context, boolean flag) {
// set the flag's expiration date
long lifespan = getRegisterOnServerLifespan(context);
long expirationTime = System.currentTimeMillis() + lifespan;
setRegisteredOnServer(context, flag, expirationTime);
}
private static void setRegisteredOnServer(Context context, Boolean flag,
long expirationTime) {
final SharedPreferences prefs = getGCMPreferences(context);
Editor editor = prefs.edit();
if (flag != null) {
editor.putBoolean(PROPERTY_ON_SERVER, flag);
log(context, Log.VERBOSE,
"Setting registeredOnServer flag as %b until %s",
flag, new Timestamp(expirationTime));
} else {
log(context, Log.VERBOSE,
"Setting registeredOnServer expiration to %s",
new Timestamp(expirationTime));
}
editor.putLong(PROPERTY_ON_SERVER_EXPIRATION_TIME, expirationTime);
editor.commit();
}
/**
* Checks whether the device was successfully registered in the server side,
* as set by {@link #setRegisteredOnServer(Context, boolean)}.
*
* <p>To avoid the scenario where the device sends the registration to the
* server but the server loses it, this flag has an expiration date, which
* is {@link #DEFAULT_ON_SERVER_LIFESPAN_MS} by default (but can be changed
* by {@link #setRegisterOnServerLifespan(Context, long)}).
*/
public static boolean isRegisteredOnServer(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
boolean isRegistered = prefs.getBoolean(PROPERTY_ON_SERVER, false);
log(context, Log.VERBOSE, "Is registered on server: %b", isRegistered);
if (isRegistered) {
// checks if the information is not stale
long expirationTime =
prefs.getLong(PROPERTY_ON_SERVER_EXPIRATION_TIME, -1);
if (System.currentTimeMillis() > expirationTime) {
log(context, Log.VERBOSE, "flag expired on: %s",
new Timestamp(expirationTime));
return false;
}
}
return isRegistered;
}
/**
* Gets how long (in milliseconds) the {@link #isRegistered(Context)}
* property is valid.
*
* @return value set by {@link #setRegisteredOnServer(Context, boolean)} or
* {@link #DEFAULT_ON_SERVER_LIFESPAN_MS} if not set.
*/
public static long getRegisterOnServerLifespan(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
long lifespan = prefs.getLong(PROPERTY_ON_SERVER_LIFESPAN,
DEFAULT_ON_SERVER_LIFESPAN_MS);
return lifespan;
}
/**
* Sets how long (in milliseconds) the {@link #isRegistered(Context)}
* flag is valid.
*/
public static void setRegisterOnServerLifespan(Context context,
long lifespan) {
final SharedPreferences prefs = getGCMPreferences(context);
Editor editor = prefs.edit();
editor.putLong(PROPERTY_ON_SERVER_LIFESPAN, lifespan);
editor.commit();
}
/**
* Gets the application version.
*/
private static int getAppVersion(Context context) {
try {
PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode;
} catch (NameNotFoundException e) {
// should never happen
throw new RuntimeException("Coult not get package name: " + e);
}
}
/**
* Resets the backoff counter.
* <p>
* This method should be called after a GCM call succeeds.
*
* @param context application's context.
*/
static void resetBackoff(Context context) {
log(context, Log.VERBOSE, "Resetting backoff");
setBackoff(context, DEFAULT_BACKOFF_MS);
}
/**
* Gets the current backoff counter.
*
* @param context application's context.
* @return current backoff counter, in milliseconds.
*/
static int getBackoff(Context context) {
final SharedPreferences prefs = getGCMPreferences(context);
return prefs.getInt(BACKOFF_MS, DEFAULT_BACKOFF_MS);
}
/**
* Sets the backoff counter.
* <p>
* This method should be called after a GCM call fails, passing an
* exponential value.
*
* @param context application's context.
* @param backoff new backoff counter, in milliseconds.
*/
static void setBackoff(Context context, int backoff) {
final SharedPreferences prefs = getGCMPreferences(context);
Editor editor = prefs.edit();
editor.putInt(BACKOFF_MS, backoff);
editor.commit();
}
private static SharedPreferences getGCMPreferences(Context context) {
return context.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE);
}
/**
* Logs a message on logcat.
*
* @param context application's context.
* @param priority logging priority
* @param template message's template
* @param args list of arguments
*/
private static void log(Context context, int priority, String template,
Object... args) {
if (Log.isLoggable(TAG, priority)) {
String message = String.format(template, args);
Log.println(priority, TAG, "[" + context.getPackageName() + "]: "
+ message);
}
}
private GCMRegistrar() {
throw new UnsupportedOperationException();
}
}
| Java |
/*
* Copyright 2012 Google 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.google.android.gcm;
/**
* Constants used by the GCM library.
*
* @deprecated GCM library has been moved to Google Play Services
* (com.google.android.gms.gcm), and this version is no longer supported.
*/
@Deprecated
public final class GCMConstants {
/**
* Intent sent to GCM to register the application.
*/
public static final String INTENT_TO_GCM_REGISTRATION =
"com.google.android.c2dm.intent.REGISTER";
/**
* Intent sent to GCM to unregister the application.
*/
public static final String INTENT_TO_GCM_UNREGISTRATION =
"com.google.android.c2dm.intent.UNREGISTER";
/**
* Intent sent by GCM indicating with the result of a registration request.
*/
public static final String INTENT_FROM_GCM_REGISTRATION_CALLBACK =
"com.google.android.c2dm.intent.REGISTRATION";
/**
* Intent used by the GCM library to indicate that the registration call
* should be retried.
*/
public static final String INTENT_FROM_GCM_LIBRARY_RETRY =
"com.google.android.gcm.intent.RETRY";
/**
* Intent sent by GCM containing a message.
*/
public static final String INTENT_FROM_GCM_MESSAGE =
"com.google.android.c2dm.intent.RECEIVE";
/**
* Extra used on
* {@value com.google.android.gcm.GCMConstants#INTENT_TO_GCM_REGISTRATION}
* to indicate which senders (Google API project ids) can send messages to
* the application.
*/
public static final String EXTRA_SENDER = "sender";
/**
* Extra used on
* {@value com.google.android.gcm.GCMConstants#INTENT_TO_GCM_REGISTRATION}
* to get the application info.
*/
public static final String EXTRA_APPLICATION_PENDING_INTENT = "app";
/**
* Extra used on
* {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK}
* to indicate that the application has been unregistered.
*/
public static final String EXTRA_UNREGISTERED = "unregistered";
/**
* Extra used on
* {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK}
* to indicate an error when the registration fails.
* See constants starting with ERROR_ for possible values.
*/
public static final String EXTRA_ERROR = "error";
/**
* Extra used on
* {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_REGISTRATION_CALLBACK}
* to indicate the registration id when the registration succeeds.
*/
public static final String EXTRA_REGISTRATION_ID = "registration_id";
/**
* Type of message present in the
* {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_MESSAGE}
* intent.
* This extra is only set for special messages sent from GCM, not for
* messages originated from the application.
*/
public static final String EXTRA_SPECIAL_MESSAGE = "message_type";
/**
* Special message indicating the server deleted the pending messages.
*/
public static final String VALUE_DELETED_MESSAGES = "deleted_messages";
/**
* Number of messages deleted by the server because the device was idle.
* Present only on messages of special type
* {@value com.google.android.gcm.GCMConstants#VALUE_DELETED_MESSAGES}
*/
public static final String EXTRA_TOTAL_DELETED = "total_deleted";
/**
* Extra used on
* {@value com.google.android.gcm.GCMConstants#INTENT_FROM_GCM_MESSAGE}
* to indicate which sender (Google API project id) sent the message.
*/
public static final String EXTRA_FROM = "from";
/**
* Permission necessary to receive GCM intents.
*/
public static final String PERMISSION_GCM_INTENTS =
"com.google.android.c2dm.permission.SEND";
/**
* @see GCMBroadcastReceiver
*/
public static final String DEFAULT_INTENT_SERVICE_CLASS_NAME =
".GCMIntentService";
/**
* The device can't read the response, or there was a 500/503 from the
* server that can be retried later. The application should use exponential
* back off and retry.
*/
public static final String ERROR_SERVICE_NOT_AVAILABLE =
"SERVICE_NOT_AVAILABLE";
/**
* There is no Google account on the phone. The application should ask the
* user to open the account manager and add a Google account.
*/
public static final String ERROR_ACCOUNT_MISSING =
"ACCOUNT_MISSING";
/**
* Bad password. The application should ask the user to enter his/her
* password, and let user retry manually later. Fix on the device side.
*/
public static final String ERROR_AUTHENTICATION_FAILED =
"AUTHENTICATION_FAILED";
/**
* The request sent by the phone does not contain the expected parameters.
* This phone doesn't currently support GCM.
*/
public static final String ERROR_INVALID_PARAMETERS =
"INVALID_PARAMETERS";
/**
* The sender account is not recognized. Fix on the device side.
*/
public static final String ERROR_INVALID_SENDER =
"INVALID_SENDER";
/**
* Incorrect phone registration with Google. This phone doesn't currently
* support GCM.
*/
public static final String ERROR_PHONE_REGISTRATION_ERROR =
"PHONE_REGISTRATION_ERROR";
private GCMConstants() {
throw new UnsupportedOperationException();
}
}
| Java |
/*
* Copyright 2012 Google 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.google.android.gcm;
import android.util.Log;
/**
* Custom logger.
*
* @deprecated GCM library has been moved to Google Play Services
* (com.google.android.gms.gcm), and this version is no longer supported.
*/
@Deprecated
class GCMLogger {
private final String mTag;
// can't use class name on TAG since size is limited to 23 chars
private final String mLogPrefix;
GCMLogger(String tag, String logPrefix) {
mTag = tag;
mLogPrefix = logPrefix;
}
/**
* Logs a message on logcat.
*
* @param priority logging priority
* @param template message's template
* @param args list of arguments
*/
protected void log(int priority, String template, Object... args) {
if (Log.isLoggable(mTag, priority)) {
String message = String.format(template, args);
Log.println(priority, mTag, mLogPrefix + message);
}
}
}
| Java |
/*
* Copyright 2012 Google 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.google.android.gcm;
import static com.google.android.gcm.GCMConstants.DEFAULT_INTENT_SERVICE_CLASS_NAME;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
/**
* {@link BroadcastReceiver} that receives GCM messages and delivers them to
* an application-specific {@link GCMBaseIntentService} subclass.
* <p>
* By default, the {@link GCMBaseIntentService} class belongs to the application
* main package and is named
* {@link GCMConstants#DEFAULT_INTENT_SERVICE_CLASS_NAME}. To use a new class,
* the {@link #getGCMIntentServiceClassName(Context)} must be overridden.
*
* @deprecated GCM library has been moved to Google Play Services
* (com.google.android.gms.gcm), and this version is no longer supported.
*/
@Deprecated
public class GCMBroadcastReceiver extends BroadcastReceiver {
private static boolean mReceiverSet = false;
private final GCMLogger mLogger = new GCMLogger("GCMBroadcastReceiver",
"[" + getClass().getName() + "]: ");
@Override
public final void onReceive(Context context, Intent intent) {
mLogger.log(Log.VERBOSE, "onReceive: %s", intent.getAction());
// do a one-time check if app is using a custom GCMBroadcastReceiver
if (!mReceiverSet) {
mReceiverSet = true;
GCMRegistrar.setRetryReceiverClassName(context,
getClass().getName());
}
String className = getGCMIntentServiceClassName(context);
mLogger.log(Log.VERBOSE, "GCM IntentService class: %s", className);
// Delegates to the application-specific intent service.
GCMBaseIntentService.runIntentInService(context, intent, className);
setResult(Activity.RESULT_OK, null /* data */, null /* extra */);
}
/**
* Gets the class name of the intent service that will handle GCM messages.
*/
protected String getGCMIntentServiceClassName(Context context) {
return getDefaultIntentServiceClassName(context);
}
/**
* Gets the default class name of the intent service that will handle GCM
* messages.
*/
static final String getDefaultIntentServiceClassName(Context context) {
String className = context.getPackageName() +
DEFAULT_INTENT_SERVICE_CLASS_NAME;
return className;
}
}
| Java |
/** Automatically generated file. DO NOT MODIFY */
package com.google.android.gcm;
public final class BuildConfig {
public final static boolean DEBUG = true;
} | Java |
/*
* Copyright 2012 Google 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.google.android.gcm.demo.server;
import com.google.android.gcm.server.Constants;
import com.google.android.gcm.server.Message;
import com.google.android.gcm.server.MulticastResult;
import com.google.android.gcm.server.Result;
import com.google.android.gcm.server.Sender;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet that adds a new message to all registered devices.
* <p>
* This servlet is used just by the browser (i.e., not device).
*/
@SuppressWarnings("serial")
public class SendAllMessagesServlet extends BaseServlet {
private static final int MULTICAST_SIZE = 1000;
private Sender sender;
private static final Executor threadPool = Executors.newFixedThreadPool(5);
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
sender = newSender(config);
}
/**
* Creates the {@link Sender} based on the servlet settings.
*/
protected Sender newSender(ServletConfig config) {
String key = (String) config.getServletContext()
.getAttribute(ApiKeyInitializer.ATTRIBUTE_ACCESS_KEY);
return new Sender(key);
}
/**
* Processes the request to add a new message.
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
List<String> devices = Datastore.getDevices();
String status;
if (devices.isEmpty()) {
status = "Message ignored as there is no device registered!";
} else {
// NOTE: check below is for demonstration purposes; a real application
// could always send a multicast, even for just one recipient
if (devices.size() == 1) {
// send a single message using plain post
String registrationId = devices.get(0);
Message message = new Message.Builder().build();
Result result = sender.send(message, registrationId, 5);
status = "Sent message to one device: " + result;
} else {
// send a multicast message using JSON
// must split in chunks of 1000 devices (GCM limit)
int total = devices.size();
List<String> partialDevices = new ArrayList<String>(total);
int counter = 0;
int tasks = 0;
for (String device : devices) {
counter++;
partialDevices.add(device);
int partialSize = partialDevices.size();
if (partialSize == MULTICAST_SIZE || counter == total) {
asyncSend(partialDevices);
partialDevices.clear();
tasks++;
}
}
status = "Asynchronously sending " + tasks + " multicast messages to " +
total + " devices";
}
}
req.setAttribute(HomeServlet.ATTRIBUTE_STATUS, status.toString());
getServletContext().getRequestDispatcher("/home").forward(req, resp);
}
private void asyncSend(List<String> partialDevices) {
// make a copy
final List<String> devices = new ArrayList<String>(partialDevices);
threadPool.execute(new Runnable() {
public void run() {
Message message = new Message.Builder().build();
MulticastResult multicastResult;
try {
multicastResult = sender.send(message, devices, 5);
} catch (IOException e) {
logger.log(Level.SEVERE, "Error posting messages", e);
return;
}
List<Result> results = multicastResult.getResults();
// analyze the results
for (int i = 0; i < devices.size(); i++) {
String regId = devices.get(i);
Result result = results.get(i);
String messageId = result.getMessageId();
if (messageId != null) {
logger.fine("Succesfully sent message to device: " + regId +
"; messageId = " + messageId);
String canonicalRegId = result.getCanonicalRegistrationId();
if (canonicalRegId != null) {
// same device has more than on registration id: update it
logger.info("canonicalRegId " + canonicalRegId);
Datastore.updateRegistration(regId, canonicalRegId);
}
} else {
String error = result.getErrorCodeName();
if (error.equals(Constants.ERROR_NOT_REGISTERED)) {
// application has been removed from device - unregister it
logger.info("Unregistered device: " + regId);
Datastore.unregister(regId);
} else {
logger.severe("Error sending message to " + regId + ": " + error);
}
}
}
}});
}
}
| Java |
/*
* Copyright 2012 Google 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.google.android.gcm.demo.server;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet that unregisters a device, whose registration id is identified by
* {@link #PARAMETER_REG_ID}.
* <p>
* The client app should call this servlet everytime it receives a
* {@code com.google.android.c2dm.intent.REGISTRATION} with an
* {@code unregistered} extra.
*/
@SuppressWarnings("serial")
public class UnregisterServlet extends BaseServlet {
private static final String PARAMETER_REG_ID = "regId";
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException {
String regId = getParameter(req, PARAMETER_REG_ID);
Datastore.unregister(regId);
setSuccess(resp);
}
}
| Java |
/*
* Copyright 2012 Google 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.google.android.gcm.demo.server;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet that registers a device, whose registration id is identified by
* {@link #PARAMETER_REG_ID}.
*
* <p>
* The client app should call this servlet everytime it receives a
* {@code com.google.android.c2dm.intent.REGISTRATION C2DM} intent without an
* error or {@code unregistered} extra.
*/
@SuppressWarnings("serial")
public class RegisterServlet extends BaseServlet {
private static final String PARAMETER_REG_ID = "regId";
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException {
String regId = getParameter(req, PARAMETER_REG_ID);
Datastore.register(regId);
setSuccess(resp);
}
}
| Java |
/*
* Copyright 2012 Google 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.google.android.gcm.demo.server;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
/**
* Simple implementation of a data store using standard Java collections.
* <p>
* This class is thread-safe but not persistent (it will lost the data when the
* app is restarted) - it is meant just as an example.
*/
public final class Datastore {
private static final List<String> regIds = new ArrayList<String>();
private static final Logger logger =
Logger.getLogger(Datastore.class.getName());
private Datastore() {
throw new UnsupportedOperationException();
}
/**
* Registers a device.
*/
public static void register(String regId) {
logger.info("Registering " + regId);
synchronized (regIds) {
regIds.add(regId);
}
}
/**
* Unregisters a device.
*/
public static void unregister(String regId) {
logger.info("Unregistering " + regId);
synchronized (regIds) {
regIds.remove(regId);
}
}
/**
* Updates the registration id of a device.
*/
public static void updateRegistration(String oldId, String newId) {
logger.info("Updating " + oldId + " to " + newId);
synchronized (regIds) {
regIds.remove(oldId);
regIds.add(newId);
}
}
/**
* Gets all registered devices.
*/
public static List<String> getDevices() {
synchronized (regIds) {
return new ArrayList<String>(regIds);
}
}
}
| Java |
/*
* Copyright 2012 Google 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.google.android.gcm.demo.server;
import java.io.IOException;
import java.util.Enumeration;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Skeleton class for all servlets in this package.
*/
@SuppressWarnings("serial")
abstract class BaseServlet extends HttpServlet {
// change to true to allow GET calls
static final boolean DEBUG = true;
protected final Logger logger = Logger.getLogger(getClass().getName());
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
if (DEBUG) {
doPost(req, resp);
} else {
super.doGet(req, resp);
}
}
protected String getParameter(HttpServletRequest req, String parameter)
throws ServletException {
String value = req.getParameter(parameter);
if (isEmptyOrNull(value)) {
if (DEBUG) {
StringBuilder parameters = new StringBuilder();
@SuppressWarnings("unchecked")
Enumeration<String> names = req.getParameterNames();
while (names.hasMoreElements()) {
String name = names.nextElement();
String param = req.getParameter(name);
parameters.append(name).append("=").append(param).append("\n");
}
logger.fine("parameters: " + parameters);
}
throw new ServletException("Parameter " + parameter + " not found");
}
return value.trim();
}
protected String getParameter(HttpServletRequest req, String parameter,
String defaultValue) {
String value = req.getParameter(parameter);
if (isEmptyOrNull(value)) {
value = defaultValue;
}
return value.trim();
}
protected void setSuccess(HttpServletResponse resp) {
setSuccess(resp, 0);
}
protected void setSuccess(HttpServletResponse resp, int size) {
resp.setStatus(HttpServletResponse.SC_OK);
resp.setContentType("text/plain");
resp.setContentLength(size);
}
protected boolean isEmptyOrNull(String value) {
return value == null || value.trim().length() == 0;
}
}
| Java |
/*
* Copyright 2012 Google 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.google.android.gcm.demo.server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
/**
* Context initializer that loads the API key from a
* {@value #PATH} file located in the classpath (typically under
* {@code WEB-INF/classes}).
*/
public class ApiKeyInitializer implements ServletContextListener {
static final String ATTRIBUTE_ACCESS_KEY = "apiKey";
private static final String PATH = "/api.key";
private final Logger logger = Logger.getLogger(getClass().getName());
public void contextInitialized(ServletContextEvent event) {
logger.info("Reading " + PATH + " from resources (probably from " +
"WEB-INF/classes");
String key = getKey();
event.getServletContext().setAttribute(ATTRIBUTE_ACCESS_KEY, key);
}
/**
* Gets the access key.
*/
protected String getKey() {
InputStream stream = Thread.currentThread().getContextClassLoader()
.getResourceAsStream(PATH);
if (stream == null) {
throw new IllegalStateException("Could not find file " + PATH +
" on web resources)");
}
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
try {
String key = reader.readLine();
return key;
} catch (IOException e) {
throw new RuntimeException("Could not read file " + PATH, e);
} finally {
try {
reader.close();
} catch (IOException e) {
logger.log(Level.WARNING, "Exception closing " + PATH, e);
}
}
}
public void contextDestroyed(ServletContextEvent event) {
}
}
| Java |
/*
* Copyright 2012 Google 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.google.android.gcm.demo.server;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet that adds display number of devices and button to send a message.
* <p>
* This servlet is used just by the browser (i.e., not device) and contains the
* main page of the demo app.
*/
@SuppressWarnings("serial")
public class HomeServlet extends BaseServlet {
static final String ATTRIBUTE_STATUS = "status";
/**
* Displays the existing messages and offer the option to send a new one.
*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.print("<html><body>");
out.print("<head>");
out.print(" <title>GCM Demo</title>");
out.print(" <link rel='icon' href='favicon.png'/>");
out.print("</head>");
String status = (String) req.getAttribute(ATTRIBUTE_STATUS);
if (status != null) {
out.print(status);
}
List<String> devices = Datastore.getDevices();
if (devices.isEmpty()) {
out.print("<h2>No devices registered!</h2>");
} else {
out.print("<h2>" + devices.size() + " device(s) registered!</h2>");
out.print("<form name='form' method='POST' action='sendAll'>");
out.print("<input type='submit' value='Send Message' />");
out.print("</form>");
}
out.print("</body></html>");
resp.setStatus(HttpServletResponse.SC_OK);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
doGet(req, resp);
}
}
| Java |
/*
* Copyright 2012 Google 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.google.android.gcm.demo.app;
import static com.google.android.gcm.demo.app.CommonUtilities.DISPLAY_MESSAGE_ACTION;
import static com.google.android.gcm.demo.app.CommonUtilities.EXTRA_MESSAGE;
import static com.google.android.gcm.demo.app.CommonUtilities.SENDER_ID;
import static com.google.android.gcm.demo.app.CommonUtilities.SERVER_URL;
import com.google.android.gcm.GCMRegistrar;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;
/**
* Main UI for the demo app.
*/
public class DemoActivity extends Activity {
TextView mDisplay;
AsyncTask<Void, Void, Void> mRegisterTask;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
checkNotNull(SERVER_URL, "SERVER_URL");
checkNotNull(SENDER_ID, "SENDER_ID");
// Make sure the device has the proper dependencies.
GCMRegistrar.checkDevice(this);
// Make sure the manifest was properly set - comment out this line
// while developing the app, then uncomment it when it's ready.
GCMRegistrar.checkManifest(this);
setContentView(R.layout.main);
mDisplay = (TextView) findViewById(R.id.display);
registerReceiver(mHandleMessageReceiver,
new IntentFilter(DISPLAY_MESSAGE_ACTION));
final String regId = GCMRegistrar.getRegistrationId(this);
if (regId.equals("")) {
// Automatically registers application on startup.
GCMRegistrar.register(this, SENDER_ID);
} else {
// Device is already registered on GCM, check server.
if (GCMRegistrar.isRegisteredOnServer(this)) {
// Skips registration.
mDisplay.append(getString(R.string.already_registered) + "\n");
} else {
// Try to register again, but not in the UI thread.
// It's also necessary to cancel the thread onDestroy(),
// hence the use of AsyncTask instead of a raw thread.
final Context context = this;
mRegisterTask = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
ServerUtilities.register(context, regId);
return null;
}
@Override
protected void onPostExecute(Void result) {
mRegisterTask = null;
}
};
mRegisterTask.execute(null, null, null);
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
/*
* Typically, an application registers automatically, so options
* below are disabled. Uncomment them if you want to manually
* register or unregister the device (you will also need to
* uncomment the equivalent options on options_menu.xml).
*/
/*
case R.id.options_register:
GCMRegistrar.register(this, SENDER_ID);
return true;
case R.id.options_unregister:
GCMRegistrar.unregister(this);
return true;
*/
case R.id.options_clear:
mDisplay.setText(null);
return true;
case R.id.options_exit:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onDestroy() {
if (mRegisterTask != null) {
mRegisterTask.cancel(true);
}
unregisterReceiver(mHandleMessageReceiver);
GCMRegistrar.onDestroy(this);
super.onDestroy();
}
private void checkNotNull(Object reference, String name) {
if (reference == null) {
throw new NullPointerException(
getString(R.string.error_config, name));
}
}
private final BroadcastReceiver mHandleMessageReceiver =
new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String newMessage = intent.getExtras().getString(EXTRA_MESSAGE);
mDisplay.append(newMessage + "\n");
}
};
} | Java |
/*
* Copyright 2012 Google 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.google.android.gcm.demo.app;
import static com.google.android.gcm.demo.app.CommonUtilities.SERVER_URL;
import static com.google.android.gcm.demo.app.CommonUtilities.TAG;
import static com.google.android.gcm.demo.app.CommonUtilities.displayMessage;
import com.google.android.gcm.GCMRegistrar;
import android.content.Context;
import android.util.Log;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
/**
* Helper class used to communicate with the demo server.
*/
public final class ServerUtilities {
private static final int MAX_ATTEMPTS = 5;
private static final int BACKOFF_MILLI_SECONDS = 2000;
private static final Random random = new Random();
/**
* Register this account/device pair within the server.
*
*/
static void register(final Context context, final String regId) {
Log.i(TAG, "registering device (regId = " + regId + ")");
String serverUrl = SERVER_URL + "/register";
Map<String, String> params = new HashMap<String, String>();
params.put("regId", regId);
long backoff = BACKOFF_MILLI_SECONDS + random.nextInt(1000);
// Once GCM returns a registration id, we need to register it in the
// demo server. As the server might be down, we will retry it a couple
// times.
for (int i = 1; i <= MAX_ATTEMPTS; i++) {
Log.d(TAG, "Attempt #" + i + " to register");
try {
displayMessage(context, context.getString(
R.string.server_registering, i, MAX_ATTEMPTS));
post(serverUrl, params);
GCMRegistrar.setRegisteredOnServer(context, true);
String message = context.getString(R.string.server_registered);
CommonUtilities.displayMessage(context, message);
return;
} catch (IOException e) {
// Here we are simplifying and retrying on any error; in a real
// application, it should retry only on unrecoverable errors
// (like HTTP error code 503).
Log.e(TAG, "Failed to register on attempt " + i + ":" + e);
if (i == MAX_ATTEMPTS) {
break;
}
try {
Log.d(TAG, "Sleeping for " + backoff + " ms before retry");
Thread.sleep(backoff);
} catch (InterruptedException e1) {
// Activity finished before we complete - exit.
Log.d(TAG, "Thread interrupted: abort remaining retries!");
Thread.currentThread().interrupt();
return;
}
// increase backoff exponentially
backoff *= 2;
}
}
String message = context.getString(R.string.server_register_error,
MAX_ATTEMPTS);
CommonUtilities.displayMessage(context, message);
}
/**
* Unregister this account/device pair within the server.
*/
static void unregister(final Context context, final String regId) {
Log.i(TAG, "unregistering device (regId = " + regId + ")");
String serverUrl = SERVER_URL + "/unregister";
Map<String, String> params = new HashMap<String, String>();
params.put("regId", regId);
try {
post(serverUrl, params);
GCMRegistrar.setRegisteredOnServer(context, false);
String message = context.getString(R.string.server_unregistered);
CommonUtilities.displayMessage(context, message);
} catch (IOException e) {
// At this point the device is unregistered from GCM, but still
// registered in the server.
// We could try to unregister again, but it is not necessary:
// if the server tries to send a message to the device, it will get
// a "NotRegistered" error message and should unregister the device.
String message = context.getString(R.string.server_unregister_error,
e.getMessage());
CommonUtilities.displayMessage(context, message);
}
}
/**
* Issue a POST request to the server.
*
* @param endpoint POST address.
* @param params request parameters.
*
* @throws IOException propagated from POST.
*/
private static void post(String endpoint, Map<String, String> params)
throws IOException {
URL url;
try {
url = new URL(endpoint);
} catch (MalformedURLException e) {
throw new IllegalArgumentException("invalid url: " + endpoint);
}
StringBuilder bodyBuilder = new StringBuilder();
Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
// constructs the POST body using the parameters
while (iterator.hasNext()) {
Entry<String, String> param = iterator.next();
bodyBuilder.append(param.getKey()).append('=')
.append(param.getValue());
if (iterator.hasNext()) {
bodyBuilder.append('&');
}
}
String body = bodyBuilder.toString();
Log.v(TAG, "Posting '" + body + "' to " + url);
byte[] bytes = body.getBytes();
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setFixedLengthStreamingMode(bytes.length);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
// post the request
OutputStream out = conn.getOutputStream();
out.write(bytes);
out.close();
// handle the response
int status = conn.getResponseCode();
if (status != 200) {
throw new IOException("Post failed with error code " + status);
}
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
}
| Java |
/*
* Copyright 2012 Google 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.google.android.gcm.demo.app;
import android.content.Context;
import android.content.Intent;
/**
* Helper class providing methods and constants common to other classes in the
* app.
*/
public final class CommonUtilities {
/**
* Base URL of the Demo Server (such as http://my_host:8080/gcm-demo)
*/
static final String SERVER_URL = null;
/**
* Google API project id registered to use GCM.
*/
static final String SENDER_ID = null;
/**
* Tag used on log messages.
*/
static final String TAG = "GCMDemo";
/**
* Intent used to display a message in the screen.
*/
static final String DISPLAY_MESSAGE_ACTION =
"com.google.android.gcm.demo.app.DISPLAY_MESSAGE";
/**
* Intent's extra that contains the message to be displayed.
*/
static final String EXTRA_MESSAGE = "message";
/**
* Notifies UI to display a message.
* <p>
* This method is defined in the common helper because it's used both by
* the UI and the background service.
*
* @param context application's context.
* @param message message to be displayed.
*/
static void displayMessage(Context context, String message) {
Intent intent = new Intent(DISPLAY_MESSAGE_ACTION);
intent.putExtra(EXTRA_MESSAGE, message);
context.sendBroadcast(intent);
}
}
| Java |
/*
* Copyright 2012 Google 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.google.android.gcm.demo.app;
import static com.google.android.gcm.demo.app.CommonUtilities.SENDER_ID;
import static com.google.android.gcm.demo.app.CommonUtilities.displayMessage;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import com.google.android.gcm.GCMBaseIntentService;
/**
* IntentService responsible for handling GCM messages.
*/
public class GCMIntentService extends GCMBaseIntentService {
@SuppressWarnings("hiding")
private static final String TAG = "GCMIntentService";
public GCMIntentService() {
super(SENDER_ID);
}
@Override
protected void onRegistered(Context context, String registrationId) {
Log.i(TAG, "Device registered: regId = " + registrationId);
displayMessage(context, getString(R.string.gcm_registered,
registrationId));
ServerUtilities.register(context, registrationId);
}
@Override
protected void onUnregistered(Context context, String registrationId) {
Log.i(TAG, "Device unregistered");
displayMessage(context, getString(R.string.gcm_unregistered));
ServerUtilities.unregister(context, registrationId);
}
@Override
protected void onMessage(Context context, Intent intent) {
Log.i(TAG, "Received message. Extras: " + intent.getExtras());
String message = getString(R.string.gcm_message);
displayMessage(context, message);
// notifies user
generateNotification(context, message);
}
@Override
protected void onDeletedMessages(Context context, int total) {
Log.i(TAG, "Received deleted messages notification");
String message = getString(R.string.gcm_deleted, total);
displayMessage(context, message);
// notifies user
generateNotification(context, message);
}
@Override
public void onError(Context context, String errorId) {
Log.i(TAG, "Received error: " + errorId);
displayMessage(context, getString(R.string.gcm_error, errorId));
}
@Override
protected boolean onRecoverableError(Context context, String errorId) {
// log message
Log.i(TAG, "Received recoverable error: " + errorId);
displayMessage(context, getString(R.string.gcm_recoverable_error,
errorId));
return super.onRecoverableError(context, errorId);
}
/**
* Issues a notification to inform the user that server has sent a message.
*/
private static void generateNotification(Context context, String message) {
int icon = R.drawable.ic_stat_gcm;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
String title = context.getString(R.string.app_name);
Intent notificationIntent = new Intent(context, DemoActivity.class);
// set intent so it does not start a new activity
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent =
PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notification);
}
}
| Java |
/*
* Copyright 2012 Google 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.google.android.gcm.demo.server;
import static com.google.appengine.api.taskqueue.TaskOptions.Builder.withUrl;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.appengine.api.taskqueue.TaskOptions.Method;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet that adds a new message to all registered devices.
* <p>
* This servlet is used just by the browser (i.e., not device).
*/
@SuppressWarnings("serial")
public class SendAllMessagesServlet extends BaseServlet {
/**
* Processes the request to add a new message.
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
List<String> devices = Datastore.getDevices();
String status;
if (devices.isEmpty()) {
status = "Message ignored as there is no device registered!";
} else {
Queue queue = QueueFactory.getQueue("gcm");
// NOTE: check below is for demonstration purposes; a real application
// could always send a multicast, even for just one recipient
if (devices.size() == 1) {
// send a single message using plain post
String device = devices.get(0);
queue.add(withUrl("/send").param(
SendMessageServlet.PARAMETER_DEVICE, device));
status = "Single message queued for registration id " + device;
} else {
// send a multicast message using JSON
// must split in chunks of 1000 devices (GCM limit)
int total = devices.size();
List<String> partialDevices = new ArrayList<String>(total);
int counter = 0;
int tasks = 0;
for (String device : devices) {
counter++;
partialDevices.add(device);
int partialSize = partialDevices.size();
if (partialSize == Datastore.MULTICAST_SIZE || counter == total) {
String multicastKey = Datastore.createMulticast(partialDevices);
logger.fine("Queuing " + partialSize + " devices on multicast " +
multicastKey);
TaskOptions taskOptions = TaskOptions.Builder
.withUrl("/send")
.param(SendMessageServlet.PARAMETER_MULTICAST, multicastKey)
.method(Method.POST);
queue.add(taskOptions);
partialDevices.clear();
tasks++;
}
}
status = "Queued tasks to send " + tasks + " multicast messages to " +
total + " devices";
}
}
req.setAttribute(HomeServlet.ATTRIBUTE_STATUS, status.toString());
getServletContext().getRequestDispatcher("/home").forward(req, resp);
}
}
| Java |
/*
* Copyright 2012 Google 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.google.android.gcm.demo.server;
import com.google.android.gcm.server.Constants;
import com.google.android.gcm.server.Message;
import com.google.android.gcm.server.MulticastResult;
import com.google.android.gcm.server.Result;
import com.google.android.gcm.server.Sender;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet that sends a message to a device.
* <p>
* This servlet is invoked by AppEngine's Push Queue mechanism.
*/
@SuppressWarnings("serial")
public class SendMessageServlet extends BaseServlet {
private static final String HEADER_QUEUE_COUNT = "X-AppEngine-TaskRetryCount";
private static final String HEADER_QUEUE_NAME = "X-AppEngine-QueueName";
private static final int MAX_RETRY = 3;
static final String PARAMETER_DEVICE = "device";
static final String PARAMETER_MULTICAST = "multicastKey";
private Sender sender;
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
sender = newSender(config);
}
/**
* Creates the {@link Sender} based on the servlet settings.
*/
protected Sender newSender(ServletConfig config) {
String key = (String) config.getServletContext()
.getAttribute(ApiKeyInitializer.ATTRIBUTE_ACCESS_KEY);
return new Sender(key);
}
/**
* Indicates to App Engine that this task should be retried.
*/
private void retryTask(HttpServletResponse resp) {
resp.setStatus(500);
}
/**
* Indicates to App Engine that this task is done.
*/
private void taskDone(HttpServletResponse resp) {
resp.setStatus(200);
}
/**
* Processes the request to add a new message.
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
if (req.getHeader(HEADER_QUEUE_NAME) == null) {
throw new IOException("Missing header " + HEADER_QUEUE_NAME);
}
String retryCountHeader = req.getHeader(HEADER_QUEUE_COUNT);
logger.fine("retry count: " + retryCountHeader);
if (retryCountHeader != null) {
int retryCount = Integer.parseInt(retryCountHeader);
if (retryCount > MAX_RETRY) {
logger.severe("Too many retries, dropping task");
taskDone(resp);
return;
}
}
String regId = req.getParameter(PARAMETER_DEVICE);
if (regId != null) {
sendSingleMessage(regId, resp);
return;
}
String multicastKey = req.getParameter(PARAMETER_MULTICAST);
if (multicastKey != null) {
sendMulticastMessage(multicastKey, resp);
return;
}
logger.severe("Invalid request!");
taskDone(resp);
return;
}
private Message createMessage() {
Message message = new Message.Builder().build();
return message;
}
private void sendSingleMessage(String regId, HttpServletResponse resp) {
logger.info("Sending message to device " + regId);
Message message = createMessage();
Result result;
try {
result = sender.sendNoRetry(message, regId);
} catch (IOException e) {
logger.log(Level.SEVERE, "Exception posting " + message, e);
taskDone(resp);
return;
}
if (result == null) {
retryTask(resp);
return;
}
if (result.getMessageId() != null) {
logger.info("Succesfully sent message to device " + regId);
String canonicalRegId = result.getCanonicalRegistrationId();
if (canonicalRegId != null) {
// same device has more than on registration id: update it
logger.finest("canonicalRegId " + canonicalRegId);
Datastore.updateRegistration(regId, canonicalRegId);
}
} else {
String error = result.getErrorCodeName();
if (error.equals(Constants.ERROR_NOT_REGISTERED)) {
// application has been removed from device - unregister it
Datastore.unregister(regId);
} else {
logger.severe("Error sending message to device " + regId
+ ": " + error);
}
}
}
private void sendMulticastMessage(String multicastKey,
HttpServletResponse resp) {
// Recover registration ids from datastore
List<String> regIds = Datastore.getMulticast(multicastKey);
Message message = createMessage();
MulticastResult multicastResult;
try {
multicastResult = sender.sendNoRetry(message, regIds);
} catch (IOException e) {
logger.log(Level.SEVERE, "Exception posting " + message, e);
multicastDone(resp, multicastKey);
return;
}
boolean allDone = true;
// check if any registration id must be updated
if (multicastResult.getCanonicalIds() != 0) {
List<Result> results = multicastResult.getResults();
for (int i = 0; i < results.size(); i++) {
String canonicalRegId = results.get(i).getCanonicalRegistrationId();
if (canonicalRegId != null) {
String regId = regIds.get(i);
Datastore.updateRegistration(regId, canonicalRegId);
}
}
}
if (multicastResult.getFailure() != 0) {
// there were failures, check if any could be retried
List<Result> results = multicastResult.getResults();
List<String> retriableRegIds = new ArrayList<String>();
for (int i = 0; i < results.size(); i++) {
String error = results.get(i).getErrorCodeName();
if (error != null) {
String regId = regIds.get(i);
logger.warning("Got error (" + error + ") for regId " + regId);
if (error.equals(Constants.ERROR_NOT_REGISTERED)) {
// application has been removed from device - unregister it
Datastore.unregister(regId);
}
if (error.equals(Constants.ERROR_UNAVAILABLE)) {
retriableRegIds.add(regId);
}
}
}
if (!retriableRegIds.isEmpty()) {
// update task
Datastore.updateMulticast(multicastKey, retriableRegIds);
allDone = false;
retryTask(resp);
}
}
if (allDone) {
multicastDone(resp, multicastKey);
} else {
retryTask(resp);
}
}
private void multicastDone(HttpServletResponse resp, String encodedKey) {
Datastore.deleteMulticast(encodedKey);
taskDone(resp);
}
}
| Java |
/*
* Copyright 2012 Google 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.google.android.gcm.demo.server;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet that unregisters a device, whose registration id is identified by
* {@link #PARAMETER_REG_ID}.
* <p>
* The client app should call this servlet everytime it receives a
* {@code com.google.android.c2dm.intent.REGISTRATION} with an
* {@code unregistered} extra.
*/
@SuppressWarnings("serial")
public class UnregisterServlet extends BaseServlet {
private static final String PARAMETER_REG_ID = "regId";
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException {
String regId = getParameter(req, PARAMETER_REG_ID);
Datastore.unregister(regId);
setSuccess(resp);
}
}
| Java |
/*
* Copyright 2012 Google 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.google.android.gcm.demo.server;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet that registers a device, whose registration id is identified by
* {@link #PARAMETER_REG_ID}.
*
* <p>
* The client app should call this servlet everytime it receives a
* {@code com.google.android.c2dm.intent.REGISTRATION C2DM} intent without an
* error or {@code unregistered} extra.
*/
@SuppressWarnings("serial")
public class RegisterServlet extends BaseServlet {
private static final String PARAMETER_REG_ID = "regId";
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException {
String regId = getParameter(req, PARAMETER_REG_ID);
Datastore.register(regId);
setSuccess(resp);
}
}
| Java |
/*
* Copyright 2012 Google 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.google.android.gcm.demo.server;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Transaction;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;
/**
* Simple implementation of a data store using standard Java collections.
* <p>
* This class is neither persistent (it will lost the data when the app is
* restarted) nor thread safe.
*/
public final class Datastore {
static final int MULTICAST_SIZE = 1000;
private static final String DEVICE_TYPE = "Device";
private static final String DEVICE_REG_ID_PROPERTY = "regId";
private static final String MULTICAST_TYPE = "Multicast";
private static final String MULTICAST_REG_IDS_PROPERTY = "regIds";
private static final FetchOptions DEFAULT_FETCH_OPTIONS = FetchOptions.Builder
.withPrefetchSize(MULTICAST_SIZE).chunkSize(MULTICAST_SIZE);
private static final Logger logger =
Logger.getLogger(Datastore.class.getName());
private static final DatastoreService datastore =
DatastoreServiceFactory.getDatastoreService();
private Datastore() {
throw new UnsupportedOperationException();
}
/**
* Registers a device.
*
* @param regId device's registration id.
*/
public static void register(String regId) {
logger.info("Registering " + regId);
Transaction txn = datastore.beginTransaction();
try {
Entity entity = findDeviceByRegId(regId);
if (entity != null) {
logger.fine(regId + " is already registered; ignoring.");
return;
}
entity = new Entity(DEVICE_TYPE);
entity.setProperty(DEVICE_REG_ID_PROPERTY, regId);
datastore.put(entity);
txn.commit();
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
}
/**
* Unregisters a device.
*
* @param regId device's registration id.
*/
public static void unregister(String regId) {
logger.info("Unregistering " + regId);
Transaction txn = datastore.beginTransaction();
try {
Entity entity = findDeviceByRegId(regId);
if (entity == null) {
logger.warning("Device " + regId + " already unregistered");
} else {
Key key = entity.getKey();
datastore.delete(key);
}
txn.commit();
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
}
/**
* Updates the registration id of a device.
*/
public static void updateRegistration(String oldId, String newId) {
logger.info("Updating " + oldId + " to " + newId);
Transaction txn = datastore.beginTransaction();
try {
Entity entity = findDeviceByRegId(oldId);
if (entity == null) {
logger.warning("No device for registration id " + oldId);
return;
}
entity.setProperty(DEVICE_REG_ID_PROPERTY, newId);
datastore.put(entity);
txn.commit();
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
}
/**
* Gets all registered devices.
*/
public static List<String> getDevices() {
List<String> devices;
Transaction txn = datastore.beginTransaction();
try {
Query query = new Query(DEVICE_TYPE);
Iterable<Entity> entities =
datastore.prepare(query).asIterable(DEFAULT_FETCH_OPTIONS);
devices = new ArrayList<String>();
for (Entity entity : entities) {
String device = (String) entity.getProperty(DEVICE_REG_ID_PROPERTY);
devices.add(device);
}
txn.commit();
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
return devices;
}
/**
* Gets the number of total devices.
*/
public static int getTotalDevices() {
Transaction txn = datastore.beginTransaction();
try {
Query query = new Query(DEVICE_TYPE).setKeysOnly();
List<Entity> allKeys =
datastore.prepare(query).asList(DEFAULT_FETCH_OPTIONS);
int total = allKeys.size();
logger.fine("Total number of devices: " + total);
txn.commit();
return total;
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
}
private static Entity findDeviceByRegId(String regId) {
Query query = new Query(DEVICE_TYPE)
.addFilter(DEVICE_REG_ID_PROPERTY, FilterOperator.EQUAL, regId);
PreparedQuery preparedQuery = datastore.prepare(query);
List<Entity> entities = preparedQuery.asList(DEFAULT_FETCH_OPTIONS);
Entity entity = null;
if (!entities.isEmpty()) {
entity = entities.get(0);
}
int size = entities.size();
if (size > 0) {
logger.severe(
"Found " + size + " entities for regId " + regId + ": " + entities);
}
return entity;
}
/**
* Creates a persistent record with the devices to be notified using a
* multicast message.
*
* @param devices registration ids of the devices.
* @return encoded key for the persistent record.
*/
public static String createMulticast(List<String> devices) {
logger.info("Storing multicast for " + devices.size() + " devices");
String encodedKey;
Transaction txn = datastore.beginTransaction();
try {
Entity entity = new Entity(MULTICAST_TYPE);
entity.setProperty(MULTICAST_REG_IDS_PROPERTY, devices);
datastore.put(entity);
Key key = entity.getKey();
encodedKey = KeyFactory.keyToString(key);
logger.fine("multicast key: " + encodedKey);
txn.commit();
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
return encodedKey;
}
/**
* Gets a persistent record with the devices to be notified using a
* multicast message.
*
* @param encodedKey encoded key for the persistent record.
*/
public static List<String> getMulticast(String encodedKey) {
Key key = KeyFactory.stringToKey(encodedKey);
Entity entity;
Transaction txn = datastore.beginTransaction();
try {
entity = datastore.get(key);
@SuppressWarnings("unchecked")
List<String> devices =
(List<String>) entity.getProperty(MULTICAST_REG_IDS_PROPERTY);
txn.commit();
return devices;
} catch (EntityNotFoundException e) {
logger.severe("No entity for key " + key);
return Collections.emptyList();
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
}
/**
* Updates a persistent record with the devices to be notified using a
* multicast message.
*
* @param encodedKey encoded key for the persistent record.
* @param devices new list of registration ids of the devices.
*/
public static void updateMulticast(String encodedKey, List<String> devices) {
Key key = KeyFactory.stringToKey(encodedKey);
Entity entity;
Transaction txn = datastore.beginTransaction();
try {
try {
entity = datastore.get(key);
} catch (EntityNotFoundException e) {
logger.severe("No entity for key " + key);
return;
}
entity.setProperty(MULTICAST_REG_IDS_PROPERTY, devices);
datastore.put(entity);
txn.commit();
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
}
/**
* Deletes a persistent record with the devices to be notified using a
* multicast message.
*
* @param encodedKey encoded key for the persistent record.
*/
public static void deleteMulticast(String encodedKey) {
Transaction txn = datastore.beginTransaction();
try {
Key key = KeyFactory.stringToKey(encodedKey);
datastore.delete(key);
txn.commit();
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
}
}
| Java |
/*
* Copyright 2012 Google 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.google.android.gcm.demo.server;
import java.io.IOException;
import java.util.Enumeration;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Skeleton class for all servlets in this package.
*/
@SuppressWarnings("serial")
abstract class BaseServlet extends HttpServlet {
// change to true to allow GET calls
static final boolean DEBUG = true;
protected final Logger logger = Logger.getLogger(getClass().getName());
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
if (DEBUG) {
doPost(req, resp);
} else {
super.doGet(req, resp);
}
}
protected String getParameter(HttpServletRequest req, String parameter)
throws ServletException {
String value = req.getParameter(parameter);
if (isEmptyOrNull(value)) {
if (DEBUG) {
StringBuilder parameters = new StringBuilder();
@SuppressWarnings("unchecked")
Enumeration<String> names = req.getParameterNames();
while (names.hasMoreElements()) {
String name = names.nextElement();
String param = req.getParameter(name);
parameters.append(name).append("=").append(param).append("\n");
}
logger.fine("parameters: " + parameters);
}
throw new ServletException("Parameter " + parameter + " not found");
}
return value.trim();
}
protected String getParameter(HttpServletRequest req, String parameter,
String defaultValue) {
String value = req.getParameter(parameter);
if (isEmptyOrNull(value)) {
value = defaultValue;
}
return value.trim();
}
protected void setSuccess(HttpServletResponse resp) {
setSuccess(resp, 0);
}
protected void setSuccess(HttpServletResponse resp, int size) {
resp.setStatus(HttpServletResponse.SC_OK);
resp.setContentType("text/plain");
resp.setContentLength(size);
}
protected boolean isEmptyOrNull(String value) {
return value == null || value.trim().length() == 0;
}
}
| Java |
/*
* Copyright 2012 Google 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.google.android.gcm.demo.server;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import java.util.logging.Logger;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
/**
* Context initializer that loads the API key from the App Engine datastore.
*/
public class ApiKeyInitializer implements ServletContextListener {
static final String ATTRIBUTE_ACCESS_KEY = "apiKey";
private static final String ENTITY_KIND = "Settings";
private static final String ENTITY_KEY = "MyKey";
private static final String ACCESS_KEY_FIELD = "ApiKey";
private final Logger logger = Logger.getLogger(getClass().getName());
public void contextInitialized(ServletContextEvent event) {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Key key = KeyFactory.createKey(ENTITY_KIND, ENTITY_KEY);
Entity entity;
try {
entity = datastore.get(key);
} catch (EntityNotFoundException e) {
entity = new Entity(key);
// NOTE: it's not possible to change entities in the local server, so
// it will be necessary to hardcode the API key below if you are running
// it locally.
entity.setProperty(ACCESS_KEY_FIELD,
"replace_this_text_by_your_Simple_API_Access_key");
datastore.put(entity);
logger.severe("Created fake key. Please go to App Engine admin "
+ "console, change its value to your API Key (the entity "
+ "type is '" + ENTITY_KIND + "' and its field to be changed is '"
+ ACCESS_KEY_FIELD + "'), then restart the server!");
}
String accessKey = (String) entity.getProperty(ACCESS_KEY_FIELD);
event.getServletContext().setAttribute(ATTRIBUTE_ACCESS_KEY, accessKey);
}
public void contextDestroyed(ServletContextEvent event) {
}
}
| Java |
/*
* Copyright 2012 Google 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.google.android.gcm.demo.server;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet that adds display number of devices and button to send a message.
* <p>
* This servlet is used just by the browser (i.e., not device) and contains the
* main page of the demo app.
*/
@SuppressWarnings("serial")
public class HomeServlet extends BaseServlet {
static final String ATTRIBUTE_STATUS = "status";
/**
* Displays the existing messages and offer the option to send a new one.
*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.print("<html><body>");
out.print("<head>");
out.print(" <title>GCM Demo</title>");
out.print(" <link rel='icon' href='favicon.png'/>");
out.print("</head>");
String status = (String) req.getAttribute(ATTRIBUTE_STATUS);
if (status != null) {
out.print(status);
}
int total = Datastore.getTotalDevices();
if (total == 0) {
out.print("<h2>No devices registered!</h2>");
} else {
out.print("<h2>" + total + " device(s) registered!</h2>");
out.print("<form name='form' method='POST' action='sendAll'>");
out.print("<input type='submit' value='Send Message' />");
out.print("</form>");
}
out.print("</body></html>");
resp.setStatus(HttpServletResponse.SC_OK);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
doGet(req, resp);
}
}
| Java |
/*
* Copyright 2013 Google 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.google.android.gcm.demo.app;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;
/**
* This {@code WakefulBroadcastReceiver} takes care of creating and managing a
* partial wake lock for your app. It passes off the work of processing the GCM
* message to an {@code IntentService}, while ensuring that the device does not
* go back to sleep in the transition. The {@code IntentService} calls
* {@code GcmBroadcastReceiver.completeWakefulIntent()} when it is ready to
* release the wake lock.
*/
public class GcmBroadcastReceiver extends WakefulBroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// Explicitly specify that GcmIntentService will handle the intent.
ComponentName comp = new ComponentName(context.getPackageName(),
GcmIntentService.class.getName());
// Start the service, keeping the device awake while it is launching.
startWakefulService(context, (intent.setComponent(comp)));
setResultCode(Activity.RESULT_OK);
}
}
| Java |
/*
* Copyright (C) 2013 The Android Open Source Project
*
* 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.google.android.gcm.demo.app;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
/**
* This {@code IntentService} does the actual handling of the GCM message.
* {@code GcmBroadcastReceiver} (a {@code WakefulBroadcastReceiver}) holds a
* partial wake lock for this service while the service does its work. When the
* service is finished, it calls {@code completeWakefulIntent()} to release the
* wake lock.
*/
public class GcmIntentService extends IntentService {
public static final int NOTIFICATION_ID = 1;
private NotificationManager mNotificationManager;
NotificationCompat.Builder builder;
public GcmIntentService() {
super("GcmIntentService");
}
public static final String TAG = "GCM Demo";
@Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
// The getMessageType() intent parameter must be the intent you received
// in your BroadcastReceiver.
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) { // has effect of unparcelling Bundle
/*
* Filter messages based on message type. Since it is likely that GCM will be
* extended in the future with new message types, just ignore any message types you're
* not interested in, or that you don't recognize.
*/
if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
sendNotification("Send error: " + extras.toString());
} else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) {
sendNotification("Deleted messages on server: " + extras.toString());
// If it's a regular GCM message, do some work.
} else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
// This loop represents the service doing some work.
for (int i = 0; i < 5; i++) {
Log.i(TAG, "Working... " + (i + 1)
+ "/5 @ " + SystemClock.elapsedRealtime());
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
}
}
Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
// Post notification of received message.
sendNotification("Received: " + extras.toString());
Log.i(TAG, "Received: " + extras.toString());
}
}
// Release the wake lock provided by the WakefulBroadcastReceiver.
GcmBroadcastReceiver.completeWakefulIntent(intent);
}
// Put the message into a notification and post it.
// This is just one simple example of what you might choose to do with
// a GCM message.
private void sendNotification(String msg) {
mNotificationManager = (NotificationManager)
this.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, DemoActivity.class), 0);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_gcm)
.setContentTitle("GCM Notification")
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
}
}
| Java |
/*
* Copyright 2013 Google 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.google.android.gcm.demo.app;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import java.io.IOException;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Main UI for the demo app.
*/
public class DemoActivity extends Activity {
public static final String EXTRA_MESSAGE = "message";
public static final String PROPERTY_REG_ID = "registration_id";
private static final String PROPERTY_APP_VERSION = "appVersion";
private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
/**
* Substitute you own sender ID here. This is the project number you got
* from the API Console, as described in "Getting Started."
*/
String SENDER_ID = "Your-Sender-ID";
/**
* Tag used on log messages.
*/
static final String TAG = "GCM Demo";
TextView mDisplay;
GoogleCloudMessaging gcm;
AtomicInteger msgId = new AtomicInteger();
Context context;
String regid;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mDisplay = (TextView) findViewById(R.id.display);
context = getApplicationContext();
// Check device for Play Services APK. If check succeeds, proceed with GCM registration.
if (checkPlayServices()) {
gcm = GoogleCloudMessaging.getInstance(this);
regid = getRegistrationId(context);
if (regid.isEmpty()) {
registerInBackground();
}
} else {
Log.i(TAG, "No valid Google Play Services APK found.");
}
}
@Override
protected void onResume() {
super.onResume();
// Check device for Play Services APK.
checkPlayServices();
}
/**
* Check the device to make sure it has the Google Play Services APK. If
* it doesn't, display a dialog that allows users to download the APK from
* the Google Play Store or enable it in the device's system settings.
*/
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
Log.i(TAG, "This device is not supported.");
finish();
}
return false;
}
return true;
}
/**
* Stores the registration ID and the app versionCode in the application's
* {@code SharedPreferences}.
*
* @param context application's context.
* @param regId registration ID
*/
private void storeRegistrationId(Context context, String regId) {
final SharedPreferences prefs = getGcmPreferences(context);
int appVersion = getAppVersion(context);
Log.i(TAG, "Saving regId on app version " + appVersion);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(PROPERTY_REG_ID, regId);
editor.putInt(PROPERTY_APP_VERSION, appVersion);
editor.commit();
}
/**
* Gets the current registration ID for application on GCM service, if there is one.
* <p>
* If result is empty, the app needs to register.
*
* @return registration ID, or empty string if there is no existing
* registration ID.
*/
private String getRegistrationId(Context context) {
final SharedPreferences prefs = getGcmPreferences(context);
String registrationId = prefs.getString(PROPERTY_REG_ID, "");
if (registrationId.isEmpty()) {
Log.i(TAG, "Registration not found.");
return "";
}
// Check if app was updated; if so, it must clear the registration ID
// since the existing regID is not guaranteed to work with the new
// app version.
int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
int currentVersion = getAppVersion(context);
if (registeredVersion != currentVersion) {
Log.i(TAG, "App version changed.");
return "";
}
return registrationId;
}
/**
* Registers the application with GCM servers asynchronously.
* <p>
* Stores the registration ID and the app versionCode in the application's
* shared preferences.
*/
private void registerInBackground() {
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
String msg = "";
try {
if (gcm == null) {
gcm = GoogleCloudMessaging.getInstance(context);
}
regid = gcm.register(SENDER_ID);
msg = "Device registered, registration ID=" + regid;
// You should send the registration ID to your server over HTTP, so it
// can use GCM/HTTP or CCS to send messages to your app.
sendRegistrationIdToBackend();
// For this demo: we don't need to send it because the device will send
// upstream messages to a server that echo back the message using the
// 'from' address in the message.
// Persist the regID - no need to register again.
storeRegistrationId(context, regid);
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
// If there is an error, don't just keep trying to register.
// Require the user to click a button again, or perform
// exponential back-off.
}
return msg;
}
@Override
protected void onPostExecute(String msg) {
mDisplay.append(msg + "\n");
}
}.execute(null, null, null);
}
// Send an upstream message.
public void onClick(final View view) {
if (view == findViewById(R.id.send)) {
new AsyncTask<Void, Void, String>() {
@Override
protected String doInBackground(Void... params) {
String msg = "";
try {
Bundle data = new Bundle();
data.putString("my_message", "Hello World");
data.putString("my_action", "com.google.android.gcm.demo.app.ECHO_NOW");
String id = Integer.toString(msgId.incrementAndGet());
gcm.send(SENDER_ID + "@gcm.googleapis.com", id, data);
msg = "Sent message";
} catch (IOException ex) {
msg = "Error :" + ex.getMessage();
}
return msg;
}
@Override
protected void onPostExecute(String msg) {
mDisplay.append(msg + "\n");
}
}.execute(null, null, null);
} else if (view == findViewById(R.id.clear)) {
mDisplay.setText("");
}
}
@Override
protected void onDestroy() {
super.onDestroy();
}
/**
* @return Application's version code from the {@code PackageManager}.
*/
private static int getAppVersion(Context context) {
try {
PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(context.getPackageName(), 0);
return packageInfo.versionCode;
} catch (NameNotFoundException e) {
// should never happen
throw new RuntimeException("Could not get package name: " + e);
}
}
/**
* @return Application's {@code SharedPreferences}.
*/
private SharedPreferences getGcmPreferences(Context context) {
// This sample app persists the registration ID in shared preferences, but
// how you store the regID in your app is up to you.
return getSharedPreferences(DemoActivity.class.getSimpleName(),
Context.MODE_PRIVATE);
}
/**
* Sends the registration ID to your server over HTTP, so it can use GCM/HTTP or CCS to send
* messages to your app. Not needed for this demo since the device sends upstream messages
* to a server that echoes back the message using the 'from' address in the message.
*/
private void sendRegistrationIdToBackend() {
// Your implementation here.
}
}
| Java |
/*
* Copyright 2012 Google 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.google.android.gcm.demo.server;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
/**
* Simple implementation of a data store using standard Java collections.
* <p>
* This class is thread-safe but not persistent (it will lost the data when the
* app is restarted) - it is meant just as an example.
*/
public final class Datastore {
private static final List<String> regIds = new ArrayList<String>();
private static final Logger logger =
Logger.getLogger(Datastore.class.getName());
private Datastore() {
throw new UnsupportedOperationException();
}
/**
* Registers a device.
*/
public static void register(String regId) {
logger.info("Registering " + regId);
synchronized (regIds) {
regIds.add(regId);
}
}
/**
* Unregisters a device.
*/
public static void unregister(String regId) {
logger.info("Unregistering " + regId);
synchronized (regIds) {
regIds.remove(regId);
}
}
/**
* Updates the registration id of a device.
*/
public static void updateRegistration(String oldId, String newId) {
logger.info("Updating " + oldId + " to " + newId);
synchronized (regIds) {
regIds.remove(oldId);
regIds.add(newId);
}
}
/**
* Gets all registered devices.
*/
public static List<String> getDevices() {
synchronized (regIds) {
return new ArrayList<String>(regIds);
}
}
}
| Java |
/*
* Copyright 2012 Google 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.google.android.gcm.demo.server;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet that unregisters a device, whose registration id is identified by
* {@link #PARAMETER_REG_ID}.
* <p>
* The client app should call this servlet everytime it receives a
* {@code com.google.android.c2dm.intent.REGISTRATION} with an
* {@code unregistered} extra.
*/
@SuppressWarnings("serial")
public class UnregisterServlet extends BaseServlet {
private static final String PARAMETER_REG_ID = "regId";
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException {
String regId = getParameter(req, PARAMETER_REG_ID);
Datastore.unregister(regId);
setSuccess(resp);
}
}
| Java |
/*
* Copyright 2012 Google 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.google.android.gcm.demo.server;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet that adds display number of devices and button to send a message.
* <p>
* This servlet is used just by the browser (i.e., not device) and contains the
* main page of the demo app.
*/
@SuppressWarnings("serial")
public class HomeServlet extends BaseServlet {
static final String ATTRIBUTE_STATUS = "status";
/**
* Displays the existing messages and offer the option to send a new one.
*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.print("<html><body>");
out.print("<head>");
out.print(" <title>GCM Demo</title>");
out.print(" <link rel='icon' href='favicon.png'/>");
out.print("</head>");
String status = (String) req.getAttribute(ATTRIBUTE_STATUS);
if (status != null) {
out.print(status);
}
List<String> devices = Datastore.getDevices();
if (devices.isEmpty()) {
out.print("<h2>No devices registered!</h2>");
} else {
out.print("<h2>" + devices.size() + " device(s) registered!</h2>");
out.print("<form name='form' method='POST' action='sendAll'>");
out.print("<input type='submit' value='Send Message' />");
out.print("</form>");
}
out.print("</body></html>");
resp.setStatus(HttpServletResponse.SC_OK);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
doGet(req, resp);
}
}
| Java |
/*
* Copyright 2012 Google 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.google.android.gcm.demo.server;
import java.io.IOException;
import java.util.Enumeration;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Skeleton class for all servlets in this package.
*/
@SuppressWarnings("serial")
abstract class BaseServlet extends HttpServlet {
// change to true to allow GET calls
static final boolean DEBUG = true;
protected final Logger logger = Logger.getLogger(getClass().getName());
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
if (DEBUG) {
doPost(req, resp);
} else {
super.doGet(req, resp);
}
}
protected String getParameter(HttpServletRequest req, String parameter)
throws ServletException {
String value = req.getParameter(parameter);
if (isEmptyOrNull(value)) {
if (DEBUG) {
StringBuilder parameters = new StringBuilder();
@SuppressWarnings("unchecked")
Enumeration<String> names = req.getParameterNames();
while (names.hasMoreElements()) {
String name = names.nextElement();
String param = req.getParameter(name);
parameters.append(name).append("=").append(param).append("\n");
}
logger.fine("parameters: " + parameters);
}
throw new ServletException("Parameter " + parameter + " not found");
}
return value.trim();
}
protected String getParameter(HttpServletRequest req, String parameter,
String defaultValue) {
String value = req.getParameter(parameter);
if (isEmptyOrNull(value)) {
value = defaultValue;
}
return value.trim();
}
protected void setSuccess(HttpServletResponse resp) {
setSuccess(resp, 0);
}
protected void setSuccess(HttpServletResponse resp, int size) {
resp.setStatus(HttpServletResponse.SC_OK);
resp.setContentType("text/plain");
resp.setContentLength(size);
}
protected boolean isEmptyOrNull(String value) {
return value == null || value.trim().length() == 0;
}
}
| Java |
/*
* Copyright 2012 Google 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.google.android.gcm.demo.server;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet that registers a device, whose registration id is identified by
* {@link #PARAMETER_REG_ID}.
*
* <p>
* The client app should call this servlet everytime it receives a
* {@code com.google.android.c2dm.intent.REGISTRATION C2DM} intent without an
* error or {@code unregistered} extra.
*/
@SuppressWarnings("serial")
public class RegisterServlet extends BaseServlet {
private static final String PARAMETER_REG_ID = "regId";
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException {
String regId = getParameter(req, PARAMETER_REG_ID);
Datastore.register(regId);
setSuccess(resp);
}
}
| Java |
/*
* Copyright 2012 Google 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.google.android.gcm.demo.server;
import com.google.android.gcm.server.Constants;
import com.google.android.gcm.server.Message;
import com.google.android.gcm.server.MulticastResult;
import com.google.android.gcm.server.Result;
import com.google.android.gcm.server.Sender;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet that adds a new message to all registered devices.
* <p>
* This servlet is used just by the browser (i.e., not device).
*/
@SuppressWarnings("serial")
public class SendAllMessagesServlet extends BaseServlet {
private static final int MULTICAST_SIZE = 1000;
private Sender sender;
private static final Executor threadPool = Executors.newFixedThreadPool(5);
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
sender = newSender(config);
}
/**
* Creates the {@link Sender} based on the servlet settings.
*/
protected Sender newSender(ServletConfig config) {
String key = (String) config.getServletContext()
.getAttribute(ApiKeyInitializer.ATTRIBUTE_ACCESS_KEY);
return new Sender(key);
}
/**
* Processes the request to add a new message.
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
List<String> devices = Datastore.getDevices();
String status;
if (devices.isEmpty()) {
status = "Message ignored as there is no device registered!";
} else {
// NOTE: check below is for demonstration purposes; a real application
// could always send a multicast, even for just one recipient
if (devices.size() == 1) {
// send a single message using plain post
String registrationId = devices.get(0);
Message message = new Message.Builder().build();
Result result = sender.send(message, registrationId, 5);
status = "Sent message to one device: " + result;
} else {
// send a multicast message using JSON
// must split in chunks of 1000 devices (GCM limit)
int total = devices.size();
List<String> partialDevices = new ArrayList<String>(total);
int counter = 0;
int tasks = 0;
for (String device : devices) {
counter++;
partialDevices.add(device);
int partialSize = partialDevices.size();
if (partialSize == MULTICAST_SIZE || counter == total) {
asyncSend(partialDevices);
partialDevices.clear();
tasks++;
}
}
status = "Asynchronously sending " + tasks + " multicast messages to " +
total + " devices";
}
}
req.setAttribute(HomeServlet.ATTRIBUTE_STATUS, status.toString());
getServletContext().getRequestDispatcher("/home").forward(req, resp);
}
private void asyncSend(List<String> partialDevices) {
// make a copy
final List<String> devices = new ArrayList<String>(partialDevices);
threadPool.execute(new Runnable() {
public void run() {
Message message = new Message.Builder().build();
MulticastResult multicastResult;
try {
multicastResult = sender.send(message, devices, 5);
} catch (IOException e) {
logger.log(Level.SEVERE, "Error posting messages", e);
return;
}
List<Result> results = multicastResult.getResults();
// analyze the results
for (int i = 0; i < devices.size(); i++) {
String regId = devices.get(i);
Result result = results.get(i);
String messageId = result.getMessageId();
if (messageId != null) {
logger.fine("Succesfully sent message to device: " + regId +
"; messageId = " + messageId);
String canonicalRegId = result.getCanonicalRegistrationId();
if (canonicalRegId != null) {
// same device has more than on registration id: update it
logger.info("canonicalRegId " + canonicalRegId);
Datastore.updateRegistration(regId, canonicalRegId);
}
} else {
String error = result.getErrorCodeName();
if (error.equals(Constants.ERROR_NOT_REGISTERED)) {
// application has been removed from device - unregister it
logger.info("Unregistered device: " + regId);
Datastore.unregister(regId);
} else {
logger.severe("Error sending message to " + regId + ": " + error);
}
}
}
}});
}
}
| Java |
/*
* Copyright 2012 Google 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.google.android.gcm.demo.server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
/**
* Context initializer that loads the API key from a
* {@value #PATH} file located in the classpath (typically under
* {@code WEB-INF/classes}).
*/
public class ApiKeyInitializer implements ServletContextListener {
static final String ATTRIBUTE_ACCESS_KEY = "apiKey";
private static final String PATH = "/api.key";
private final Logger logger = Logger.getLogger(getClass().getName());
public void contextInitialized(ServletContextEvent event) {
logger.info("Reading " + PATH + " from resources (probably from " +
"WEB-INF/classes");
String key = getKey();
event.getServletContext().setAttribute(ATTRIBUTE_ACCESS_KEY, key);
}
/**
* Gets the access key.
*/
protected String getKey() {
InputStream stream = Thread.currentThread().getContextClassLoader()
.getResourceAsStream(PATH);
if (stream == null) {
throw new IllegalStateException("Could not find file " + PATH +
" on web resources)");
}
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
try {
String key = reader.readLine();
return key;
} catch (IOException e) {
throw new RuntimeException("Could not read file " + PATH, e);
} finally {
try {
reader.close();
} catch (IOException e) {
logger.log(Level.WARNING, "Exception closing " + PATH, e);
}
}
}
public void contextDestroyed(ServletContextEvent event) {
}
}
| Java |
/*
* Copyright 2012 Google 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.google.android.gcm.demo.server;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.appengine.api.datastore.Transaction;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Logger;
/**
* Simple implementation of a data store using standard Java collections.
* <p>
* This class is neither persistent (it will lost the data when the app is
* restarted) nor thread safe.
*/
public final class Datastore {
static final int MULTICAST_SIZE = 1000;
private static final String DEVICE_TYPE = "Device";
private static final String DEVICE_REG_ID_PROPERTY = "regId";
private static final String MULTICAST_TYPE = "Multicast";
private static final String MULTICAST_REG_IDS_PROPERTY = "regIds";
private static final FetchOptions DEFAULT_FETCH_OPTIONS = FetchOptions.Builder
.withPrefetchSize(MULTICAST_SIZE).chunkSize(MULTICAST_SIZE);
private static final Logger logger =
Logger.getLogger(Datastore.class.getName());
private static final DatastoreService datastore =
DatastoreServiceFactory.getDatastoreService();
private Datastore() {
throw new UnsupportedOperationException();
}
/**
* Registers a device.
*
* @param regId device's registration id.
*/
public static void register(String regId) {
logger.info("Registering " + regId);
Transaction txn = datastore.beginTransaction();
try {
Entity entity = findDeviceByRegId(regId);
if (entity != null) {
logger.fine(regId + " is already registered; ignoring.");
return;
}
entity = new Entity(DEVICE_TYPE);
entity.setProperty(DEVICE_REG_ID_PROPERTY, regId);
datastore.put(entity);
txn.commit();
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
}
/**
* Unregisters a device.
*
* @param regId device's registration id.
*/
public static void unregister(String regId) {
logger.info("Unregistering " + regId);
Transaction txn = datastore.beginTransaction();
try {
Entity entity = findDeviceByRegId(regId);
if (entity == null) {
logger.warning("Device " + regId + " already unregistered");
} else {
Key key = entity.getKey();
datastore.delete(key);
}
txn.commit();
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
}
/**
* Updates the registration id of a device.
*/
public static void updateRegistration(String oldId, String newId) {
logger.info("Updating " + oldId + " to " + newId);
Transaction txn = datastore.beginTransaction();
try {
Entity entity = findDeviceByRegId(oldId);
if (entity == null) {
logger.warning("No device for registration id " + oldId);
return;
}
entity.setProperty(DEVICE_REG_ID_PROPERTY, newId);
datastore.put(entity);
txn.commit();
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
}
/**
* Gets all registered devices.
*/
public static List<String> getDevices() {
List<String> devices;
Transaction txn = datastore.beginTransaction();
try {
Query query = new Query(DEVICE_TYPE);
Iterable<Entity> entities =
datastore.prepare(query).asIterable(DEFAULT_FETCH_OPTIONS);
devices = new ArrayList<String>();
for (Entity entity : entities) {
String device = (String) entity.getProperty(DEVICE_REG_ID_PROPERTY);
devices.add(device);
}
txn.commit();
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
return devices;
}
/**
* Gets the number of total devices.
*/
public static int getTotalDevices() {
Transaction txn = datastore.beginTransaction();
try {
Query query = new Query(DEVICE_TYPE).setKeysOnly();
List<Entity> allKeys =
datastore.prepare(query).asList(DEFAULT_FETCH_OPTIONS);
int total = allKeys.size();
logger.fine("Total number of devices: " + total);
txn.commit();
return total;
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
}
private static Entity findDeviceByRegId(String regId) {
Query query = new Query(DEVICE_TYPE)
.addFilter(DEVICE_REG_ID_PROPERTY, FilterOperator.EQUAL, regId);
PreparedQuery preparedQuery = datastore.prepare(query);
List<Entity> entities = preparedQuery.asList(DEFAULT_FETCH_OPTIONS);
Entity entity = null;
if (!entities.isEmpty()) {
entity = entities.get(0);
}
int size = entities.size();
if (size > 0) {
logger.severe(
"Found " + size + " entities for regId " + regId + ": " + entities);
}
return entity;
}
/**
* Creates a persistent record with the devices to be notified using a
* multicast message.
*
* @param devices registration ids of the devices.
* @return encoded key for the persistent record.
*/
public static String createMulticast(List<String> devices) {
logger.info("Storing multicast for " + devices.size() + " devices");
String encodedKey;
Transaction txn = datastore.beginTransaction();
try {
Entity entity = new Entity(MULTICAST_TYPE);
entity.setProperty(MULTICAST_REG_IDS_PROPERTY, devices);
datastore.put(entity);
Key key = entity.getKey();
encodedKey = KeyFactory.keyToString(key);
logger.fine("multicast key: " + encodedKey);
txn.commit();
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
return encodedKey;
}
/**
* Gets a persistent record with the devices to be notified using a
* multicast message.
*
* @param encodedKey encoded key for the persistent record.
*/
public static List<String> getMulticast(String encodedKey) {
Key key = KeyFactory.stringToKey(encodedKey);
Entity entity;
Transaction txn = datastore.beginTransaction();
try {
entity = datastore.get(key);
@SuppressWarnings("unchecked")
List<String> devices =
(List<String>) entity.getProperty(MULTICAST_REG_IDS_PROPERTY);
txn.commit();
return devices;
} catch (EntityNotFoundException e) {
logger.severe("No entity for key " + key);
return Collections.emptyList();
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
}
/**
* Updates a persistent record with the devices to be notified using a
* multicast message.
*
* @param encodedKey encoded key for the persistent record.
* @param devices new list of registration ids of the devices.
*/
public static void updateMulticast(String encodedKey, List<String> devices) {
Key key = KeyFactory.stringToKey(encodedKey);
Entity entity;
Transaction txn = datastore.beginTransaction();
try {
try {
entity = datastore.get(key);
} catch (EntityNotFoundException e) {
logger.severe("No entity for key " + key);
return;
}
entity.setProperty(MULTICAST_REG_IDS_PROPERTY, devices);
datastore.put(entity);
txn.commit();
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
}
/**
* Deletes a persistent record with the devices to be notified using a
* multicast message.
*
* @param encodedKey encoded key for the persistent record.
*/
public static void deleteMulticast(String encodedKey) {
Transaction txn = datastore.beginTransaction();
try {
Key key = KeyFactory.stringToKey(encodedKey);
datastore.delete(key);
txn.commit();
} finally {
if (txn.isActive()) {
txn.rollback();
}
}
}
}
| Java |
/*
* Copyright 2012 Google 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.google.android.gcm.demo.server;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet that unregisters a device, whose registration id is identified by
* {@link #PARAMETER_REG_ID}.
* <p>
* The client app should call this servlet everytime it receives a
* {@code com.google.android.c2dm.intent.REGISTRATION} with an
* {@code unregistered} extra.
*/
@SuppressWarnings("serial")
public class UnregisterServlet extends BaseServlet {
private static final String PARAMETER_REG_ID = "regId";
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException {
String regId = getParameter(req, PARAMETER_REG_ID);
Datastore.unregister(regId);
setSuccess(resp);
}
}
| Java |
/*
* Copyright 2012 Google 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.google.android.gcm.demo.server;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet that adds display number of devices and button to send a message.
* <p>
* This servlet is used just by the browser (i.e., not device) and contains the
* main page of the demo app.
*/
@SuppressWarnings("serial")
public class HomeServlet extends BaseServlet {
static final String ATTRIBUTE_STATUS = "status";
/**
* Displays the existing messages and offer the option to send a new one.
*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.print("<html><body>");
out.print("<head>");
out.print(" <title>GCM Demo</title>");
out.print(" <link rel='icon' href='favicon.png'/>");
out.print("</head>");
String status = (String) req.getAttribute(ATTRIBUTE_STATUS);
if (status != null) {
out.print(status);
}
int total = Datastore.getTotalDevices();
if (total == 0) {
out.print("<h2>No devices registered!</h2>");
} else {
out.print("<h2>" + total + " device(s) registered!</h2>");
out.print("<form name='form' method='POST' action='sendAll'>");
out.print("<input type='submit' value='Send Message' />");
out.print("</form>");
}
out.print("</body></html>");
resp.setStatus(HttpServletResponse.SC_OK);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
doGet(req, resp);
}
}
| Java |
/*
* Copyright 2012 Google 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.google.android.gcm.demo.server;
import java.io.IOException;
import java.util.Enumeration;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Skeleton class for all servlets in this package.
*/
@SuppressWarnings("serial")
abstract class BaseServlet extends HttpServlet {
// change to true to allow GET calls
static final boolean DEBUG = true;
protected final Logger logger = Logger.getLogger(getClass().getName());
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
if (DEBUG) {
doPost(req, resp);
} else {
super.doGet(req, resp);
}
}
protected String getParameter(HttpServletRequest req, String parameter)
throws ServletException {
String value = req.getParameter(parameter);
if (isEmptyOrNull(value)) {
if (DEBUG) {
StringBuilder parameters = new StringBuilder();
@SuppressWarnings("unchecked")
Enumeration<String> names = req.getParameterNames();
while (names.hasMoreElements()) {
String name = names.nextElement();
String param = req.getParameter(name);
parameters.append(name).append("=").append(param).append("\n");
}
logger.fine("parameters: " + parameters);
}
throw new ServletException("Parameter " + parameter + " not found");
}
return value.trim();
}
protected String getParameter(HttpServletRequest req, String parameter,
String defaultValue) {
String value = req.getParameter(parameter);
if (isEmptyOrNull(value)) {
value = defaultValue;
}
return value.trim();
}
protected void setSuccess(HttpServletResponse resp) {
setSuccess(resp, 0);
}
protected void setSuccess(HttpServletResponse resp, int size) {
resp.setStatus(HttpServletResponse.SC_OK);
resp.setContentType("text/plain");
resp.setContentLength(size);
}
protected boolean isEmptyOrNull(String value) {
return value == null || value.trim().length() == 0;
}
}
| Java |
/*
* Copyright 2012 Google 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.google.android.gcm.demo.server;
import com.google.android.gcm.server.Constants;
import com.google.android.gcm.server.Message;
import com.google.android.gcm.server.MulticastResult;
import com.google.android.gcm.server.Result;
import com.google.android.gcm.server.Sender;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet that sends a message to a device.
* <p>
* This servlet is invoked by AppEngine's Push Queue mechanism.
*/
@SuppressWarnings("serial")
public class SendMessageServlet extends BaseServlet {
private static final String HEADER_QUEUE_COUNT = "X-AppEngine-TaskRetryCount";
private static final String HEADER_QUEUE_NAME = "X-AppEngine-QueueName";
private static final int MAX_RETRY = 3;
static final String PARAMETER_DEVICE = "device";
static final String PARAMETER_MULTICAST = "multicastKey";
private Sender sender;
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
sender = newSender(config);
}
/**
* Creates the {@link Sender} based on the servlet settings.
*/
protected Sender newSender(ServletConfig config) {
String key = (String) config.getServletContext()
.getAttribute(ApiKeyInitializer.ATTRIBUTE_ACCESS_KEY);
return new Sender(key);
}
/**
* Indicates to App Engine that this task should be retried.
*/
private void retryTask(HttpServletResponse resp) {
resp.setStatus(500);
}
/**
* Indicates to App Engine that this task is done.
*/
private void taskDone(HttpServletResponse resp) {
resp.setStatus(200);
}
/**
* Processes the request to add a new message.
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
if (req.getHeader(HEADER_QUEUE_NAME) == null) {
throw new IOException("Missing header " + HEADER_QUEUE_NAME);
}
String retryCountHeader = req.getHeader(HEADER_QUEUE_COUNT);
logger.fine("retry count: " + retryCountHeader);
if (retryCountHeader != null) {
int retryCount = Integer.parseInt(retryCountHeader);
if (retryCount > MAX_RETRY) {
logger.severe("Too many retries, dropping task");
taskDone(resp);
return;
}
}
String regId = req.getParameter(PARAMETER_DEVICE);
if (regId != null) {
sendSingleMessage(regId, resp);
return;
}
String multicastKey = req.getParameter(PARAMETER_MULTICAST);
if (multicastKey != null) {
sendMulticastMessage(multicastKey, resp);
return;
}
logger.severe("Invalid request!");
taskDone(resp);
return;
}
private Message createMessage() {
Message message = new Message.Builder().build();
return message;
}
private void sendSingleMessage(String regId, HttpServletResponse resp) {
logger.info("Sending message to device " + regId);
Message message = createMessage();
Result result;
try {
result = sender.sendNoRetry(message, regId);
} catch (IOException e) {
logger.log(Level.SEVERE, "Exception posting " + message, e);
taskDone(resp);
return;
}
if (result == null) {
retryTask(resp);
return;
}
if (result.getMessageId() != null) {
logger.info("Succesfully sent message to device " + regId);
String canonicalRegId = result.getCanonicalRegistrationId();
if (canonicalRegId != null) {
// same device has more than on registration id: update it
logger.finest("canonicalRegId " + canonicalRegId);
Datastore.updateRegistration(regId, canonicalRegId);
}
} else {
String error = result.getErrorCodeName();
if (error.equals(Constants.ERROR_NOT_REGISTERED)) {
// application has been removed from device - unregister it
Datastore.unregister(regId);
} else {
logger.severe("Error sending message to device " + regId
+ ": " + error);
}
}
}
private void sendMulticastMessage(String multicastKey,
HttpServletResponse resp) {
// Recover registration ids from datastore
List<String> regIds = Datastore.getMulticast(multicastKey);
Message message = createMessage();
MulticastResult multicastResult;
try {
multicastResult = sender.sendNoRetry(message, regIds);
} catch (IOException e) {
logger.log(Level.SEVERE, "Exception posting " + message, e);
multicastDone(resp, multicastKey);
return;
}
boolean allDone = true;
// check if any registration id must be updated
if (multicastResult.getCanonicalIds() != 0) {
List<Result> results = multicastResult.getResults();
for (int i = 0; i < results.size(); i++) {
String canonicalRegId = results.get(i).getCanonicalRegistrationId();
if (canonicalRegId != null) {
String regId = regIds.get(i);
Datastore.updateRegistration(regId, canonicalRegId);
}
}
}
if (multicastResult.getFailure() != 0) {
// there were failures, check if any could be retried
List<Result> results = multicastResult.getResults();
List<String> retriableRegIds = new ArrayList<String>();
for (int i = 0; i < results.size(); i++) {
String error = results.get(i).getErrorCodeName();
if (error != null) {
String regId = regIds.get(i);
logger.warning("Got error (" + error + ") for regId " + regId);
if (error.equals(Constants.ERROR_NOT_REGISTERED)) {
// application has been removed from device - unregister it
Datastore.unregister(regId);
}
if (error.equals(Constants.ERROR_UNAVAILABLE)) {
retriableRegIds.add(regId);
}
}
}
if (!retriableRegIds.isEmpty()) {
// update task
Datastore.updateMulticast(multicastKey, retriableRegIds);
allDone = false;
retryTask(resp);
}
}
if (allDone) {
multicastDone(resp, multicastKey);
} else {
retryTask(resp);
}
}
private void multicastDone(HttpServletResponse resp, String encodedKey) {
Datastore.deleteMulticast(encodedKey);
taskDone(resp);
}
}
| Java |
/*
* Copyright 2012 Google 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.google.android.gcm.demo.server;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet that registers a device, whose registration id is identified by
* {@link #PARAMETER_REG_ID}.
*
* <p>
* The client app should call this servlet everytime it receives a
* {@code com.google.android.c2dm.intent.REGISTRATION C2DM} intent without an
* error or {@code unregistered} extra.
*/
@SuppressWarnings("serial")
public class RegisterServlet extends BaseServlet {
private static final String PARAMETER_REG_ID = "regId";
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException {
String regId = getParameter(req, PARAMETER_REG_ID);
Datastore.register(regId);
setSuccess(resp);
}
}
| Java |
/*
* Copyright 2012 Google 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.google.android.gcm.demo.server;
import static com.google.appengine.api.taskqueue.TaskOptions.Builder.withUrl;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
import com.google.appengine.api.taskqueue.TaskOptions.Method;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet that adds a new message to all registered devices.
* <p>
* This servlet is used just by the browser (i.e., not device).
*/
@SuppressWarnings("serial")
public class SendAllMessagesServlet extends BaseServlet {
/**
* Processes the request to add a new message.
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException {
List<String> devices = Datastore.getDevices();
String status;
if (devices.isEmpty()) {
status = "Message ignored as there is no device registered!";
} else {
Queue queue = QueueFactory.getQueue("gcm");
// NOTE: check below is for demonstration purposes; a real application
// could always send a multicast, even for just one recipient
if (devices.size() == 1) {
// send a single message using plain post
String device = devices.get(0);
queue.add(withUrl("/send").param(
SendMessageServlet.PARAMETER_DEVICE, device));
status = "Single message queued for registration id " + device;
} else {
// send a multicast message using JSON
// must split in chunks of 1000 devices (GCM limit)
int total = devices.size();
List<String> partialDevices = new ArrayList<String>(total);
int counter = 0;
int tasks = 0;
for (String device : devices) {
counter++;
partialDevices.add(device);
int partialSize = partialDevices.size();
if (partialSize == Datastore.MULTICAST_SIZE || counter == total) {
String multicastKey = Datastore.createMulticast(partialDevices);
logger.fine("Queuing " + partialSize + " devices on multicast " +
multicastKey);
TaskOptions taskOptions = TaskOptions.Builder
.withUrl("/send")
.param(SendMessageServlet.PARAMETER_MULTICAST, multicastKey)
.method(Method.POST);
queue.add(taskOptions);
partialDevices.clear();
tasks++;
}
}
status = "Queued tasks to send " + tasks + " multicast messages to " +
total + " devices";
}
}
req.setAttribute(HomeServlet.ATTRIBUTE_STATUS, status.toString());
getServletContext().getRequestDispatcher("/home").forward(req, resp);
}
}
| Java |
/*
* Copyright 2012 Google 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.google.android.gcm.demo.server;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import java.util.logging.Logger;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
/**
* Context initializer that loads the API key from the App Engine datastore.
*/
public class ApiKeyInitializer implements ServletContextListener {
static final String ATTRIBUTE_ACCESS_KEY = "apiKey";
private static final String ENTITY_KIND = "Settings";
private static final String ENTITY_KEY = "MyKey";
private static final String ACCESS_KEY_FIELD = "ApiKey";
private final Logger logger = Logger.getLogger(getClass().getName());
public void contextInitialized(ServletContextEvent event) {
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Key key = KeyFactory.createKey(ENTITY_KIND, ENTITY_KEY);
Entity entity;
try {
entity = datastore.get(key);
} catch (EntityNotFoundException e) {
entity = new Entity(key);
// NOTE: it's not possible to change entities in the local server, so
// it will be necessary to hardcode the API key below if you are running
// it locally.
entity.setProperty(ACCESS_KEY_FIELD,
"replace_this_text_by_your_Simple_API_Access_key");
datastore.put(entity);
logger.severe("Created fake key. Please go to App Engine admin "
+ "console, change its value to your API Key (the entity "
+ "type is '" + ENTITY_KIND + "' and its field to be changed is '"
+ ACCESS_KEY_FIELD + "'), then restart the server!");
}
String accessKey = (String) entity.getProperty(ACCESS_KEY_FIELD);
event.getServletContext().setAttribute(ATTRIBUTE_ACCESS_KEY, accessKey);
}
public void contextDestroyed(ServletContextEvent event) {
}
}
| Java |
/*
* Copyright 2012 Google 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.google.android.gcm.demo.app;
import android.content.Context;
import android.content.Intent;
/**
* Helper class providing methods and constants common to other classes in the
* app.
*/
public final class CommonUtilities {
/**
* Base URL of the Demo Server (such as http://my_host:8080/gcm-demo)
*/
static final String SERVER_URL = null;
/**
* Google API project id registered to use GCM.
*/
static final String SENDER_ID = null;
/**
* Tag used on log messages.
*/
static final String TAG = "GCMDemo";
/**
* Intent used to display a message in the screen.
*/
static final String DISPLAY_MESSAGE_ACTION =
"com.google.android.gcm.demo.app.DISPLAY_MESSAGE";
/**
* Intent's extra that contains the message to be displayed.
*/
static final String EXTRA_MESSAGE = "message";
/**
* Notifies UI to display a message.
* <p>
* This method is defined in the common helper because it's used both by
* the UI and the background service.
*
* @param context application's context.
* @param message message to be displayed.
*/
static void displayMessage(Context context, String message) {
Intent intent = new Intent(DISPLAY_MESSAGE_ACTION);
intent.putExtra(EXTRA_MESSAGE, message);
context.sendBroadcast(intent);
}
}
| Java |
/*
* Copyright 2012 Google 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.google.android.gcm.demo.app;
import static com.google.android.gcm.demo.app.CommonUtilities.SENDER_ID;
import static com.google.android.gcm.demo.app.CommonUtilities.displayMessage;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import com.google.android.gcm.GCMBaseIntentService;
/**
* IntentService responsible for handling GCM messages.
*/
public class GCMIntentService extends GCMBaseIntentService {
@SuppressWarnings("hiding")
private static final String TAG = "GCMIntentService";
public GCMIntentService() {
super(SENDER_ID);
}
@Override
protected void onRegistered(Context context, String registrationId) {
Log.i(TAG, "Device registered: regId = " + registrationId);
displayMessage(context, getString(R.string.gcm_registered,
registrationId));
ServerUtilities.register(context, registrationId);
}
@Override
protected void onUnregistered(Context context, String registrationId) {
Log.i(TAG, "Device unregistered");
displayMessage(context, getString(R.string.gcm_unregistered));
ServerUtilities.unregister(context, registrationId);
}
@Override
protected void onMessage(Context context, Intent intent) {
Log.i(TAG, "Received message. Extras: " + intent.getExtras());
String message = getString(R.string.gcm_message);
displayMessage(context, message);
// notifies user
generateNotification(context, message);
}
@Override
protected void onDeletedMessages(Context context, int total) {
Log.i(TAG, "Received deleted messages notification");
String message = getString(R.string.gcm_deleted, total);
displayMessage(context, message);
// notifies user
generateNotification(context, message);
}
@Override
public void onError(Context context, String errorId) {
Log.i(TAG, "Received error: " + errorId);
displayMessage(context, getString(R.string.gcm_error, errorId));
}
@Override
protected boolean onRecoverableError(Context context, String errorId) {
// log message
Log.i(TAG, "Received recoverable error: " + errorId);
displayMessage(context, getString(R.string.gcm_recoverable_error,
errorId));
return super.onRecoverableError(context, errorId);
}
/**
* Issues a notification to inform the user that server has sent a message.
*/
private static void generateNotification(Context context, String message) {
int icon = R.drawable.ic_stat_gcm;
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(icon, message, when);
String title = context.getString(R.string.app_name);
Intent notificationIntent = new Intent(context, DemoActivity.class);
// set intent so it does not start a new activity
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent =
PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, title, message, intent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, notification);
}
}
| Java |
/*
* Copyright 2012 Google 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.google.android.gcm.demo.app;
import static com.google.android.gcm.demo.app.CommonUtilities.SERVER_URL;
import static com.google.android.gcm.demo.app.CommonUtilities.TAG;
import static com.google.android.gcm.demo.app.CommonUtilities.displayMessage;
import com.google.android.gcm.GCMRegistrar;
import android.content.Context;
import android.util.Log;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
/**
* Helper class used to communicate with the demo server.
*/
public final class ServerUtilities {
private static final int MAX_ATTEMPTS = 5;
private static final int BACKOFF_MILLI_SECONDS = 2000;
private static final Random random = new Random();
/**
* Register this account/device pair within the server.
*
*/
static void register(final Context context, final String regId) {
Log.i(TAG, "registering device (regId = " + regId + ")");
String serverUrl = SERVER_URL + "/register";
Map<String, String> params = new HashMap<String, String>();
params.put("regId", regId);
long backoff = BACKOFF_MILLI_SECONDS + random.nextInt(1000);
// Once GCM returns a registration id, we need to register it in the
// demo server. As the server might be down, we will retry it a couple
// times.
for (int i = 1; i <= MAX_ATTEMPTS; i++) {
Log.d(TAG, "Attempt #" + i + " to register");
try {
displayMessage(context, context.getString(
R.string.server_registering, i, MAX_ATTEMPTS));
post(serverUrl, params);
GCMRegistrar.setRegisteredOnServer(context, true);
String message = context.getString(R.string.server_registered);
CommonUtilities.displayMessage(context, message);
return;
} catch (IOException e) {
// Here we are simplifying and retrying on any error; in a real
// application, it should retry only on unrecoverable errors
// (like HTTP error code 503).
Log.e(TAG, "Failed to register on attempt " + i + ":" + e);
if (i == MAX_ATTEMPTS) {
break;
}
try {
Log.d(TAG, "Sleeping for " + backoff + " ms before retry");
Thread.sleep(backoff);
} catch (InterruptedException e1) {
// Activity finished before we complete - exit.
Log.d(TAG, "Thread interrupted: abort remaining retries!");
Thread.currentThread().interrupt();
return;
}
// increase backoff exponentially
backoff *= 2;
}
}
String message = context.getString(R.string.server_register_error,
MAX_ATTEMPTS);
CommonUtilities.displayMessage(context, message);
}
/**
* Unregister this account/device pair within the server.
*/
static void unregister(final Context context, final String regId) {
Log.i(TAG, "unregistering device (regId = " + regId + ")");
String serverUrl = SERVER_URL + "/unregister";
Map<String, String> params = new HashMap<String, String>();
params.put("regId", regId);
try {
post(serverUrl, params);
GCMRegistrar.setRegisteredOnServer(context, false);
String message = context.getString(R.string.server_unregistered);
CommonUtilities.displayMessage(context, message);
} catch (IOException e) {
// At this point the device is unregistered from GCM, but still
// registered in the server.
// We could try to unregister again, but it is not necessary:
// if the server tries to send a message to the device, it will get
// a "NotRegistered" error message and should unregister the device.
String message = context.getString(R.string.server_unregister_error,
e.getMessage());
CommonUtilities.displayMessage(context, message);
}
}
/**
* Issue a POST request to the server.
*
* @param endpoint POST address.
* @param params request parameters.
*
* @throws IOException propagated from POST.
*/
private static void post(String endpoint, Map<String, String> params)
throws IOException {
URL url;
try {
url = new URL(endpoint);
} catch (MalformedURLException e) {
throw new IllegalArgumentException("invalid url: " + endpoint);
}
StringBuilder bodyBuilder = new StringBuilder();
Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
// constructs the POST body using the parameters
while (iterator.hasNext()) {
Entry<String, String> param = iterator.next();
bodyBuilder.append(param.getKey()).append('=')
.append(param.getValue());
if (iterator.hasNext()) {
bodyBuilder.append('&');
}
}
String body = bodyBuilder.toString();
Log.v(TAG, "Posting '" + body + "' to " + url);
byte[] bytes = body.getBytes();
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setFixedLengthStreamingMode(bytes.length);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
// post the request
OutputStream out = conn.getOutputStream();
out.write(bytes);
out.close();
// handle the response
int status = conn.getResponseCode();
if (status != 200) {
throw new IOException("Post failed with error code " + status);
}
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.