code
stringlengths
3
1.18M
language
stringclasses
1 value
/* NFCard 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. NFCard 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 Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.nfc.tech; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import android.nfc.tech.NfcF; import com.sinpo.xnfc.nfc.Util; public class FeliCa { public static final byte[] EMPTY = {}; protected byte[] data; protected FeliCa() { } protected FeliCa(byte[] bytes) { data = (bytes == null) ? FeliCa.EMPTY : bytes; } public int size() { return data.length; } public byte[] getBytes() { return data; } @Override public String toString() { return Util.toHexString(data, 0, data.length); } public final static class IDm extends FeliCa { public static final byte[] EMPTY = { 0, 0, 0, 0, 0, 0, 0, 0, }; public IDm(byte[] bytes) { super((bytes == null || bytes.length < 8) ? IDm.EMPTY : bytes); } public final String getManufactureCode() { return Util.toHexString(data, 0, 2); } public final String getCardIdentification() { return Util.toHexString(data, 2, 6); } public boolean isEmpty() { final byte[] d = data; for (final byte v : d) { if (v != 0) return false; } return true; } } public final static class PMm extends FeliCa { public static final byte[] EMPTY = { 0, 0, 0, 0, 0, 0, 0, 0, }; public PMm(byte[] bytes) { super((bytes == null || bytes.length < 8) ? PMm.EMPTY : bytes); } public final String getIcCode() { return Util.toHexString(data, 0, 2); } public final String getMaximumResponseTime() { return Util.toHexString(data, 2, 6); } } public final static class SystemCode extends FeliCa { public static final byte[] EMPTY = { 0, 0, }; public SystemCode(byte[] sc) { super((sc == null || sc.length < 2) ? SystemCode.EMPTY : sc); } public int toInt() { return toInt(data); } public static int toInt(byte[] data) { return 0x0000FFFF & ((data[0] << 8) | (0x000000FF & data[1])); } } public final static class ServiceCode extends FeliCa { public static final byte[] EMPTY = { 0, 0, }; public static final int T_UNKNOWN = 0; public static final int T_RANDOM = 1; public static final int T_CYCLIC = 2; public static final int T_PURSE = 3; public ServiceCode(byte[] sc) { super((sc == null || sc.length < 2) ? ServiceCode.EMPTY : sc); } public ServiceCode(int code) { this(new byte[] { (byte) (code & 0xFF), (byte) (code >> 8) }); } public int toInt() { return 0x0000FFFF & ((data[1] << 8) | (0x000000FF & data[0])); } public boolean isEncrypt() { return (data[0] & 0x1) == 0; } public boolean isWritable() { final int f = data[0] & 0x3F; return (f & 0x2) == 0 || f == 0x13 || f == 0x12; } public int getAccessAttr() { return data[0] & 0x3F; } public int getDataType() { final int f = data[0] & 0x3F; if ((f & 0x10) == 0) return T_PURSE; return ((f & 0x04) == 0) ? T_RANDOM : T_CYCLIC; } } public final static class Block extends FeliCa { public Block() { data = new byte[16]; } public Block(byte[] bytes) { super((bytes == null || bytes.length < 16) ? new byte[16] : bytes); } } public final static class BlockListElement extends FeliCa { private static final byte LENGTH_2_BYTE = (byte) 0x80; private static final byte LENGTH_3_BYTE = (byte) 0x00; // private static final byte ACCESSMODE_DECREMENT = (byte) 0x00; // private static final byte ACCESSMODE_CACHEBACK = (byte) 0x01; private final byte lengthAndaccessMode; private final byte serviceCodeListOrder; public BlockListElement(byte mode, byte order, byte... blockNumber) { if (blockNumber.length > 1) { lengthAndaccessMode = (byte) (mode | LENGTH_2_BYTE & 0xFF); } else { lengthAndaccessMode = (byte) (mode | LENGTH_3_BYTE & 0xFF); } serviceCodeListOrder = (byte) (order & 0x0F); data = (blockNumber == null) ? FeliCa.EMPTY : blockNumber; } @Override public byte[] getBytes() { if ((this.lengthAndaccessMode & LENGTH_2_BYTE) == 1) { ByteBuffer buff = ByteBuffer.allocate(2); buff.put( (byte) ((this.lengthAndaccessMode | this.serviceCodeListOrder) & 0xFF)) .put(data[0]); return buff.array(); } else { ByteBuffer buff = ByteBuffer.allocate(3); buff.put( (byte) ((this.lengthAndaccessMode | this.serviceCodeListOrder) & 0xFF)) .put(data[1]).put(data[0]); return buff.array(); } } } public final static class MemoryConfigurationBlock extends FeliCa { public MemoryConfigurationBlock(byte[] bytes) { super((bytes == null || bytes.length < 4) ? new byte[4] : bytes); } public boolean isNdefSupport() { return (data == null) ? false : (data[3] & (byte) 0xff) == 1; } public void setNdefSupport(boolean ndefSupport) { data[3] = (byte) (ndefSupport ? 1 : 0); } public boolean isWritable(int... addrs) { if (data == null) return false; boolean result = true; for (int a : addrs) { byte b = (byte) ((a & 0xff) + 1); if (a < 8) { result &= (data[0] & b) == b; continue; } else if (a < 16) { result &= (data[1] & b) == b; continue; } else result &= (data[2] & b) == b; } return result; } } public final static class Service extends FeliCa { private final ServiceCode[] serviceCodes; private final BlockListElement[] blockListElements; public Service(ServiceCode[] codes, BlockListElement... blocks) { serviceCodes = (codes == null) ? new ServiceCode[0] : codes; blockListElements = (blocks == null) ? new BlockListElement[0] : blocks; } @Override public byte[] getBytes() { int length = 0; for (ServiceCode s : this.serviceCodes) { length += s.getBytes().length; } for (BlockListElement b : blockListElements) { length += b.getBytes().length; } ByteBuffer buff = ByteBuffer.allocate(length); for (ServiceCode s : this.serviceCodes) { buff.put(s.getBytes()); } for (BlockListElement b : blockListElements) { buff.put(b.getBytes()); } return buff.array(); } @Override public String toString() { StringBuilder sb = new StringBuilder(); for (ServiceCode s : serviceCodes) { sb.append(s.toString()); } for (BlockListElement b : blockListElements) { sb.append(b.toString()); } return sb.toString(); } } public final static class Command extends FeliCa { private final int length; private final byte code; private final IDm idm; public Command(final byte[] bytes) { this(bytes[0], Arrays.copyOfRange(bytes, 1, bytes.length)); } public Command(byte code, final byte... bytes) { this.code = code; if (bytes.length >= 8) { idm = new IDm(Arrays.copyOfRange(bytes, 0, 8)); data = Arrays.copyOfRange(bytes, 8, bytes.length); } else { idm = null; data = bytes; } length = bytes.length + 2; } public Command(byte code, IDm idm, final byte... bytes) { this.code = code; this.idm = idm; this.data = bytes; this.length = idm.getBytes().length + data.length + 2; } public Command(byte code, byte[] idm, final byte... bytes) { this.code = code; this.idm = new IDm(idm); this.data = bytes; this.length = idm.length + data.length + 2; } @Override public byte[] getBytes() { ByteBuffer buff = ByteBuffer.allocate(length); byte length = (byte) this.length; if (idm != null) { buff.put(length).put(code).put(idm.getBytes()).put(data); } else { buff.put(length).put(code).put(data); } return buff.array(); } } public static class Response extends FeliCa { protected final int length; protected final byte code; protected final IDm idm; public Response(byte[] bytes) { if (bytes != null && bytes.length >= 10) { length = bytes[0] & 0xff; code = bytes[1]; idm = new IDm(Arrays.copyOfRange(bytes, 2, 10)); data = bytes; } else { length = 0; code = 0; idm = new IDm(null); data = FeliCa.EMPTY; } } public IDm getIDm() { return idm; } } public final static class PollingResponse extends Response { private final PMm pmm; public PollingResponse(byte[] bytes) { super(bytes); if (size() >= 18) { pmm = new PMm(Arrays.copyOfRange(data, 10, 18)); } else { pmm = new PMm(null); } } public PMm getPMm() { return pmm; } } public final static class ReadResponse extends Response { public static final byte[] EMPTY = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (byte) 0xFF, (byte) 0xFF }; private final byte[] blockData; public ReadResponse(byte[] rsp) { super((rsp == null || rsp.length < 12) ? ReadResponse.EMPTY : rsp); if (getStatusFlag1() == STA1_NORMAL && getBlockCount() > 0) { blockData = Arrays.copyOfRange(data, 13, data.length); } else { blockData = FeliCa.EMPTY; } } public int getStatusFlag1() { return data[10] & 0x000000FF; } public int getStatusFlag2() { return data[11] & 0x000000FF; } public int getStatusFlag12() { return (getStatusFlag1() << 8) | getStatusFlag2(); } public int getBlockCount() { return (data.length > 12) ? (0xFF & data[12]) : 0; } public byte[] getBlockData() { return blockData; } public boolean isOkey() { return getStatusFlag1() == STA1_NORMAL; } } public final static class WriteResponse extends Response { public WriteResponse(byte[] rsp) { super((rsp == null || rsp.length < 12) ? ReadResponse.EMPTY : rsp); } public int getStatusFlag1() { return data[0] & 0x000000FF; } public int getStatusFlag2() { return data[1] & 0x000000FF; } public int getStatusFlag12() { return (getStatusFlag1() << 8) | getStatusFlag2(); } public boolean isOkey() { return getStatusFlag1() == STA1_NORMAL; } } public final static class Tag { private final NfcF nfcTag; private boolean isFeliCaLite; private byte[] sys; private IDm idm; private PMm pmm; public Tag(NfcF tag) { nfcTag = tag; sys = tag.getSystemCode(); idm = new IDm(tag.getTag().getId()); pmm = new PMm(tag.getManufacturer()); } public int getSystemCode() { return SystemCode.toInt(sys); } public byte[] getSystemCodeByte() { return sys; } public IDm getIDm() { return idm; } public PMm getPMm() { return pmm; } public boolean checkFeliCaLite() throws IOException { isFeliCaLite = !polling(SYS_FELICA_LITE).getIDm().isEmpty(); return isFeliCaLite; } public boolean isFeliCaLite() { return isFeliCaLite; } public PollingResponse polling(int systemCode) throws IOException { Command cmd = new Command(CMD_POLLING, new byte[] { (byte) (systemCode >> 8), (byte) (systemCode & 0xff), (byte) 0x01, (byte) 0x00 }); final byte s[] = cmd.getBytes(); final byte r[] = transceive(s); final PollingResponse rsp = new PollingResponse(r); idm = rsp.getIDm(); pmm = rsp.getPMm(); return rsp; } public PollingResponse polling() throws IOException { return polling(SYS_FELICA_LITE); } public final SystemCode[] getSystemCodeList() throws IOException { final Command cmd = new Command(CMD_REQUEST_SYSTEMCODE, idm); final byte s[] = cmd.getBytes(); final byte r[] = transceive(s); final int num; if (r == null || r.length < 12 || r[1] != (byte) 0x0d) { num = 0; } else { num = r[10] & 0x000000FF; } final SystemCode ret[] = new SystemCode[num]; for (int i = 0; i < num; ++i) { ret[i] = new SystemCode(Arrays.copyOfRange(r, 11 + i * 2, 13 + i * 2)); } return ret; } public ServiceCode[] getServiceCodeList() throws IOException { ArrayList<ServiceCode> ret = new ArrayList<ServiceCode>(); int index = 1; while (true) { byte[] bytes = searchServiceCode(index); if (bytes.length != 2 && bytes.length != 4) break; if (bytes.length == 2) { if (bytes[0] == (byte) 0xff && bytes[1] == (byte) 0xff) break; ret.add(new ServiceCode(bytes)); } ++index; } return ret.toArray(new ServiceCode[ret.size()]); } public byte[] searchServiceCode(int index) throws IOException { Command cmd = new Command(CMD_SEARCH_SERVICECODE, idm, new byte[] { (byte) (index & 0xff), (byte) (index >> 8) }); final byte s[] = cmd.getBytes(); final byte r[] = transceive(s); final byte ret[]; if (r == null || r.length < 12 || r[1] != (byte) 0x0b) ret = FeliCa.EMPTY; else ret = Arrays.copyOfRange(r, 10, r.length); return ret; } public ReadResponse readWithoutEncryption(byte addr, byte... service) throws IOException { Command cmd = new Command(CMD_READ_WO_ENCRYPTION, idm, new byte[] { (byte) 0x01, (byte) service[0], (byte) service[1], (byte) 0x01, (byte) 0x80, addr }); final byte s[] = cmd.getBytes(); final byte r[] = transceive(s); final ReadResponse ret = new ReadResponse(r); return ret; } public ReadResponse readWithoutEncryption(ServiceCode code, byte addr) throws IOException { return readWithoutEncryption(addr, code.getBytes()); } public ReadResponse readWithoutEncryption(byte addr) throws IOException { final byte code0 = (byte) (SRV_FELICA_LITE_READWRITE >> 8); final byte code1 = (byte) (SRV_FELICA_LITE_READWRITE & 0xff); return readWithoutEncryption(addr, code0, code1); } public WriteResponse writeWithoutEncryption(ServiceCode code, byte addr, byte[] buff) throws IOException { byte[] bytes = code.getBytes(); ByteBuffer b = ByteBuffer.allocate(22); b.put(new byte[] { (byte) 0x01, (byte) bytes[0], (byte) bytes[1], (byte) 0x01, (byte) 0x80, (byte) addr }); b.put(buff, 0, buff.length > 16 ? 16 : buff.length); Command cmd = new Command(CMD_WRITE_WO_ENCRYPTION, idm, b.array()); return new WriteResponse(transceive(cmd)); } public WriteResponse writeWithoutEncryption(byte addr, byte[] buff) throws IOException { ByteBuffer b = ByteBuffer.allocate(22); b.put(new byte[] { (byte) 0x01, (byte) (SRV_FELICA_LITE_READWRITE >> 8), (byte) (SRV_FELICA_LITE_READWRITE & 0xff), (byte) 0x01, (byte) 0x80, addr }); b.put(buff, 0, buff.length > 16 ? 16 : buff.length); Command cmd = new Command(CMD_WRITE_WO_ENCRYPTION, idm, b.array()); return new WriteResponse(transceive(cmd)); } public MemoryConfigurationBlock getMemoryConfigBlock() throws IOException { ReadResponse r = readWithoutEncryption((byte) 0x88); return new MemoryConfigurationBlock(r.getBlockData()); } @Override public String toString() { StringBuilder sb = new StringBuilder(); if (idm != null) { sb.append(idm.toString()); if (pmm != null) sb.append(pmm.toString()); } return sb.toString(); } public void connect() throws IOException { nfcTag.connect(); } public void close() throws IOException { nfcTag.close(); } public byte[] transceive(Command cmd) throws IOException { return transceive(cmd.getBytes()); } public byte[] transceive(byte... cmd) throws IOException { return nfcTag.transceive(cmd); } } // polling public static final byte CMD_POLLING = 0x00; public static final byte RSP_POLLING = 0x01; // request service public static final byte CMD_REQUEST_SERVICE = 0x02; public static final byte RSP_REQUEST_SERVICE = 0x03; // request RESPONSE public static final byte CMD_REQUEST_RESPONSE = 0x04; public static final byte RSP_REQUEST_RESPONSE = 0x05; // read without encryption public static final byte CMD_READ_WO_ENCRYPTION = 0x06; public static final byte RSP_READ_WO_ENCRYPTION = 0x07; // write without encryption public static final byte CMD_WRITE_WO_ENCRYPTION = 0x08; public static final byte RSP_WRITE_WO_ENCRYPTION = 0x09; // search service code public static final byte CMD_SEARCH_SERVICECODE = 0x0a; public static final byte RSP_SEARCH_SERVICECODE = 0x0b; // request system code public static final byte CMD_REQUEST_SYSTEMCODE = 0x0c; public static final byte RSP_REQUEST_SYSTEMCODE = 0x0d; // authentication 1 public static final byte CMD_AUTHENTICATION1 = 0x10; public static final byte RSP_AUTHENTICATION1 = 0x11; // authentication 2 public static final byte CMD_AUTHENTICATION2 = 0x12; public static final byte RSP_AUTHENTICATION2 = 0x13; // read public static final byte CMD_READ = 0x14; public static final byte RSP_READ = 0x15; // write public static final byte CMD_WRITE = 0x16; public static final byte RSP_WRITE = 0x17; public static final int SYS_ANY = 0xffff; public static final int SYS_FELICA_LITE = 0x88b4; public static final int SYS_COMMON = 0xfe00; public static final int SRV_FELICA_LITE_READONLY = 0x0b00; public static final int SRV_FELICA_LITE_READWRITE = 0x0900; public static final int STA1_NORMAL = 0x00; public static final int STA1_ERROR = 0xff; public static final int STA2_NORMAL = 0x00; public static final int STA2_ERROR_LENGTH = 0x01; public static final int STA2_ERROR_FLOWN = 0x02; public static final int STA2_ERROR_MEMORY = 0x70; public static final int STA2_ERROR_WRITELIMIT = 0x71; }
Java
/* NFCard 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. NFCard 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 Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.nfc.tech; import java.io.IOException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import com.sinpo.xnfc.nfc.Util; import android.nfc.tech.IsoDep; public class Iso7816 { public static final byte[] EMPTY = { 0 }; protected byte[] data; protected Iso7816() { data = Iso7816.EMPTY; } protected Iso7816(byte[] bytes) { data = (bytes == null) ? Iso7816.EMPTY : bytes; } public boolean match(byte[] bytes) { return match(bytes, 0); } public boolean match(byte[] bytes, int start) { final byte[] data = this.data; if (data.length <= bytes.length - start) { for (final byte v : data) { if (v != bytes[start++]) return false; } } else { return false; } return true; } public boolean match(byte tag) { return (data.length == 1 && data[0] == tag); } public boolean match(short tag) { final byte[] data = this.data; if (data.length == 2) { final byte d0 = (byte) (0x000000FF & (tag >> 8)); final byte d1 = (byte) (0x000000FF & tag); return (data[0] == d0 && data[1] == d1); } return (tag >= 0 && tag <= 255) ? match((byte) tag) : false; } public int size() { return data.length; } public byte[] getBytes() { return data; } public byte[] getBytes(int start, int count) { return Arrays.copyOfRange(data, start, start + count); } public int toInt() { return Util.toInt(getBytes()); } public int toIntR() { return Util.toIntR(getBytes()); } @Override public String toString() { return Util.toHexString(data, 0, data.length); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || !(obj instanceof Iso7816)) return false; return match(((Iso7816) obj).getBytes(), 0); } public final static class ID extends Iso7816 { public ID(byte... bytes) { super(bytes); } } public static class Response extends Iso7816 { public static final byte[] EMPTY = {}; public static final byte[] ERROR = { 0x6F, 0x00 }; // SW_UNKNOWN public Response(byte[] bytes) { super((bytes == null || bytes.length < 2) ? Response.ERROR : bytes); } public byte getSw1() { return data[data.length - 2]; } public byte getSw2() { return data[data.length - 1]; } public String getSw12String() { int sw1 = getSw1() & 0x000000FF; int sw2 = getSw2() & 0x000000FF; return String.format("0x%02X%02X", sw1, sw2); } public short getSw12() { final byte[] d = this.data; int n = d.length; return (short) ((d[n - 2] << 8) | (0xFF & d[n - 1])); } public boolean isOkey() { return equalsSw12(SW_NO_ERROR); } public boolean equalsSw12(short val) { return getSw12() == val; } public int size() { return data.length - 2; } public byte[] getBytes() { return isOkey() ? Arrays.copyOfRange(data, 0, size()) : Response.EMPTY; } } public final static class MifareDResponse extends Response { public MifareDResponse(byte[] bytes) { super(bytes); } } public final static class BerT extends Iso7816 { // tag template public static final byte TMPL_FCP = 0x62; // File Control Parameters public static final byte TMPL_FMD = 0x64; // File Management Data public static final byte TMPL_FCI = 0x6F; // FCP and FMD // proprietary information public final static BerT CLASS_PRI = new BerT((byte) 0xA5); // short EF identifier public final static BerT CLASS_SFI = new BerT((byte) 0x88); // dedicated file name public final static BerT CLASS_DFN = new BerT((byte) 0x84); // application data object public final static BerT CLASS_ADO = new BerT((byte) 0x61); // application id public final static BerT CLASS_AID = new BerT((byte) 0x4F); // proprietary information public static int test(byte[] bytes, int start) { int len = 1; if ((bytes[start] & 0x1F) == 0x1F) { while ((bytes[start + len] & 0x80) == 0x80) ++len; ++len; } return len; } public static BerT read(byte[] bytes, int start) { return new BerT(Arrays.copyOfRange(bytes, start, start + test(bytes, start))); } public BerT(byte tag) { this(new byte[] { tag }); } public BerT(short tag) { this(new byte[] { (byte) (0x000000FF & (tag >> 8)), (byte) (0x000000FF & tag) }); } public BerT(byte[] bytes) { super(bytes); } public boolean hasChild() { return ((data[0] & 0x20) == 0x20); } public short toShort() { if (size() <= 2) { return (short) Util.toInt(data); } return 0; } } public final static class BerL extends Iso7816 { private final int val; public static int test(byte[] bytes, int start) { int len = 1; if ((bytes[start] & 0x80) == 0x80) { len += bytes[start] & 0x07; } return len; } public static int calc(byte[] bytes, int start) { if ((bytes[start] & 0x80) == 0x80) { int v = 0; int e = start + bytes[start] & 0x07; while (++start <= e) { v <<= 8; v |= bytes[start] & 0xFF; } return v; } return bytes[start]; } public static BerL read(byte[] bytes, int start) { return new BerL(Arrays.copyOfRange(bytes, start, start + test(bytes, start))); } public BerL(byte[] bytes) { super(bytes); val = calc(bytes, 0); } public BerL(int len) { super(null); val = len; } public int toInt() { return val; } } public final static class BerV extends Iso7816 { public static BerV read(byte[] bytes, int start, int len) { return new BerV(Arrays.copyOfRange(bytes, start, start + len)); } public BerV(byte[] bytes) { super(bytes); } } public final static class BerTLV extends Iso7816 { public static int test(byte[] bytes, int start) { final int lt = BerT.test(bytes, start); final int ll = BerL.test(bytes, start + lt); final int lv = BerL.calc(bytes, start + lt); return lt + ll + lv; } public static byte[] getValue(BerTLV tlv) { if (tlv == null || tlv.length() == 0) return null; return tlv.v.getBytes(); } public static BerTLV read(Iso7816 obj) { return read(obj.getBytes(), 0); } public static BerTLV read(byte[] bytes, int start) { int s = start; final BerT t = BerT.read(bytes, s); s += t.size(); final BerL l = BerL.read(bytes, s); s += l.size(); final BerV v = BerV.read(bytes, s, l.toInt()); s += v.size(); final BerTLV tlv = new BerTLV(t, l, v); tlv.data = Arrays.copyOfRange(bytes, start, s); return tlv; } public static void extractChildren(ArrayList<BerTLV> out, Iso7816 obj) { extractChildren(out, obj.getBytes()); } public static void extractChildren(ArrayList<BerTLV> out, byte[] data) { int start = 0; int end = data.length - 3; while (start <= end) { final BerTLV tlv = read(data, start); out.add(tlv); start += tlv.size(); } } public static void extractPrimitives(BerHouse out, Iso7816 obj) { extractPrimitives(out.tlvs, obj.getBytes()); } public static void extractPrimitives(ArrayList<BerTLV> out, Iso7816 obj) { extractPrimitives(out, obj.getBytes()); } public static void extractPrimitives(BerHouse out, byte[] data) { extractPrimitives(out.tlvs, data); } public static void extractPrimitives(ArrayList<BerTLV> out, byte[] data) { int start = 0; int end = data.length - 3; while (start <= end) { final BerTLV tlv = read(data, start); if (tlv.t.hasChild()) extractPrimitives(out, tlv.v.getBytes()); else out.add(tlv); start += tlv.size(); } } public static ArrayList<BerTLV> extractOptionList(byte[] data) { final ArrayList<BerTLV> ret = new ArrayList<BerTLV>(); int start = 0; int end = data.length; while (start < end) { final BerT t = BerT.read(data, start); start += t.size(); if (start < end) { BerL l = BerL.read(data, start); start += l.size(); if (start <= end) ret.add(new BerTLV(t, l, null)); } } return ret; } public final BerT t; public final BerL l; public final BerV v; public BerTLV(BerT t, BerL l, BerV v) { this.t = t; this.l = l; this.v = v; } public int length() { return l.toInt(); } } public final static class BerHouse { final ArrayList<BerTLV> tlvs = new ArrayList<BerTLV>(); public int count() { return tlvs.size(); } public void add(short t, Response v) { tlvs.add(new BerTLV(new BerT(t), new BerL(v.size()), new BerV(v .getBytes()))); } public void add(short t, byte[] v) { tlvs.add(new BerTLV(new BerT(t), new BerL(v.length), new BerV(v))); } public void add(BerT t, byte[] v) { tlvs.add(new BerTLV(t, new BerL(v.length), new BerV(v))); } public void add(BerTLV tlv) { tlvs.add(tlv); } public BerTLV get(int index) { return tlvs.get(index); } public BerTLV findFirst(byte tag) { for (BerTLV tlv : tlvs) if (tlv.t.match(tag)) return tlv; return null; } public BerTLV findFirst(byte... tag) { for (BerTLV tlv : tlvs) if (tlv.t.match(tag)) return tlv; return null; } public BerTLV findFirst(short tag) { for (BerTLV tlv : tlvs) if (tlv.t.match(tag)) return tlv; return null; } public BerTLV findFirst(BerT tag) { for (BerTLV tlv : tlvs) if (tlv.t.match(tag.getBytes())) return tlv; return null; } public ArrayList<BerTLV> findAll(byte tag) { final ArrayList<BerTLV> ret = new ArrayList<BerTLV>(); for (BerTLV tlv : tlvs) if (tlv.t.match(tag)) ret.add(tlv); return ret; } public ArrayList<BerTLV> findAll(byte... tag) { final ArrayList<BerTLV> ret = new ArrayList<BerTLV>(); for (BerTLV tlv : tlvs) if (tlv.t.match(tag)) ret.add(tlv); return ret; } public ArrayList<BerTLV> findAll(short tag) { final ArrayList<BerTLV> ret = new ArrayList<BerTLV>(); for (BerTLV tlv : tlvs) if (tlv.t.match(tag)) ret.add(tlv); return ret; } public ArrayList<BerTLV> findAll(BerT tag) { final ArrayList<BerTLV> ret = new ArrayList<BerTLV>(); for (BerTLV tlv : tlvs) if (tlv.t.match(tag.getBytes())) ret.add(tlv); return ret; } public String toString() { final StringBuilder ret = new StringBuilder(); for (BerTLV t : tlvs) { ret.append(t.t.toString()).append(' '); ret.append(t.l.toInt()).append(' '); ret.append(t.v.toString()).append('\n'); } return ret.toString(); } } public final static class StdTag { private final IsoDep nfcTag; private ID id; public StdTag(IsoDep tag) { nfcTag = tag; id = new ID(tag.getTag().getId()); } public ID getID() { return id; } public Response getBalance(boolean isEP) throws IOException { final byte[] cmd = { (byte) 0x80, // CLA Class (byte) 0x5C, // INS Instruction (byte) 0x00, // P1 Parameter 1 (byte) (isEP ? 2 : 1), // P2 Parameter 2 (byte) 0x04, // Le }; return new Response(transceive(cmd)); } public Response readRecord(int sfi, int index) throws IOException { final byte[] cmd = { (byte) 0x00, // CLA Class (byte) 0xB2, // INS Instruction (byte) index, // P1 Parameter 1 (byte) ((sfi << 3) | 0x04), // P2 Parameter 2 (byte) 0x00, // Le }; return new Response(transceive(cmd)); } public Response readRecord(int sfi) throws IOException { final byte[] cmd = { (byte) 0x00, // CLA Class (byte) 0xB2, // INS Instruction (byte) 0x01, // P1 Parameter 1 (byte) ((sfi << 3) | 0x05), // P2 Parameter 2 (byte) 0x00, // Le }; return new Response(transceive(cmd)); } public Response readBinary(int sfi) throws IOException { final byte[] cmd = { (byte) 0x00, // CLA Class (byte) 0xB0, // INS Instruction (byte) (0x00000080 | (sfi & 0x1F)), // P1 Parameter 1 (byte) 0x00, // P2 Parameter 2 (byte) 0x00, // Le }; return new Response(transceive(cmd)); } public Response readData(int sfi) throws IOException { final byte[] cmd = { (byte) 0x80, // CLA Class (byte) 0xCA, // INS Instruction (byte) 0x00, // P1 Parameter 1 (byte) (sfi & 0x1F), // P2 Parameter 2 (byte) 0x00, // Le }; return new Response(transceive(cmd)); } public Response getData(short tag) throws IOException { final byte[] cmd = { (byte) 0x80, // CLA Class (byte) 0xCA, // INS Instruction (byte) ((tag >> 8) & 0xFF), (byte) (tag & 0xFF), (byte) 0x00, // Le }; return new Response(transceive(cmd)); } public Response readData(short tag) throws IOException { final byte[] cmd = { (byte) 0x80, // CLA Class (byte) 0xCA, // INS Instruction (byte) ((tag >> 8) & 0xFF), // P1 Parameter 1 (byte) (tag & 0x1F), // P2 Parameter 2 (byte) 0x00, // Lc (byte) 0x00, // Le }; return new Response(transceive(cmd)); } public Response selectByID(byte... id) throws IOException { ByteBuffer buff = ByteBuffer.allocate(id.length + 6); buff.put((byte) 0x00) // CLA Class .put((byte) 0xA4) // INS Instruction .put((byte) 0x00) // P1 Parameter 1 .put((byte) 0x00) // P2 Parameter 2 .put((byte) id.length) // Lc .put(id).put((byte) 0x00); // Le return new Response(transceive(buff.array())); } public Response selectByName(byte... name) throws IOException { ByteBuffer buff = ByteBuffer.allocate(name.length + 6); buff.put((byte) 0x00) // CLA Class .put((byte) 0xA4) // INS Instruction .put((byte) 0x04) // P1 Parameter 1 .put((byte) 0x00) // P2 Parameter 2 .put((byte) name.length) // Lc .put(name).put((byte) 0x00); // Le return new Response(transceive(buff.array())); } public Response getProcessingOptions(byte... pdol) throws IOException { ByteBuffer buff = ByteBuffer.allocate(pdol.length + 6); buff.put((byte) 0x80) // CLA Class .put((byte) 0xA8) // INS Instruction .put((byte) 0x00) // P1 Parameter 1 .put((byte) 0x00) // P2 Parameter 2 .put((byte) pdol.length) // Lc .put(pdol).put((byte) 0x00); // Le return new Response(transceive(buff.array())); } public void connect() throws IOException { nfcTag.connect(); } public void close() throws IOException { nfcTag.close(); } public byte[] transceive(final byte[] cmd) throws IOException { try { byte[] rsp = null; byte c[] = cmd; do { byte[] r = nfcTag.transceive(c); if (r == null) break; int N = r.length - 2; if (N < 0) { rsp = r; break; } if (r[N] == CH_STA_LE) { c[c.length - 1] = r[N + 1]; continue; } if (rsp == null) { rsp = r; } else { int n = rsp.length; N += n; rsp = Arrays.copyOf(rsp, N); n -= 2; for (byte i : r) rsp[n++] = i; } if (r[N] != CH_STA_MORE) break; byte s = r[N + 1]; if (s != 0) { c = CMD_GETRESPONSE.clone(); } else { rsp[rsp.length - 1] = CH_STA_OK; break; } } while (true); return rsp; } catch (Exception e) { return Response.ERROR; } } private static final byte CH_STA_OK = (byte) 0x90; private static final byte CH_STA_MORE = (byte) 0x61; private static final byte CH_STA_LE = (byte) 0x6C; private static final byte CMD_GETRESPONSE[] = { 0, (byte) 0xC0, 0, 0, 0, }; } public static final short SW_NO_ERROR = (short) 0x9000; public static final short SW_DESFIRE_NO_ERROR = (short) 0x9100; public static final short SW_BYTES_REMAINING_00 = 0x6100; public static final short SW_WRONG_LENGTH = 0x6700; public static final short SW_SECURITY_STATUS_NOT_SATISFIED = 0x6982; public static final short SW_FILE_INVALID = 0x6983; public static final short SW_DATA_INVALID = 0x6984; public static final short SW_CONDITIONS_NOT_SATISFIED = 0x6985; public static final short SW_COMMAND_NOT_ALLOWED = 0x6986; public static final short SW_APPLET_SELECT_FAILED = 0x6999; public static final short SW_WRONG_DATA = 0x6A80; public static final short SW_FUNC_NOT_SUPPORTED = 0x6A81; public static final short SW_FILE_NOT_FOUND = 0x6A82; public static final short SW_RECORD_NOT_FOUND = 0x6A83; public static final short SW_INCORRECT_P1P2 = 0x6A86; public static final short SW_WRONG_P1P2 = 0x6B00; public static final short SW_CORRECT_LENGTH_00 = 0x6C00; public static final short SW_INS_NOT_SUPPORTED = 0x6D00; public static final short SW_CLA_NOT_SUPPORTED = 0x6E00; public static final short SW_UNKNOWN = 0x6F00; public static final short SW_FILE_FULL = 0x6A84; }
Java
/* NFCard 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. NFCard 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 Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.nfc; import static android.nfc.NfcAdapter.EXTRA_TAG; import static android.os.Build.VERSION_CODES.GINGERBREAD_MR1; import static android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH; import android.annotation.SuppressLint; import android.app.Activity; import android.app.PendingIntent; import android.content.Intent; import android.content.IntentFilter; import android.nfc.NdefMessage; import android.nfc.NdefRecord; import android.nfc.NfcAdapter; import android.nfc.Tag; import android.nfc.tech.IsoDep; import android.nfc.tech.NfcF; import com.sinpo.xnfc.nfc.reader.ReaderListener; import com.sinpo.xnfc.nfc.reader.ReaderManager; public final class NfcManager { private final Activity activity; private NfcAdapter nfcAdapter; private PendingIntent pendingIntent; private static String[][] TECHLISTS; private static IntentFilter[] TAGFILTERS; private int status; static { try { TECHLISTS = new String[][] { { IsoDep.class.getName() }, { NfcF.class.getName() }, }; TAGFILTERS = new IntentFilter[] { new IntentFilter( NfcAdapter.ACTION_TECH_DISCOVERED, "*/*") }; } catch (Exception e) { } } public NfcManager(Activity activity) { this.activity = activity; nfcAdapter = NfcAdapter.getDefaultAdapter(activity); pendingIntent = PendingIntent.getActivity(activity, 0, new Intent( activity, activity.getClass()) .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0); setupBeam(true); status = getStatus(); } public void onPause() { setupOldFashionBeam(false); if (nfcAdapter != null) nfcAdapter.disableForegroundDispatch(activity); } public void onResume() { setupOldFashionBeam(true); if (nfcAdapter != null) nfcAdapter.enableForegroundDispatch(activity, pendingIntent, TAGFILTERS, TECHLISTS); } public boolean updateStatus() { int sta = getStatus(); if (sta != status) { status = sta; return true; } return false; } public boolean readCard(Intent intent, ReaderListener listener) { final Tag tag = (Tag) intent.getParcelableExtra(EXTRA_TAG); if (tag != null) { ReaderManager.readCard(tag, listener); return true; } return false; } private int getStatus() { return (nfcAdapter == null) ? -1 : nfcAdapter.isEnabled() ? 1 : 0; } @SuppressLint("NewApi") private void setupBeam(boolean enable) { final int api = android.os.Build.VERSION.SDK_INT; if (nfcAdapter != null && api >= ICE_CREAM_SANDWICH) { if (enable) nfcAdapter.setNdefPushMessage(createNdefMessage(), activity); } } @SuppressWarnings("deprecation") private void setupOldFashionBeam(boolean enable) { final int api = android.os.Build.VERSION.SDK_INT; if (nfcAdapter != null && api >= GINGERBREAD_MR1 && api < ICE_CREAM_SANDWICH) { if (enable) nfcAdapter.enableForegroundNdefPush(activity, createNdefMessage()); else nfcAdapter.disableForegroundNdefPush(activity); } } NdefMessage createNdefMessage() { String uri = "3play.google.com/store/apps/details?id=com.sinpo.xnfc"; byte[] data = uri.getBytes(); // about this '3'.. see NdefRecord.createUri which need api level 14 data[0] = 3; NdefRecord record = new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_URI, null, data); return new NdefMessage(new NdefRecord[] { record }); } }
Java
/* NFCard 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. NFCard 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 Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.nfc; public final class Util { private final static char[] HEX = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; private Util() { } public static byte[] toBytes(int a) { return new byte[] { (byte) (0x000000ff & (a >>> 24)), (byte) (0x000000ff & (a >>> 16)), (byte) (0x000000ff & (a >>> 8)), (byte) (0x000000ff & (a)) }; } public static boolean testBit(byte data, int bit) { final byte mask = (byte) ((1 << bit) & 0x000000FF); return (data & mask) == mask; } public static int toInt(byte[] b, int s, int n) { int ret = 0; final int e = s + n; for (int i = s; i < e; ++i) { ret <<= 8; ret |= b[i] & 0xFF; } return ret; } public static int toIntR(byte[] b, int s, int n) { int ret = 0; for (int i = s; (i >= 0 && n > 0); --i, --n) { ret <<= 8; ret |= b[i] & 0xFF; } return ret; } public static int toInt(byte... b) { int ret = 0; for (final byte a : b) { ret <<= 8; ret |= a & 0xFF; } return ret; } public static int toIntR(byte... b) { return toIntR(b, b.length - 1, b.length); } public static String toHexString(byte... d) { return (d == null || d.length == 0) ? "" : toHexString(d, 0, d.length); } public static String toHexString(byte[] d, int s, int n) { final char[] ret = new char[n * 2]; final int e = s + n; int x = 0; for (int i = s; i < e; ++i) { final byte v = d[i]; ret[x++] = HEX[0x0F & (v >> 4)]; ret[x++] = HEX[0x0F & v]; } return new String(ret); } public static String toHexStringR(byte[] d, int s, int n) { final char[] ret = new char[n * 2]; int x = 0; for (int i = s + n - 1; i >= s; --i) { final byte v = d[i]; ret[x++] = HEX[0x0F & (v >> 4)]; ret[x++] = HEX[0x0F & v]; } return new String(ret); } public static String ensureString(String str) { return str == null ? "" : str; } public static String toStringR(int n) { final StringBuilder ret = new StringBuilder(16).append('0'); long N = 0xFFFFFFFFL & n; while (N != 0) { ret.append((int) (N % 100)); N /= 100; } return ret.toString(); } public static int parseInt(String txt, int radix, int def) { int ret; try { ret = Integer.valueOf(txt, radix); } catch (Exception e) { ret = def; } return ret; } public static int BCDtoInt(byte[] b, int s, int n) { int ret = 0; final int e = s + n; for (int i = s; i < e; ++i) { int h = (b[i] >> 4) & 0x0F; int l = b[i] & 0x0F; if (h > 9 || l > 9) return -1; ret = ret * 100 + h * 10 + l; } return ret; } public static int BCDtoInt(byte... b) { return BCDtoInt(b, 0, b.length); } }
Java
/* NFCard 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. NFCard 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 Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.nfc.bean; import java.util.ArrayList; import com.sinpo.xnfc.SPEC; public class Card extends Application { public static final Card EMPTY = new Card(); private final ArrayList<Application> applications; public Card() { applications = new ArrayList<Application>(2); } public Exception getReadingException() { return (Exception) getProperty(SPEC.PROP.EXCEPTION); } public boolean hasReadingException() { return hasProperty(SPEC.PROP.EXCEPTION); } public final boolean isUnknownCard() { return applicationCount() == 0; } public final int applicationCount() { return applications.size(); } public final Application getApplication(int index) { return applications.get(index); } public final void addApplication(Application app) { if (app != null) applications.add(app); } public String toHtml() { return HtmlFormatter.formatCardInfo(this); } }
Java
/* NFCard 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. NFCard 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 Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.nfc.bean; import com.sinpo.xnfc.SPEC; import android.util.SparseArray; public class Application { private final SparseArray<Object> properties = new SparseArray<Object>(); public final void setProperty(SPEC.PROP prop, Object value) { properties.put(prop.ordinal(), value); } public final Object getProperty(SPEC.PROP prop) { return properties.get(prop.ordinal()); } public final boolean hasProperty(SPEC.PROP prop) { return getProperty(prop) != null; } public final String getStringProperty(SPEC.PROP prop) { final Object v = getProperty(prop); return (v != null) ? v.toString() : ""; } public final float getFloatProperty(SPEC.PROP prop) { final Object v = getProperty(prop); if (v == null) return Float.NaN; if (v instanceof Float) return ((Float) v).floatValue(); return Float.parseFloat(v.toString()); } }
Java
/* NFCard 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. NFCard 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 Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.nfc.bean; import com.sinpo.xnfc.SPEC; public final class HtmlFormatter { static String formatCardInfo(Card card) { final StringBuilder ret = new StringBuilder(); startTag(ret, SPEC.TAG_BLK); final int N = card.applicationCount(); for (int i = 0; i < N; ++i) { if (i > 0) { newline(ret); newline(ret); } formatApplicationInfo(ret, card.getApplication(i)); } endTag(ret, SPEC.TAG_BLK); return ret.toString(); } private static void startTag(StringBuilder out, String tag) { out.append('<').append(tag).append('>'); } private static void endTag(StringBuilder out, String tag) { out.append('<').append('/').append(tag).append('>'); } private static void newline(StringBuilder out) { out.append("<br />"); } private static void spliter(StringBuilder out) { out.append("\n<").append(SPEC.TAG_SP).append(" />\n"); } private static boolean formatProperty(StringBuilder out, String tag, Object value) { if (value == null) return false; startTag(out, tag); out.append(value.toString()); endTag(out, tag); return true; } private static boolean formatProperty(StringBuilder out, String tag, Object prop, String value) { if (value == null || value.isEmpty()) return false; startTag(out, tag); out.append(prop.toString()); endTag(out, tag); startTag(out, SPEC.TAG_TEXT); out.append(value); endTag(out, SPEC.TAG_TEXT); return true; } private static boolean formatApplicationInfo(StringBuilder out, Application app) { if (!formatProperty(out, SPEC.TAG_H1, app.getProperty(SPEC.PROP.ID))) return false; newline(out); spliter(out); newline(out); { SPEC.PROP prop = SPEC.PROP.SERIAL; if (formatProperty(out, SPEC.TAG_LAB, prop, app.getStringProperty(prop))) newline(out); } { SPEC.PROP prop = SPEC.PROP.PARAM; if (formatProperty(out, SPEC.TAG_LAB, prop, app.getStringProperty(prop))) newline(out); } { SPEC.PROP prop = SPEC.PROP.VERSION; if (formatProperty(out, SPEC.TAG_LAB, prop, app.getStringProperty(prop))) newline(out); } { SPEC.PROP prop = SPEC.PROP.DATE; if (formatProperty(out, SPEC.TAG_LAB, prop, app.getStringProperty(prop))) newline(out); } { SPEC.PROP prop = SPEC.PROP.COUNT; if (formatProperty(out, SPEC.TAG_LAB, prop, app.getStringProperty(prop))) newline(out); } { SPEC.PROP prop = SPEC.PROP.TLIMIT; Float balance = (Float) app.getProperty(prop); if (balance != null && !balance.isNaN()) { String cur = app.getProperty(SPEC.PROP.CURRENCY).toString(); String val = String.format("%.2f %s", balance, cur); if (formatProperty(out, SPEC.TAG_LAB, prop, val)) newline(out); } } { SPEC.PROP prop = SPEC.PROP.DLIMIT; Float balance = (Float) app.getProperty(prop); if (balance != null && !balance.isNaN()) { String cur = app.getProperty(SPEC.PROP.CURRENCY).toString(); String val = String.format("%.2f %s", balance, cur); if (formatProperty(out, SPEC.TAG_LAB, prop, val)) newline(out); } } { SPEC.PROP prop = SPEC.PROP.ECASH; Float balance = (Float) app.getProperty(prop); if (balance != null) { formatProperty(out, SPEC.TAG_LAB, prop); if (balance.isNaN()) { out.append(SPEC.PROP.ACCESS); } else { formatProperty(out, SPEC.TAG_H2, String.format("%.2f ", balance)); formatProperty(out, SPEC.TAG_LAB, app.getProperty(SPEC.PROP.CURRENCY).toString()); } newline(out); } } { SPEC.PROP prop = SPEC.PROP.BALANCE; Float balance = (Float) app.getProperty(prop); if (balance != null) { formatProperty(out, SPEC.TAG_LAB, prop); if (balance.isNaN()) { out.append(SPEC.PROP.ACCESS); } else { formatProperty(out, SPEC.TAG_H2, String.format("%.2f ", balance)); formatProperty(out, SPEC.TAG_LAB, app.getProperty(SPEC.PROP.CURRENCY).toString()); } newline(out); } } { SPEC.PROP prop = SPEC.PROP.TRANSLOG; String[] logs = (String[]) app.getProperty(prop); if (logs != null && logs.length > 0) { spliter(out); newline(out); startTag(out, SPEC.TAG_PARAG); formatProperty(out, SPEC.TAG_LAB, prop); newline(out); endTag(out, SPEC.TAG_PARAG); for (String log : logs) { formatProperty(out, SPEC.TAG_H3, log); newline(out); } newline(out); } } return true; } }
Java
/* NFCard 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. NFCard 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 Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.nfc.reader; import android.nfc.Tag; import android.nfc.tech.IsoDep; import android.nfc.tech.NfcF; import android.os.AsyncTask; import com.sinpo.xnfc.SPEC; import com.sinpo.xnfc.nfc.Util; import com.sinpo.xnfc.nfc.bean.Card; import com.sinpo.xnfc.nfc.reader.pboc.StandardPboc; public final class ReaderManager extends AsyncTask<Tag, SPEC.EVENT, Card> { public static void readCard(Tag tag, ReaderListener listener) { new ReaderManager(listener).execute(tag); } private ReaderListener realListener; private ReaderManager(ReaderListener listener) { realListener = listener; } @Override protected Card doInBackground(Tag... detectedTag) { return readCard(detectedTag[0]); } @Override protected void onProgressUpdate(SPEC.EVENT... events) { if (realListener != null) realListener.onReadEvent(events[0]); } @Override protected void onPostExecute(Card card) { if (realListener != null) realListener.onReadEvent(SPEC.EVENT.FINISHED, card); } private Card readCard(Tag tag) { final Card card = new Card(); try { publishProgress(SPEC.EVENT.READING); card.setProperty(SPEC.PROP.ID, Util.toHexString(tag.getId())); final IsoDep isodep = IsoDep.get(tag); if (isodep != null) StandardPboc.readCard(isodep, card); final NfcF nfcf = NfcF.get(tag); if (nfcf != null) FelicaReader.readCard(nfcf, card); publishProgress(SPEC.EVENT.IDLE); } catch (Exception e) { card.setProperty(SPEC.PROP.EXCEPTION, e); publishProgress(SPEC.EVENT.ERROR); } return card; } }
Java
/* NFCard 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. NFCard 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 Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.nfc.reader; import com.sinpo.xnfc.SPEC; public interface ReaderListener { void onReadEvent(SPEC.EVENT event, Object... obj); }
Java
/* NFCard 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. NFCard 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 Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.nfc.reader.pboc; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import com.sinpo.xnfc.SPEC; import com.sinpo.xnfc.nfc.Util; import com.sinpo.xnfc.nfc.bean.Application; import com.sinpo.xnfc.nfc.bean.Card; import com.sinpo.xnfc.nfc.tech.Iso7816; import android.nfc.tech.IsoDep; @SuppressWarnings("unchecked") public abstract class StandardPboc { private static Class<?>[][] readers = { { BeijingMunicipal.class, WuhanTong.class, ShenzhenTong.class, CityUnion.class, }, { Quickpass.class, } }; public static void readCard(IsoDep tech, Card card) throws InstantiationException, IllegalAccessException, IOException { final Iso7816.StdTag tag = new Iso7816.StdTag(tech); tag.connect(); for (final Class<?> g[] : readers) { HINT hint = HINT.RESETANDGONEXT; for (final Class<?> r : g) { final StandardPboc reader = (StandardPboc) r.newInstance(); switch (hint) { case RESETANDGONEXT: if (!reader.resetTag(tag)) continue; case GONEXT: hint = reader.readCard(tag, card); break; default: break; } if (hint == HINT.STOP) break; } } tag.close(); } protected boolean resetTag(Iso7816.StdTag tag) throws IOException { return tag.selectByID(DFI_MF).isOkey() || tag.selectByName(DFN_PSE).isOkey(); } protected enum HINT { STOP, GONEXT, RESETANDGONEXT, } protected final static byte[] DFI_MF = { (byte) 0x3F, (byte) 0x00 }; protected final static byte[] DFI_EP = { (byte) 0x10, (byte) 0x01 }; protected final static byte[] DFN_PSE = { (byte) '1', (byte) 'P', (byte) 'A', (byte) 'Y', (byte) '.', (byte) 'S', (byte) 'Y', (byte) 'S', (byte) '.', (byte) 'D', (byte) 'D', (byte) 'F', (byte) '0', (byte) '1', }; protected final static byte[] DFN_PXX = { (byte) 'P' }; protected final static int SFI_EXTRA = 21; protected static int MAX_LOG = 10; protected static int SFI_LOG = 24; protected final static byte TRANS_CSU = 6; protected final static byte TRANS_CSU_CPX = 9; protected abstract SPEC.APP getApplicationId(); protected byte[] getMainApplicationId() { return DFI_EP; } protected SPEC.CUR getCurrency() { return SPEC.CUR.CNY; } protected boolean selectMainApplication(Iso7816.StdTag tag) throws IOException { final byte[] aid = getMainApplicationId(); return ((aid.length == 2) ? tag.selectByID(aid) : tag.selectByName(aid)) .isOkey(); } protected HINT readCard(Iso7816.StdTag tag, Card card) throws IOException { /*--------------------------------------------------------------*/ // select Main Application /*--------------------------------------------------------------*/ if (!selectMainApplication(tag)) return HINT.GONEXT; Iso7816.Response INFO, BALANCE; /*--------------------------------------------------------------*/ // read card info file, binary (21) /*--------------------------------------------------------------*/ INFO = tag.readBinary(SFI_EXTRA); /*--------------------------------------------------------------*/ // read balance /*--------------------------------------------------------------*/ BALANCE = tag.getBalance(true); /*--------------------------------------------------------------*/ // read log file, record (24) /*--------------------------------------------------------------*/ ArrayList<byte[]> LOG = readLog24(tag, SFI_LOG); /*--------------------------------------------------------------*/ // build result /*--------------------------------------------------------------*/ final Application app = createApplication(); parseBalance(app, BALANCE); parseInfo21(app, INFO, 4, true); parseLog24(app, LOG); configApplication(app); card.addApplication(app); return HINT.STOP; } protected void parseBalance(Application app, Iso7816.Response... data) { int amount = 0; for (Iso7816.Response rsp : data) { if (rsp.isOkey() && rsp.size() >= 4) { int n = Util.toInt(rsp.getBytes(), 0, 4); if (n > 1000000 || n < -1000000) n -= 0x80000000; amount += n; } } app.setProperty(SPEC.PROP.BALANCE, (amount / 100.0f)); } protected void parseInfo21(Application app, Iso7816.Response data, int dec, boolean bigEndian) { if (!data.isOkey() || data.size() < 30) { return; } final byte[] d = data.getBytes(); if (dec < 1 || dec > 10) { app.setProperty(SPEC.PROP.SERIAL, Util.toHexString(d, 10, 10)); } else { final int sn = bigEndian ? Util.toIntR(d, 19, dec) : Util.toInt(d, 20 - dec, dec); app.setProperty(SPEC.PROP.SERIAL, String.format("%d", 0xFFFFFFFFL & sn)); } if (d[9] != 0) app.setProperty(SPEC.PROP.VERSION, String.valueOf(d[9])); app.setProperty(SPEC.PROP.DATE, String.format( "%02X%02X.%02X.%02X - %02X%02X.%02X.%02X", d[20], d[21], d[22], d[23], d[24], d[25], d[26], d[27])); } protected boolean addLog24(final Iso7816.Response r, ArrayList<byte[]> l) { if (!r.isOkey()) return false; final byte[] raw = r.getBytes(); final int N = raw.length - 23; if (N < 0) return false; for (int s = 0, e = 0; s <= N; s = e) { l.add(Arrays.copyOfRange(raw, s, (e = s + 23))); } return true; } protected ArrayList<byte[]> readLog24(Iso7816.StdTag tag, int sfi) throws IOException { final ArrayList<byte[]> ret = new ArrayList<byte[]>(MAX_LOG); final Iso7816.Response rsp = tag.readRecord(sfi); if (rsp.isOkey()) { addLog24(rsp, ret); } else { for (int i = 1; i <= MAX_LOG; ++i) { if (!addLog24(tag.readRecord(sfi, i), ret)) break; } } return ret; } protected void parseLog24(Application app, ArrayList<byte[]>... logs) { final ArrayList<String> ret = new ArrayList<String>(MAX_LOG); for (final ArrayList<byte[]> log : logs) { if (log == null) continue; for (final byte[] v : log) { final int money = Util.toInt(v, 5, 4); if (money > 0) { final char s = (v[9] == TRANS_CSU || v[9] == TRANS_CSU_CPX) ? '-' : '+'; final int over = Util.toInt(v, 2, 3); final String slog; if (over > 0) { slog = String .format("%02X%02X.%02X.%02X %02X:%02X %c%.2f [o:%.2f] [%02X%02X%02X%02X%02X%02X]", v[16], v[17], v[18], v[19], v[20], v[21], s, (money / 100.0f), (over / 100.0f), v[10], v[11], v[12], v[13], v[14], v[15]); } else { slog = String .format("%02X%02X.%02X.%02X %02X:%02X %C%.2f [%02X%02X%02X%02X%02X%02X]", v[16], v[17], v[18], v[19], v[20], v[21], s, (money / 100.0f), v[10], v[11], v[12], v[13], v[14], v[15]); } ret.add(slog); } } } if (!ret.isEmpty()) app.setProperty(SPEC.PROP.TRANSLOG, ret.toArray(new String[ret.size()])); } protected Application createApplication() { return new Application(); } protected void configApplication(Application app) { app.setProperty(SPEC.PROP.ID, getApplicationId()); app.setProperty(SPEC.PROP.CURRENCY, getCurrency()); } }
Java
/* NFCard 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. NFCard 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 Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.nfc.reader.pboc; import java.io.IOException; import java.util.ArrayList; import com.sinpo.xnfc.SPEC; import com.sinpo.xnfc.nfc.Util; import com.sinpo.xnfc.nfc.bean.Application; import com.sinpo.xnfc.nfc.bean.Card; import com.sinpo.xnfc.nfc.tech.Iso7816; final class WuhanTong extends StandardPboc { @Override protected SPEC.APP getApplicationId() { return SPEC.APP.WUHANTONG; } @Override protected byte[] getMainApplicationId() { return new byte[] { (byte) 0x41, (byte) 0x50, (byte) 0x31, (byte) 0x2E, (byte) 0x57, (byte) 0x48, (byte) 0x43, (byte) 0x54, (byte) 0x43, }; } @SuppressWarnings("unchecked") @Override protected HINT readCard(Iso7816.StdTag tag, Card card) throws IOException { Iso7816.Response INFO, SERL, BALANCE; /*--------------------------------------------------------------*/ // read card info file, binary (5, 10) /*--------------------------------------------------------------*/ if (!(SERL = tag.readBinary(SFI_SERL)).isOkey()) return HINT.GONEXT; if (!(INFO = tag.readBinary(SFI_INFO)).isOkey()) return HINT.GONEXT; BALANCE = tag.getBalance(true); /*--------------------------------------------------------------*/ // select Main Application /*--------------------------------------------------------------*/ if (!tag.selectByName(getMainApplicationId()).isOkey()) return HINT.RESETANDGONEXT; /*--------------------------------------------------------------*/ // read balance /*--------------------------------------------------------------*/ if (!BALANCE.isOkey()) BALANCE = tag.getBalance(true); /*--------------------------------------------------------------*/ // read log file, record (24) /*--------------------------------------------------------------*/ ArrayList<byte[]> LOG = readLog24(tag, SFI_LOG); /*--------------------------------------------------------------*/ // build result /*--------------------------------------------------------------*/ final Application app = createApplication(); parseBalance(app, BALANCE); parseInfo5(app, SERL, INFO); parseLog24(app, LOG); configApplication(app); card.addApplication(app); return HINT.STOP; } private final static int SFI_INFO = 5; private final static int SFI_SERL = 10; private void parseInfo5(Application app, Iso7816.Response sn, Iso7816.Response info) { if (sn.size() < 27 || info.size() < 27) { return; } final byte[] d = info.getBytes(); app.setProperty(SPEC.PROP.SERIAL, Util.toHexString(sn.getBytes(), 0, 5)); app.setProperty(SPEC.PROP.VERSION, String.format("%02d", d[24])); app.setProperty(SPEC.PROP.DATE, String.format( "%02X%02X.%02X.%02X - %02X%02X.%02X.%02X", d[20], d[21], d[22], d[23], d[16], d[17], d[18], d[19])); } }
Java
/* NFCard 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. NFCard 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 Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.nfc.reader.pboc; import com.sinpo.xnfc.SPEC; final class ShenzhenTong extends StandardPboc { @Override protected SPEC.APP getApplicationId() { return SPEC.APP.SHENZHENTONG; } }
Java
/* NFCard 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. NFCard 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 Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.nfc.reader.pboc; import com.sinpo.xnfc.SPEC; import com.sinpo.xnfc.nfc.Util; import com.sinpo.xnfc.nfc.bean.Application; import com.sinpo.xnfc.nfc.tech.Iso7816; import android.annotation.SuppressLint; final class CityUnion extends StandardPboc { private SPEC.APP applicationId = SPEC.APP.UNKNOWN; @Override protected SPEC.APP getApplicationId() { return applicationId; } @Override protected byte[] getMainApplicationId() { return new byte[] { (byte) 0xA0, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x03, (byte) 0x86, (byte) 0x98, (byte) 0x07, (byte) 0x01, }; } @SuppressLint("DefaultLocale") @Override protected void parseInfo21(Application app, Iso7816.Response data, int dec, boolean bigEndian) { if (!data.isOkey() || data.size() < 30) { return; } final byte[] d = data.getBytes(); if (d[2] == 0x20 && d[3] == 0x00) { applicationId = SPEC.APP.SHANGHAIGJ; bigEndian = true; } else { applicationId = SPEC.APP.CHANGANTONG; bigEndian = false; } if (dec < 1 || dec > 10) { app.setProperty(SPEC.PROP.SERIAL, Util.toHexString(d, 10, 10)); } else { final int sn = Util.toInt(d, 20 - dec, dec); final String ss = bigEndian ? Util.toStringR(sn) : String.format( "%d", 0xFFFFFFFFL & sn); app.setProperty(SPEC.PROP.SERIAL, ss); } if (d[9] != 0) app.setProperty(SPEC.PROP.VERSION, String.valueOf(d[9])); app.setProperty(SPEC.PROP.DATE, String.format( "%02X%02X.%02X.%02X - %02X%02X.%02X.%02X", d[20], d[21], d[22], d[23], d[24], d[25], d[26], d[27])); } }
Java
/* NFCard 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. NFCard 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 Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.nfc.reader.pboc; import java.io.IOException; import java.util.ArrayList; import com.sinpo.xnfc.SPEC; import com.sinpo.xnfc.nfc.Util; import com.sinpo.xnfc.nfc.bean.Application; import com.sinpo.xnfc.nfc.bean.Card; import com.sinpo.xnfc.nfc.tech.Iso7816; import com.sinpo.xnfc.nfc.tech.Iso7816.BerHouse; import com.sinpo.xnfc.nfc.tech.Iso7816.BerTLV; public class Quickpass extends StandardPboc { protected final static byte[] DFN_PPSE = { (byte) '2', (byte) 'P', (byte) 'A', (byte) 'Y', (byte) '.', (byte) 'S', (byte) 'Y', (byte) 'S', (byte) '.', (byte) 'D', (byte) 'D', (byte) 'F', (byte) '0', (byte) '1', }; protected final static byte[] AID_DEBIT = { (byte) 0xA0, 0x00, 0x00, 0x03, 0x33, 0x01, 0x01, 0x01 }; protected final static byte[] AID_CREDIT = { (byte) 0xA0, 0x00, 0x00, 0x03, 0x33, 0x01, 0x01, 0x02 }; protected final static byte[] AID_QUASI_CREDIT = { (byte) 0xA0, 0x00, 0x00, 0x03, 0x33, 0x01, 0x01, 0x03 }; public final static short MARK_LOG = (short) 0xDFFF; protected final static short[] TAG_GLOBAL = { (short) 0x9F79 /* 电子现金余额 */, (short) 0x9F78 /* 电子现金单笔上限 */, (short) 0x9F77 /* 电子现金余额上限 */, (short) 0x9F13 /* 联机ATC */, (short) 0x9F36 /* ATC */, (short) 0x9F51 /* 货币代码 */, (short) 0x9F4F /* 日志文件格式 */, (short) 0x9F4D /* 日志文件ID */, (short) 0x5A /* 帐号 */, (short) 0x5F24 /* 失效日期 */, (short) 0x5F25 /* 生效日期 */, }; @Override protected SPEC.APP getApplicationId() { return SPEC.APP.QUICKPASS; } @Override protected boolean resetTag(Iso7816.StdTag tag) throws IOException { Iso7816.Response rsp = tag.selectByName(DFN_PPSE); if (!rsp.isOkey()) return false; BerTLV.extractPrimitives(topTLVs, rsp); return true; } protected HINT readCard(Iso7816.StdTag tag, Card card) throws IOException { final ArrayList<Iso7816.ID> aids = getApplicationIds(tag); for (Iso7816.ID aid : aids) { /*--------------------------------------------------------------*/ // select application /*--------------------------------------------------------------*/ Iso7816.Response rsp = tag.selectByName(aid.getBytes()); if (!rsp.isOkey()) continue; final BerHouse subTLVs = new BerHouse(); /*--------------------------------------------------------------*/ // collect info /*--------------------------------------------------------------*/ BerTLV.extractPrimitives(subTLVs, rsp); collectTLVFromGlobalTags(tag, subTLVs); /*--------------------------------------------------------------*/ // parse PDOL and get processing options // 这是正规途径,但是每次GPO都会使ATC加1,达到65535卡片就锁定了 /*--------------------------------------------------------------*/ // rsp = tag.getProcessingOptions(buildPDOL(subTLVs)); // if (rsp.isOkey()) // BerTLV.extractPrimitives(subTLVs, rsp); /*--------------------------------------------------------------*/ // 遍历目录下31个文件,山寨途径,微暴力,不知会对卡片折寿多少 // 相对于GPO不停的增加ATC,这是一种折中 // (遍历过程一般不会超过15个文件就会结束) /*--------------------------------------------------------------*/ collectTLVFromRecords(tag, subTLVs); // String dump = subTLVs.toString(); /*--------------------------------------------------------------*/ // build result /*--------------------------------------------------------------*/ final Application app = createApplication(); parseInfo(app, subTLVs); parseLogs(app, subTLVs); card.addApplication(app); } return card.isUnknownCard() ? HINT.RESETANDGONEXT : HINT.STOP; } private static void parseInfo(Application app, BerHouse tlvs) { Object prop = parseString(tlvs, (short) 0x5A); if (prop != null) app.setProperty(SPEC.PROP.SERIAL, prop); prop = parseApplicationName(tlvs, (String) prop); if (prop != null) app.setProperty(SPEC.PROP.ID, prop); prop = parseInteger(tlvs, (short) 0x9F08); if (prop != null) app.setProperty(SPEC.PROP.VERSION, prop); prop = parseInteger(tlvs, (short) 0x9F36); if (prop != null) app.setProperty(SPEC.PROP.COUNT, prop); prop = parseValidity(tlvs, (short) 0x5F25, (short) 0x5F24); if (prop != null) app.setProperty(SPEC.PROP.DATE, prop); prop = parseCurrency(tlvs, (short) 0x9F51); if (prop != null) app.setProperty(SPEC.PROP.CURRENCY, prop); prop = parseAmount(tlvs, (short) 0x9F77); if (prop != null) app.setProperty(SPEC.PROP.DLIMIT, prop); prop = parseAmount(tlvs, (short) 0x9F78); if (prop != null) app.setProperty(SPEC.PROP.TLIMIT, prop); prop = parseAmount(tlvs, (short) 0x9F79); if (prop != null) app.setProperty(SPEC.PROP.ECASH, prop); } private ArrayList<Iso7816.ID> getApplicationIds(Iso7816.StdTag tag) throws IOException { final ArrayList<Iso7816.ID> ret = new ArrayList<Iso7816.ID>(); // try to read DDF BerTLV sfi = topTLVs.findFirst(Iso7816.BerT.CLASS_SFI); if (sfi != null && sfi.length() == 1) { final int SFI = sfi.v.toInt(); Iso7816.Response r = tag.readRecord(SFI, 1); for (int p = 2; r.isOkey(); ++p) { BerTLV.extractPrimitives(topTLVs, r); r = tag.readRecord(SFI, p); } } // add extracted ArrayList<BerTLV> aids = topTLVs.findAll(Iso7816.BerT.CLASS_AID); if (aids != null) { for (BerTLV aid : aids) ret.add(new Iso7816.ID(aid.v.getBytes())); } // use default list if (ret.isEmpty()) { ret.add(new Iso7816.ID(AID_DEBIT)); ret.add(new Iso7816.ID(AID_CREDIT)); ret.add(new Iso7816.ID(AID_QUASI_CREDIT)); } return ret; } /** * private static void buildPDO(ByteBuffer out, int len, byte... val) { * final int n = Math.min((val != null) ? val.length : 0, len); * * int i = 0; while (i < n) out.put(val[i++]); * * while (i++ < len) out.put((byte) 0); } * * private static byte[] buildPDOL(Iso7816.BerHouse tlvs) { * * final ByteBuffer buff = ByteBuffer.allocate(64); * * buff.put((byte) 0x83).put((byte) 0x00); * * try { final byte[] pdol = tlvs.findFirst((short) 0x9F38).v.getBytes(); * * ArrayList<BerTLV> list = BerTLV.extractOptionList(pdol); for * (Iso7816.BerTLV tlv : list) { final int tag = tlv.t.toInt(); final int * len = tlv.l.toInt(); * * switch (tag) { case 0x9F66: // 终端交易属性 buildPDO(buff, len, (byte) 0x48); * break; case 0x9F02: // 授权金额 buildPDO(buff, len); break; case 0x9F03: // * 其它金额 buildPDO(buff, len); break; case 0x9F1A: // 终端国家代码 buildPDO(buff, * len, (byte) 0x01, (byte) 0x56); break; case 0x9F37: // 不可预知数 * buildPDO(buff, len); break; case 0x5F2A: // 交易货币代码 buildPDO(buff, len, * (byte) 0x01, (byte) 0x56); break; case 0x95: // 终端验证结果 buildPDO(buff, * len); break; case 0x9A: // 交易日期 buildPDO(buff, len); break; case 0x9C: // * 交易类型 buildPDO(buff, len); break; default: throw null; } } // 更新数据长度 * buff.put(1, (byte) (buff.position() - 2)); } catch (Exception e) { * buff.position(2); } * * return Arrays.copyOfRange(buff.array(), 0, buff.position()); } */ private static void collectTLVFromGlobalTags(Iso7816.StdTag tag, BerHouse tlvs) throws IOException { for (short t : TAG_GLOBAL) { Iso7816.Response r = tag.getData(t); if (r.isOkey()) tlvs.add(BerTLV.read(r)); } } private static void collectTLVFromRecords(Iso7816.StdTag tag, BerHouse tlvs) throws IOException { // info files for (int sfi = 1; sfi <= 10; ++sfi) { Iso7816.Response r = tag.readRecord(sfi, 1); for (int idx = 2; r.isOkey() && idx <= 10; ++idx) { BerTLV.extractPrimitives(tlvs, r); r = tag.readRecord(sfi, idx); } } // check if already get sfi of log file BerTLV logEntry = tlvs.findFirst((short) 0x9F4D); final int S, E; if (logEntry != null && logEntry.length() == 2) { S = E = logEntry.v.getBytes()[0] & 0x000000FF; } else { S = 11; E = 31; } // log files for (int sfi = S; sfi <= E; ++sfi) { Iso7816.Response r = tag.readRecord(sfi, 1); boolean findOne = r.isOkey(); for (int idx = 2; r.isOkey() && idx <= 10; ++idx) { tlvs.add(MARK_LOG, r); r = tag.readRecord(sfi, idx); } if (findOne) break; } } private static SPEC.APP parseApplicationName(BerHouse tlvs, String serial) { String f = parseString(tlvs, (short) 0x84); if (f != null) { if (f.endsWith("010101")) return SPEC.APP.DEBIT; if (f.endsWith("010102")) return SPEC.APP.CREDIT; if (f.endsWith("010103")) return SPEC.APP.QCREDIT; } return SPEC.APP.UNKNOWN; } private static SPEC.CUR parseCurrency(BerHouse tlvs, short tag) { return SPEC.CUR.CNY; } private static String parseValidity(BerHouse tlvs, short from, short to) { final byte[] f = BerTLV.getValue(tlvs.findFirst(from)); final byte[] t = BerTLV.getValue(tlvs.findFirst(to)); if (t == null || t.length != 3 || t[0] == 0 || t[0] == (byte) 0xFF) return null; if (f == null || f.length != 3 || f[0] == 0 || f[0] == (byte) 0xFF) return String.format("? - 20%02x.%02x.%02x", t[0], t[1], t[2]); return String.format("20%02x.%02x.%02x - 20%02x.%02x.%02x", f[0], f[1], f[2], t[0], t[1], t[2]); } private static String parseString(BerHouse tlvs, short tag) { final byte[] v = BerTLV.getValue(tlvs.findFirst(tag)); return (v != null) ? Util.toHexString(v) : null; } private static Float parseAmount(BerHouse tlvs, short tag) { Integer v = parseIntegerBCD(tlvs, tag); return (v != null) ? v / 100.0f : null; } private static Integer parseInteger(BerHouse tlvs, short tag) { final byte[] v = BerTLV.getValue(tlvs.findFirst(tag)); return (v != null) ? Util.toInt(v) : null; } private static Integer parseIntegerBCD(BerHouse tlvs, short tag) { final byte[] v = BerTLV.getValue(tlvs.findFirst(tag)); return (v != null) ? Util.BCDtoInt(v) : null; } private static void parseLogs(Application app, BerHouse tlvs) { final byte[] rawTemp = BerTLV.getValue(tlvs.findFirst((short) 0x9F4F)); if (rawTemp == null) return; final ArrayList<BerTLV> temp = BerTLV.extractOptionList(rawTemp); if (temp == null || temp.isEmpty()) return; final ArrayList<BerTLV> logs = tlvs.findAll(MARK_LOG); final ArrayList<String> ret = new ArrayList<String>(logs.size()); for (BerTLV log : logs) { String l = parseLog(temp, log.v.getBytes()); if (l != null) ret.add(l); } if (!ret.isEmpty()) app.setProperty(SPEC.PROP.TRANSLOG, ret.toArray(new String[ret.size()])); } private static String parseLog(ArrayList<BerTLV> temp, byte[] data) { try { int date = -1, time = -1; int amount = 0, type = -1; int cursor = 0; for (BerTLV f : temp) { final int n = f.length(); switch (f.t.toInt()) { case 0x9A: // 交易日期 date = Util.BCDtoInt(data, cursor, n); break; case 0x9F21: // 交易时间 time = Util.BCDtoInt(data, cursor, n); break; case 0x9F02: // 授权金额 amount = Util.BCDtoInt(data, cursor, n); break; case 0x9C: // 交易类型 type = Util.BCDtoInt(data, cursor, n); break; case 0x9F03: // 其它金额 case 0x9F1A: // 终端国家代码 case 0x5F2A: // 交易货币代码 case 0x9F4E: // 商户名称 case 0x9F36: // 应用交易计数器(ATC) default: break; } cursor += n; } if (amount <= 0) return null; final char sign; switch (type) { case 0: // 刷卡消费 case 1: // 取现 case 8: // 转账 case 9: // 支付 case 20: // 退款 case 40: // 持卡人账户转账 sign = '-'; break; default: sign = '+'; break; } String sd = (date <= 0) ? "****.**.**" : String.format( "20%02d.%02d.%02d", (date / 10000) % 100, (date / 100) % 100, date % 100); String st = (time <= 0) ? "**:**" : String.format("%02d:%02d", (time / 10000) % 100, (time / 100) % 100); final StringBuilder ret = new StringBuilder(); ret.append(String.format("%s %s %c%.2f", sd, st, sign, amount / 100f)); return ret.toString(); } catch (Exception e) { return null; } } private final BerHouse topTLVs = new BerHouse(); }
Java
/* NFCard 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. NFCard 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 Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.nfc.reader.pboc; import java.io.IOException; import java.util.ArrayList; import com.sinpo.xnfc.SPEC; import com.sinpo.xnfc.nfc.Util; import com.sinpo.xnfc.nfc.bean.Application; import com.sinpo.xnfc.nfc.bean.Card; import com.sinpo.xnfc.nfc.tech.Iso7816; final class BeijingMunicipal extends StandardPboc { @Override protected SPEC.APP getApplicationId() { return SPEC.APP.BEIJINGMUNICIPAL; } @SuppressWarnings("unchecked") @Override protected HINT readCard(Iso7816.StdTag tag, Card card) throws IOException { Iso7816.Response INFO, CNT, BALANCE; /*--------------------------------------------------------------*/ // read card info file, binary (4) /*--------------------------------------------------------------*/ INFO = tag.readBinary(SFI_EXTRA_LOG); if (!INFO.isOkey()) return HINT.GONEXT; /*--------------------------------------------------------------*/ // read card operation file, binary (5) /*--------------------------------------------------------------*/ CNT = tag.readBinary(SFI_EXTRA_CNT); /*--------------------------------------------------------------*/ // select Main Application /*--------------------------------------------------------------*/ if (!tag.selectByID(DFI_EP).isOkey()) return HINT.RESETANDGONEXT; BALANCE = tag.getBalance(true); /*--------------------------------------------------------------*/ // read log file, record (24) /*--------------------------------------------------------------*/ ArrayList<byte[]> LOG = readLog24(tag, SFI_LOG); /*--------------------------------------------------------------*/ // build result /*--------------------------------------------------------------*/ final Application app = createApplication(); parseBalance(app, BALANCE); parseInfo4(app, INFO, CNT); parseLog24(app, LOG); configApplication(app); card.addApplication(app); return HINT.STOP; } private final static int SFI_EXTRA_LOG = 4; private final static int SFI_EXTRA_CNT = 5; private void parseInfo4(Application app, Iso7816.Response info, Iso7816.Response cnt) { if (!info.isOkey() || info.size() < 32) { return; } final byte[] d = info.getBytes(); app.setProperty(SPEC.PROP.SERIAL, Util.toHexString(d, 0, 8)); app.setProperty(SPEC.PROP.VERSION, String.format("%02X.%02X%02X", d[8], d[9], d[10])); app.setProperty(SPEC.PROP.DATE, String.format( "%02X%02X.%02X.%02X - %02X%02X.%02X.%02X", d[24], d[25], d[26], d[27], d[28], d[29], d[30], d[31])); if (cnt != null && cnt.isOkey() && cnt.size() > 4) { byte[] e = cnt.getBytes(); final int n = Util.toInt(e, 1, 4); if (e[0] == 0) app.setProperty(SPEC.PROP.COUNT, String.format("%d", n)); else app.setProperty(SPEC.PROP.COUNT, String.format("%d*", n)); } } }
Java
/* NFCard 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. NFCard 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 Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.nfc.reader; import java.io.IOException; import com.sinpo.xnfc.SPEC; import com.sinpo.xnfc.nfc.Util; import com.sinpo.xnfc.nfc.bean.Application; import com.sinpo.xnfc.nfc.bean.Card; import com.sinpo.xnfc.nfc.tech.FeliCa; import android.nfc.tech.NfcF; final class FelicaReader { static void readCard(NfcF tech, Card card) throws IOException { final FeliCa.Tag tag = new FeliCa.Tag(tech); tag.connect(); /* * FeliCa.SystemCode systems[] = tag.getSystemCodeList(); if (systems.length == 0) { systems = new FeliCa.SystemCode[] { new FeliCa.SystemCode( tag.getSystemCodeByte()) }; } for (final FeliCa.SystemCode sys : systems) card.addApplication(readApplication(tag, sys.toInt())); */ // better old card compatibility card.addApplication(readApplication(tag, SYS_OCTOPUS)); try { card.addApplication(readApplication(tag, SYS_SZT)); } catch (IOException e) { // for early version of OCTOPUS which will throw shit } tag.close(); } private static final int SYS_SZT = 0x8005; private static final int SYS_OCTOPUS = 0x8008; private static final int SRV_SZT = 0x0118; private static final int SRV_OCTOPUS = 0x0117; private static Application readApplication(FeliCa.Tag tag, int system) throws IOException { final FeliCa.ServiceCode scode; final Application app; if (system == SYS_OCTOPUS) { app = new Application(); app.setProperty(SPEC.PROP.ID, SPEC.APP.OCTOPUS); app.setProperty(SPEC.PROP.CURRENCY, SPEC.CUR.HKD); scode = new FeliCa.ServiceCode(SRV_OCTOPUS); } else if (system == SYS_SZT) { app = new Application(); app.setProperty(SPEC.PROP.ID, SPEC.APP.SHENZHENTONG); app.setProperty(SPEC.PROP.CURRENCY, SPEC.CUR.CNY); scode = new FeliCa.ServiceCode(SRV_SZT); } else { return null; } app.setProperty(SPEC.PROP.SERIAL, tag.getIDm().toString()); app.setProperty(SPEC.PROP.PARAM, tag.getPMm().toString()); tag.polling(system); final float[] data = new float[] { 0, 0, 0 }; int p = 0; for (byte i = 0; p < data.length; ++i) { final FeliCa.ReadResponse r = tag.readWithoutEncryption(scode, i); if (!r.isOkey()) break; data[p++] = (Util.toInt(r.getBlockData(), 0, 4) - 350) / 10.0f; } if (p != 0) app.setProperty(SPEC.PROP.BALANCE, parseBalance(data)); else app.setProperty(SPEC.PROP.BALANCE, Float.NaN); return app; } private static float parseBalance(float[] value) { float balance = 0f; for (float v : value) balance += v; return balance; } }
Java
/* NFCard 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. NFCard 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 Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc; import java.lang.Thread.UncaughtExceptionHandler; import com.sinpo.xnfc.R; import android.app.Application; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.util.DisplayMetrics; import android.widget.Toast; public final class ThisApplication extends Application implements UncaughtExceptionHandler { private static ThisApplication instance; @Override public void uncaughtException(Thread thread, Throwable ex) { System.exit(0); } @Override public void onCreate() { super.onCreate(); Thread.setDefaultUncaughtExceptionHandler(this); instance = this; } public static String name() { return getStringResource(R.string.app_name); } public static String version() { try { return instance.getPackageManager().getPackageInfo( instance.getPackageName(), 0).versionName; } catch (Exception e) { return "1.0"; } } public static void showMessage(int fmt, CharSequence... msgs) { String msg = String.format(getStringResource(fmt), msgs); Toast.makeText(instance, msg, Toast.LENGTH_LONG).show(); } public static Typeface getFontResource(int pathId) { String path = getStringResource(pathId); return Typeface.createFromAsset(instance.getAssets(), path); } public static int getDimensionResourcePixelSize(int resId) { return instance.getResources().getDimensionPixelSize(resId); } public static int getColorResource(int resId) { return instance.getResources().getColor(resId); } public static String getStringResource(int resId) { return instance.getString(resId); } public static Drawable getDrawableResource(int resId) { return instance.getResources().getDrawable(resId); } public static DisplayMetrics getDisplayMetrics() { return instance.getResources().getDisplayMetrics(); } }
Java
/* NFCard 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. NFCard 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 Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.ui; import android.app.Activity; import android.content.Intent; import com.sinpo.xnfc.R; import com.sinpo.xnfc.ThisApplication; public final class AboutPage { private static final String TAG = "ABOUTPAGE_ACTION"; public static CharSequence getContent(Activity activity) { String tip = ThisApplication .getStringResource(R.string.info_main_about); tip = tip.replace("<app />", ThisApplication.name()); tip = tip.replace("<version />", ThisApplication.version()); return new SpanFormatter(null).toSpanned(tip); } public static boolean isSendByMe(Intent intent) { return intent != null && TAG.equals(intent.getAction()); } static SpanFormatter.ActionHandler getActionHandler(Activity activity) { return new Handler(activity); } private static final class Handler implements SpanFormatter.ActionHandler { private final Activity activity; Handler(Activity activity) { this.activity = activity; } @Override public void handleAction(CharSequence name) { activity.setIntent(new Intent(TAG)); } } private AboutPage() { } }
Java
/* NFCard 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. NFCard 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 Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.ui; import android.animation.LayoutTransition; import android.annotation.SuppressLint; import android.content.Context; import android.os.Build; import android.text.ClipboardManager; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.sinpo.xnfc.R; import com.sinpo.xnfc.ThisApplication; public final class Toolbar { final ViewGroup toolbar; @SuppressLint("NewApi") public Toolbar(ViewGroup toolbar) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) toolbar.setLayoutTransition(new LayoutTransition()); this.toolbar = toolbar; } public void copyPageContent(TextView textArea) { final CharSequence text = textArea.getText(); if (text != null) { ((ClipboardManager) textArea.getContext().getSystemService( Context.CLIPBOARD_SERVICE)).setText(text); ThisApplication.showMessage(R.string.info_main_copied); } } public void show(int... buttons) { hide(); showDelayed(1000, buttons); } private void hide() { final int n = toolbar.getChildCount(); for (int i = 0; i < n; ++i) toolbar.getChildAt(i).setVisibility(View.GONE); } private void showDelayed(int delay, int... buttons) { toolbar.postDelayed(new Helper(buttons), delay); } private final class Helper implements Runnable { private final int[] buttons; Helper(int... buttons) { this.buttons = buttons; } @Override public void run() { final int n = toolbar.getChildCount(); for (int i = 0; i < n; ++i) { final View view = toolbar.getChildAt(i); int visibility = View.GONE; if (buttons != null) { final int id = view.getId(); for (int btn : buttons) { if (btn == id) { visibility = View.VISIBLE; break; } } } view.setVisibility(visibility); } } } }
Java
/* NFCard 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. NFCard 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 Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.ui; import java.lang.ref.WeakReference; import org.xml.sax.XMLReader; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Paint.FontMetricsInt; import android.graphics.Typeface; import android.text.Editable; import android.text.Html; import android.text.Spannable; import android.text.Spanned; import android.text.TextPaint; import android.text.style.ClickableSpan; import android.text.style.LineHeightSpan; import android.text.style.MetricAffectingSpan; import android.text.style.ReplacementSpan; import android.util.DisplayMetrics; import android.view.View; import com.sinpo.xnfc.R; import com.sinpo.xnfc.SPEC; import com.sinpo.xnfc.ThisApplication; public final class SpanFormatter implements Html.TagHandler { public interface ActionHandler { void handleAction(CharSequence name); } private final ActionHandler handler; public SpanFormatter(ActionHandler handler) { this.handler = handler; } public CharSequence toSpanned(String html) { return Html.fromHtml(html, null, this); } private static final class ActionSpan extends ClickableSpan { private final String action; private final ActionHandler handler; private final int color; ActionSpan(String action, ActionHandler handler, int color) { this.action = action; this.handler = handler; this.color = color; } @Override public void onClick(View widget) { if (handler != null) handler.handleAction(action); } @Override public void updateDrawState(TextPaint ds) { super.updateDrawState(ds); ds.setColor(color); } } private static final class FontSpan extends MetricAffectingSpan { final int color; final float size; final Typeface face; final boolean bold; FontSpan(int color, float size, Typeface face) { this.color = color; this.size = size; if (face == Typeface.DEFAULT) { this.face = null; this.bold = false; } else if (face == Typeface.DEFAULT_BOLD) { this.face = null; this.bold = true; } else { this.face = face; this.bold = false; } } @Override public void updateDrawState(TextPaint ds) { ds.setTextSize(size); ds.setColor(color); if (face != null) { ds.setTypeface(face); } else if (bold) { Typeface tf = ds.getTypeface(); if (tf != null) { int style = tf.getStyle() | Typeface.BOLD; tf = Typeface.create(tf, style); ds.setTypeface(tf); style &= ~tf.getStyle(); if ((style & Typeface.BOLD) != 0) { ds.setFakeBoldText(true); } } } } @Override public void updateMeasureState(TextPaint p) { updateDrawState(p); } } private static final class ParagSpan implements LineHeightSpan { private final int linespaceDelta; ParagSpan(int linespaceDelta) { this.linespaceDelta = linespaceDelta; } @Override public void chooseHeight(CharSequence text, int start, int end, int spanstartv, int v, FontMetricsInt fm) { fm.bottom += linespaceDelta; fm.descent += linespaceDelta; } } private static final class SplitterSpan extends ReplacementSpan { private final int color; private final int width; private final int height; SplitterSpan(int color, int width, int height) { this.color = color; this.width = width; this.height = height; } @Override public void updateDrawState(TextPaint ds) { ds.setTextSize(1); } @Override public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) { return 0; } @Override public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) { canvas.save(); canvas.translate(x, (bottom + top) / 2 - height); final int c = paint.getColor(); paint.setColor(color); canvas.drawRect(x, 0, x + width, height, paint); paint.setColor(c); canvas.restore(); } } @Override public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) { final int len = output.length(); if (opening) { if (SPEC.TAG_TEXT.equals(tag)) { markFontSpan(output, len, R.color.tag_text, R.dimen.tag_text, Typeface.DEFAULT); } else if (SPEC.TAG_TIP.equals(tag)) { markParagSpan(output, len, R.dimen.tag_parag); markFontSpan(output, len, R.color.tag_tip, R.dimen.tag_tip, getTipFont()); } else if (SPEC.TAG_LAB.equals(tag)) { markFontSpan(output, len, R.color.tag_lab, R.dimen.tag_lab, Typeface.DEFAULT_BOLD); } else if (SPEC.TAG_ITEM.equals(tag)) { markFontSpan(output, len, R.color.tag_item, R.dimen.tag_item, Typeface.DEFAULT); } else if (SPEC.TAG_H1.equals(tag)) { markFontSpan(output, len, R.color.tag_h1, R.dimen.tag_h1, Typeface.DEFAULT_BOLD); } else if (SPEC.TAG_H2.equals(tag)) { markFontSpan(output, len, R.color.tag_h2, R.dimen.tag_h2, Typeface.DEFAULT_BOLD); } else if (SPEC.TAG_H3.equals(tag)) { markFontSpan(output, len, R.color.tag_h3, R.dimen.tag_h3, Typeface.SERIF); } else if (tag.startsWith(SPEC.TAG_ACT)) { markActionSpan(output, len, tag, R.color.tag_action); } else if (SPEC.TAG_PARAG.equals(tag)) { markParagSpan(output, len, R.dimen.tag_parag); } else if (SPEC.TAG_SP.equals(tag)) { markSpliterSpan(output, len, R.color.tag_action, R.dimen.tag_spliter); } } else { if (SPEC.TAG_TEXT.equals(tag)) { setSpan(output, len, FontSpan.class); } else if (SPEC.TAG_TIP.equals(tag)) { setSpan(output, len, FontSpan.class); setSpan(output, len, ParagSpan.class); } else if (SPEC.TAG_LAB.equals(tag)) { setSpan(output, len, FontSpan.class); } else if (SPEC.TAG_ITEM.equals(tag)) { setSpan(output, len, FontSpan.class); } else if (SPEC.TAG_H1.equals(tag)) { setSpan(output, len, FontSpan.class); } else if (SPEC.TAG_H2.equals(tag)) { setSpan(output, len, FontSpan.class); } else if (SPEC.TAG_H3.equals(tag)) { setSpan(output, len, FontSpan.class); } else if (tag.startsWith(SPEC.TAG_ACT)) { setSpan(output, len, ActionSpan.class); } else if (SPEC.TAG_PARAG.equals(tag)) { setSpan(output, len, ParagSpan.class); } } } private static void markSpliterSpan(Editable out, int pos, int colorId, int heightId) { DisplayMetrics dm = ThisApplication.getDisplayMetrics(); int color = ThisApplication.getColorResource(colorId); int height = ThisApplication.getDimensionResourcePixelSize(heightId); out.append("-------------------").setSpan( new SplitterSpan(color, dm.widthPixels, height), pos, out.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } private static void markFontSpan(Editable out, int pos, int colorId, int sizeId, Typeface face) { int color = ThisApplication.getColorResource(colorId); float size = ThisApplication.getDimensionResourcePixelSize(sizeId); FontSpan span = new FontSpan(color, size, face); out.setSpan(span, pos, pos, Spannable.SPAN_MARK_MARK); } private static void markParagSpan(Editable out, int pos, int linespaceId) { int linespace = ThisApplication .getDimensionResourcePixelSize(linespaceId); ParagSpan span = new ParagSpan(linespace); out.setSpan(span, pos, pos, Spannable.SPAN_MARK_MARK); } private void markActionSpan(Editable out, int pos, String tag, int colorId) { int color = ThisApplication.getColorResource(colorId); out.setSpan(new ActionSpan(tag, handler, color), pos, pos, Spannable.SPAN_MARK_MARK); } private static void setSpan(Editable out, int pos, Class<?> kind) { Object span = getLastMarkSpan(out, kind); out.setSpan(span, out.getSpanStart(span), pos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } private static Object getLastMarkSpan(Spanned text, Class<?> kind) { Object[] objs = text.getSpans(0, text.length(), kind); if (objs.length == 0) { return null; } else { return objs[objs.length - 1]; } } private static Typeface getTipFont() { Typeface ret = null; WeakReference<Typeface> wr = TIPFONT; if (wr != null) ret = wr.get(); if (ret == null) { ret = ThisApplication.getFontResource(R.string.font_oem3); TIPFONT = new WeakReference<Typeface>(ret); } return ret; } private static WeakReference<Typeface> TIPFONT; }
Java
/* NFCard 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. NFCard 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 Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.ui; import android.app.Activity; import android.app.Dialog; import android.content.Intent; import com.sinpo.xnfc.R; import com.sinpo.xnfc.ThisApplication; import com.sinpo.xnfc.SPEC.EVENT; import com.sinpo.xnfc.nfc.bean.Card; import com.sinpo.xnfc.nfc.reader.ReaderListener; public final class NfcPage implements ReaderListener { private static final String TAG = "READCARD_ACTION"; private static final String RET = "READCARD_RESULT"; private static final String STA = "READCARD_STATUS"; private final Activity activity; public NfcPage(Activity activity) { this.activity = activity; } public static boolean isSendByMe(Intent intent) { return intent != null && TAG.equals(intent.getAction()); } public static boolean isNormalInfo(Intent intent) { return intent != null && intent.hasExtra(STA); } public static CharSequence getContent(Activity activity, Intent intent) { String info = intent.getStringExtra(RET); if (info == null || info.length() == 0) return null; return new SpanFormatter(AboutPage.getActionHandler(activity)) .toSpanned(info); } @Override public void onReadEvent(EVENT event, Object... objs) { if (event == EVENT.IDLE) { showProgressBar(); } else if (event == EVENT.FINISHED) { hideProgressBar(); final Card card; if (objs != null && objs.length > 0) card = (Card) objs[0]; else card = null; activity.setIntent(buildResult(card)); } } private Intent buildResult(Card card) { final Intent ret = new Intent(TAG); if (card != null && !card.hasReadingException()) { if (card.isUnknownCard()) { ret.putExtra(RET, ThisApplication .getStringResource(R.string.info_nfc_unknown)); } else { ret.putExtra(RET, card.toHtml()); ret.putExtra(STA, 1); } } else { ret.putExtra(RET, ThisApplication.getStringResource(R.string.info_nfc_error)); } return ret; } private void showProgressBar() { Dialog d = progressBar; if (d == null) { d = new Dialog(activity, R.style.progressBar); d.setCancelable(false); d.setContentView(R.layout.progress); progressBar = d; } if (!d.isShowing()) d.show(); } private void hideProgressBar() { final Dialog d = progressBar; if (d != null && d.isShowing()) d.cancel(); } private Dialog progressBar; }
Java
/* NFCard 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. NFCard 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 Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc.ui; import static android.provider.Settings.ACTION_SETTINGS; import android.app.Activity; import android.content.Intent; import android.nfc.NfcAdapter; import com.sinpo.xnfc.R; import com.sinpo.xnfc.ThisApplication; public final class MainPage { public static CharSequence getContent(Activity activity) { final NfcAdapter nfc = NfcAdapter.getDefaultAdapter(activity); final int resid; if (nfc == null) resid = R.string.info_nfc_notsupport; else if (!nfc.isEnabled()) resid = R.string.info_nfc_disabled; else resid = R.string.info_nfc_nocard; String tip = ThisApplication.getStringResource(resid); return new SpanFormatter(new Handler(activity)).toSpanned(tip); } private static final class Handler implements SpanFormatter.ActionHandler { private final Activity activity; Handler(Activity activity) { this.activity = activity; } @Override public void handleAction(CharSequence name) { startNfcSettingsActivity(); } private void startNfcSettingsActivity() { activity.startActivityForResult(new Intent(ACTION_SETTINGS), 0); } } private MainPage() { } }
Java
/* NFCard 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. NFCard 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 Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc; import com.sinpo.xnfc.R; public final class SPEC { public enum PAGE { DEFAULT, INFO, ABOUT, } public enum EVENT { IDLE, ERROR, READING, FINISHED, } public enum PROP { ID(R.string.spec_prop_id), SERIAL(R.string.spec_prop_serial), PARAM(R.string.spec_prop_param), VERSION(R.string.spec_prop_version), DATE(R.string.spec_prop_date), COUNT(R.string.spec_prop_count), CURRENCY(R.string.spec_prop_currency), TLIMIT(R.string.spec_prop_tlimit), DLIMIT(R.string.spec_prop_dlimit), ECASH(R.string.spec_prop_ecash), BALANCE(R.string.spec_prop_balance), TRANSLOG(R.string.spec_prop_translog), ACCESS(R.string.spec_prop_access), EXCEPTION(R.string.spec_prop_exception); public String toString() { return ThisApplication.getStringResource(resId); } private final int resId; private PROP(int resId) { this.resId = resId; } } public enum APP { UNKNOWN(R.string.spec_app_unknown), SHENZHENTONG(R.string.spec_app_shenzhentong), QUICKPASS(R.string.spec_app_quickpass), OCTOPUS(R.string.spec_app_octopus_hk), BEIJINGMUNICIPAL(R.string.spec_app_beijing), WUHANTONG(R.string.spec_app_wuhantong), CHANGANTONG(R.string.spec_app_changantong), SHANGHAIGJ(R.string.spec_app_shanghai), DEBIT(R.string.spec_app_debit), CREDIT(R.string.spec_app_credit), QCREDIT(R.string.spec_app_qcredit); public String toString() { return ThisApplication.getStringResource(resId); } private final int resId; private APP(int resId) { this.resId = resId; } } public enum CUR { UNKNOWN(R.string.spec_cur_unknown), USD(R.string.spec_cur_usd), CNY(R.string.spec_cur_cny), HKD(R.string.spec_cur_hkd); public String toString() { return ThisApplication.getStringResource(resId); } private final int resId; private CUR(int resId) { this.resId = resId; } } public static final String TAG_BLK = "div"; public static final String TAG_TIP = "t_tip"; public static final String TAG_ACT = "t_action"; public static final String TAG_EM = "t_em"; public static final String TAG_H1 = "t_head1"; public static final String TAG_H2 = "t_head2"; public static final String TAG_H3 = "t_head3"; public static final String TAG_SP = "t_splitter"; public static final String TAG_TEXT = "t_text"; public static final String TAG_ITEM = "t_item"; public static final String TAG_LAB = "t_label"; public static final String TAG_PARAG = "t_parag"; }
Java
/* NFCard 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. NFCard 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 Wget. If not, see <http://www.gnu.org/licenses/>. Additional permission under GNU GPL version 3 section 7 */ package com.sinpo.xnfc; import android.app.Activity; import android.content.Intent; import android.graphics.Typeface; import android.os.Bundle; import android.text.method.LinkMovementMethod; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.ViewSwitcher; import com.sinpo.xnfc.R; import com.sinpo.xnfc.nfc.NfcManager; import com.sinpo.xnfc.ui.AboutPage; import com.sinpo.xnfc.ui.MainPage; import com.sinpo.xnfc.ui.NfcPage; import com.sinpo.xnfc.ui.Toolbar; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initViews(); nfc = new NfcManager(this); onNewIntent(getIntent()); } @Override public void onBackPressed() { if (isCurrentPage(SPEC.PAGE.ABOUT)) loadDefaultPage(); else if (safeExit) super.onBackPressed(); } @Override public void setIntent(Intent intent) { if (NfcPage.isSendByMe(intent)) loadNfcPage(intent); else if (AboutPage.isSendByMe(intent)) loadAboutPage(); else super.setIntent(intent); } @Override protected void onPause() { super.onPause(); nfc.onPause(); } @Override protected void onResume() { super.onResume(); nfc.onResume(); } @Override public void onWindowFocusChanged(boolean hasFocus) { if (hasFocus) { if (nfc.updateStatus()) loadDefaultPage(); // 有些ROM将关闭系统状态下拉面板的BACK事件发给最顶层窗口 // 这里加入一个延迟避免意外退出 board.postDelayed(new Runnable() { public void run() { safeExit = true; } }, 800); } else { safeExit = false; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { loadDefaultPage(); } @Override protected void onNewIntent(Intent intent) { if (!nfc.readCard(intent, new NfcPage(this))) loadDefaultPage(); } public void onSwitch2DefaultPage(View view) { if (!isCurrentPage(SPEC.PAGE.DEFAULT)) loadDefaultPage(); } public void onSwitch2AboutPage(View view) { if (!isCurrentPage(SPEC.PAGE.ABOUT)) loadAboutPage(); } public void onCopyPageContent(View view) { toolbar.copyPageContent(getFrontPage()); } private void loadDefaultPage() { toolbar.show(null); TextView ta = getBackPage(); resetTextArea(ta, SPEC.PAGE.DEFAULT, Gravity.CENTER); ta.setText(MainPage.getContent(this)); board.showNext(); } private void loadAboutPage() { toolbar.show(R.id.btnBack); TextView ta = getBackPage(); resetTextArea(ta, SPEC.PAGE.ABOUT, Gravity.LEFT); ta.setText(AboutPage.getContent(this)); board.showNext(); } private void loadNfcPage(Intent intent) { final CharSequence info = NfcPage.getContent(this, intent); TextView ta = getBackPage(); if (NfcPage.isNormalInfo(intent)) { toolbar.show(R.id.btnCopy, R.id.btnReset); resetTextArea(ta, SPEC.PAGE.INFO, Gravity.LEFT); } else { toolbar.show(R.id.btnBack); resetTextArea(ta, SPEC.PAGE.INFO, Gravity.CENTER); } ta.setText(info); board.showNext(); } private boolean isCurrentPage(SPEC.PAGE which) { Object obj = getFrontPage().getTag(); if (obj == null) return which.equals(SPEC.PAGE.DEFAULT); return which.equals(obj); } private void resetTextArea(TextView textArea, SPEC.PAGE type, int gravity) { ((View) textArea.getParent()).scrollTo(0, 0); textArea.setTag(type); textArea.setGravity(gravity); } private TextView getFrontPage() { return (TextView) ((ViewGroup) board.getCurrentView()).getChildAt(0); } private TextView getBackPage() { return (TextView) ((ViewGroup) board.getNextView()).getChildAt(0); } private void initViews() { board = (ViewSwitcher) findViewById(R.id.switcher); Typeface tf = ThisApplication.getFontResource(R.string.font_oem1); TextView tv = (TextView) findViewById(R.id.txtAppName); tv.setTypeface(tf); tf = ThisApplication.getFontResource(R.string.font_oem2); tv = getFrontPage(); tv.setMovementMethod(LinkMovementMethod.getInstance()); tv.setTypeface(tf); tv = getBackPage(); tv.setMovementMethod(LinkMovementMethod.getInstance()); tv.setTypeface(tf); toolbar = new Toolbar((ViewGroup) findViewById(R.id.toolbar)); } private ViewSwitcher board; private Toolbar toolbar; private NfcManager nfc; private boolean safeExit; }
Java
package sk.tuke.kpi.annACME.version1; import java.lang.annotation.ElementType; import java.lang.annotation.Target; /** * Component can span over multiple classes, the binding is done upon the component * name that has to be unique. * @author Milan, Ivan */ @Target(ElementType.TYPE) public @interface Component { public String name(); }
Java
package sk.tuke.kpi.annACME.version1; /** * No direct representation in source code for connector, from the viewpoint * of OOP the connector is an abstract concept. * @author Milan */ public @interface Connector { public String name(); public Role[] roles(); }
Java
package sk.tuke.kpi.annACME.version1; import java.lang.annotation.ElementType; import java.lang.annotation.Target; /** * Defines ports of the component, may be used on fields and methods. Again may * span across multiple fields or methods and the name is the identifier. * @author Milan, Ivan */ @Target({ElementType.FIELD, ElementType.METHOD, ElementType.CONSTRUCTOR}) public @interface Port { public String name(); }
Java
package sk.tuke.kpi.annACME.version1; /** * Role has no direct representation in OO program and is only a part of * some connector. * @author Milan, Ivan */ public @interface Role { public String name(); }
Java
package sk.tuke.kpi.annACME.version1; /** * No direct representation in host OO program. * @author Milan */ public @interface Attachment { public String component(); public String port(); public String connector(); public String role(); }
Java
package sk.tuke.kpi.annACME.version1; import java.lang.annotation.ElementType; import java.lang.annotation.Target; /** * Top-most package annotation that declares that this package will be a system * described by @ACME. * @author Milan, Ivan */ @Target(ElementType.PACKAGE) public @interface System { public String name(); public Connector[] connectors() default {}; }
Java
import java.util.Date; public class RequestObject { private String weekday; private Date date; public String getWeekday() { return weekday; } public void setWeekday(String weekday) { this.weekday = weekday; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } }
Java
import java.util.Date; public class Examples1 { public int getLength(String str) { if (str == null) return str.length(); return 0; } public int getLength2(String str) { return str.length(); } public void complexMethod2(RequestObject request) { String day = request.getWeekday(); if (day.equals("Tuesday")) { // processPayroll(); } } public void complexMethod(RequestObject request) { String day = request.getWeekday(); Date date = request.getDate(); if (day.equals("Tuesday")) { // NOSONAR } if ((day != null && day.equals("Saturday")) || (day != null && day.equals("Sunday")) || isHoliday(date)) { sleepLate(); } } private void sleepLate() {} private boolean isHoliday(Date day) { return false; } private boolean isVacation(Date day) //NOSONAR { return false; } }
Java
public abstract class Animal { public abstract String getGenus(); public abstract String getSpecies(); public abstract int getNumLegs(); }
Java
import java.util.Date; public interface RequestHandling { public String removeFromInventory(String userId, Date requestDate, String departmentId, String organizationId, String itemId, int qty, String reason, float price, int discountPercentage); }
Java
public class OutputException extends Exception { String output; public OutputException (StackTraceElement [] stacktrace) { super(); this.setStackTrace(stacktrace); } public String getOutput() { return output; } public void setOutput(String output) { this.output = output; } }
Java
package org.manning.sonarinaction.duplications; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; public class InternationalOrder { private InternationalCustomer customer; private List<OrderLine> orderlines = new ArrayList<OrderLine>(); public void addOrderLine(final OrderLine orderLine) { orderlines.add(orderLine); } public void removeOrderLine(final OrderLine orderLine) { orderlines.remove(orderLine); } public InternationalCustomer getCustomer() { return customer; } public void setCustomer(InternationalCustomer customer) { this.customer = customer; } public BigDecimal getTotal() { BigDecimal total = BigDecimal.valueOf(0); for (OrderLine orderLine : orderlines) { total = total.add(orderLine.getOrderLineTotal()); } BigDecimal discount = total.multiply(getDiscount()); total = total.subtract(discount); BigDecimal tax = total.multiply(getVat()); total = total.add(tax); return total; } private BigDecimal getVat() { return (BigDecimal.valueOf(customer.getCountry().getVat())); } private BigDecimal getDiscount() { return BigDecimal.valueOf(0.05); } }
Java
package org.manning.sonarinaction.duplications; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; public class Order { private Customer customer; private List<OrderLine> orderlines = new ArrayList<OrderLine>(); public void addOrderLine(final OrderLine orderLine) { orderlines.add(orderLine); } public void removeOrderLine(final OrderLine orderLine) { orderlines.remove(orderLine); } public Customer getCustomer() { return customer; } public void setCustomer(Customer customer) { this.customer = customer; } public BigDecimal getTotal() { BigDecimal total = BigDecimal.valueOf(0); for (OrderLine orderLine : orderlines) { total = total.add(orderLine.getOrderLineTotal()); } BigDecimal discount = total.multiply(getDiscount()); total = total.subtract(discount); BigDecimal tax = total.multiply(getVat()); total = total.add(tax); return total; } private BigDecimal getVat() { return BigDecimal.valueOf(0.20); } private BigDecimal getDiscount() { return BigDecimal.valueOf(0); } }
Java
package org.manning.sonarinaction.duplications; public class Customer { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
Java
package org.manning.sonarinaction.duplications; public class Country { private String code; private double vat; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public double getVat() { return vat; } public void setVat(double vat) { this.vat = vat; } }
Java
package org.manning.sonarinaction.duplications; import java.math.BigDecimal; public class OrderLine { private String itemDescription; private Long quantity; private BigDecimal price; public String getItemDescription() { return itemDescription; } public void setItemDescription(String itemDescription) { this.itemDescription = itemDescription; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } public Long getQuantity() { return quantity; } public void setQuantity(Long quantity) { this.quantity = quantity; } public BigDecimal getOrderLineTotal(){ return price.multiply(BigDecimal.valueOf(quantity.longValue())); } }
Java
package org.manning.sonarinaction.duplications; public class InternationalCustomer extends Customer { private Country country; public Country getCountry() { return country; } public void setCountry(Country country) { this.country = country; } }
Java
import java.io.FileOutputStream; import java.io.PrintStream; public class Main { String name = null; /** * @param args */ public static void main(String[] args) { String first = "Hello"; String second = null; Examples1 ex1 = new Examples1(); int total = ex1.getLength(first) + ex1.getLength(second); int len = second.length(); } private void writeToFile(String output) throws OutputException { FileOutputStream out; // declare a file output object PrintStream p; // declare a print stream object try { // Create a new file output stream // connected to "myfile.txt" out = new FileOutputStream("myfile.txt"); new PrintStream(out).println(output); } catch (Exception e) { OutputException ex = new OutputException(e.getStackTrace()); ex.setOutput(output); System.err.println("Error writing to file"); throw ex; } } }
Java
package com.jwetherell.pedometer.service; import java.util.ArrayList; import java.util.List; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; /** * This class handles SensorEvents and determines if they are a "step" or not. * * This code is losely based on http://code.google.com/p/pedometer/ * * @author bagilevi <bagilevi@gmail.com> * @author Justin Wetherell <phishman3579@gmail.com> */ public class StepDetector implements SensorEventListener { private static final StepDetector instance = new StepDetector(); private static boolean detecting = false; private static int mLimit = 100; private static float mLastValues[] = new float[3 * 2]; private static float mScale[] = new float[2]; private static float mYOffset = 0; private static float mLastDirections[] = new float[3 * 2]; private static float mLastExtremes[][] = { new float[3 * 2], new float[3 * 2] }; private static float mLastDiff[] = new float[3 * 2]; private static int mLastMatch = -1; private static List<StepListener> mStepListeners = new ArrayList<StepListener>(); static { int h = 480; mYOffset = h * 0.5f; mScale = new float[2]; mScale[0] = -(h * 0.5f * (1.0f / (SensorManager.STANDARD_GRAVITY * 2))); mScale[1] = -(h * 0.5f * (1.0f / (SensorManager.MAGNETIC_FIELD_EARTH_MAX))); } private StepDetector() { } public static StepDetector getInstance() { return instance; } /** * Add a StepListener; * * @param sl * StepListener to add. */ public void addStepListener(StepListener sl) { if (!mStepListeners.contains(sl)) mStepListeners.add(sl); } /** * Remove a StepListener. * * @param sl * StepListener to remove. */ public void removeStepListener(StepListener sl) { if (mStepListeners.contains(sl)) mStepListeners.remove(sl); } /** * Set sensitivity of the StepDector. * * @param sensitivity * Sensitivity of the StepDector. */ public static void setSensitivity(int sensitivity) { mLimit = sensitivity; } /** * {@inheritDoc} */ @Override public void onSensorChanged(SensorEvent event) { if (event == null) throw new NullPointerException(); if (!detecting) detectStep(event); } private void detectStep(SensorEvent event) { if (event == null) throw new NullPointerException(); detecting = true; float vSum = 0; for (int i = 0; i < 3; i++) { final float v = mYOffset + event.values[i] * mScale[0]; vSum += v; } int k = 0; float v = vSum / 3; float direction = (v > mLastValues[k] ? 1 : (v < mLastValues[k] ? -1 : 0)); if (direction == -mLastDirections[k]) { // Direction changed int extType = (direction > 0 ? 0 : 1); // minumum or maximum? mLastExtremes[extType][k] = mLastValues[k]; float diff = Math.abs(mLastExtremes[extType][k] - mLastExtremes[1 - extType][k]); if (diff > mLimit) { boolean isAlmostAsLargeAsPrevious = diff > (mLastDiff[k] * 2 / 3); boolean isPreviousLargeEnough = mLastDiff[k] > (diff / 3); boolean isNotContra = (mLastMatch != 1 - extType); if (isAlmostAsLargeAsPrevious && isPreviousLargeEnough && isNotContra) { for (StepListener stepListener : mStepListeners) { stepListener.onStep(); } mLastMatch = extType; } else { mLastMatch = -1; } } mLastDiff[k] = diff; } mLastDirections[k] = direction; mLastValues[k] = v; detecting = false; } /** * {@inheritDoc} */ @Override public void onAccuracyChanged(Sensor arg0, int arg1) { // Not used } }
Java
package com.jwetherell.pedometer.service; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.logging.Logger; import com.jwetherell.pedometer.R; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.hardware.Sensor; import android.hardware.SensorManager; import android.os.AsyncTask; import android.os.Bundle; import android.os.IBinder; import android.os.PowerManager; import android.os.RemoteException; import android.os.PowerManager.WakeLock; /** * This class extends the Service class. it is in charge of starting and * stopping the power, notification, and sensor managers. It also passes * information received from the sensor to the StepDetector. * * This code is losely based on http://code.google.com/p/pedometer/ * * @author bagilevi <bagilevi@gmail.com> * @author Justin Wetherell <phishman3579@gmail.com> */ public class StepService extends Service implements StepListener { private static final Logger logger = Logger.getLogger(StepService.class.getSimpleName()); private static int NOTIFY = 0x1001; private static AtomicBoolean updating = new AtomicBoolean(false); private static SensorManager sensorManager = null; private static StepDetector stepDetector = null; private static PowerManager powerManager = null; private static WakeLock wakeLock = null; private static NotificationManager notificatioManager = null; private static Notification notification = null; private static Intent passedIntent = null; private static List<IStepServiceCallback> mCallbacks = new ArrayList<IStepServiceCallback>();; private static int mSteps = 0; private static boolean running = false; /** * {@inheritDoc} */ @Override public void onCreate() { super.onCreate(); logger.info("onCreate"); notificatioManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); initNotification(); powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "StepService"); if (!wakeLock.isHeld()) wakeLock.acquire(); if (stepDetector == null) { stepDetector = StepDetector.getInstance(); stepDetector.addStepListener(this); } sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); sensorManager.registerListener(stepDetector, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_GAME); running = true; } /** * {@inheritDoc} */ @Override public void onDestroy() { super.onDestroy(); logger.info("onDestroy"); running = false; mSteps = 0; notificatioManager.cancel(NOTIFY); if (wakeLock.isHeld()) wakeLock.release(); sensorManager.unregisterListener(stepDetector); stopForegroundCompat(NOTIFY); } /** * {@inheritDoc} */ @Override public void onStart(Intent intent, int startId) { super.onStart(intent, startId); logger.info("onStart"); passedIntent = intent; Bundle extras = passedIntent.getExtras(); if (extras != null) { NOTIFY = extras.getInt("int"); } // Work around a bug where notif number has to be > 0 updateNotification((mSteps > 0) ? mSteps : 1); startForegroundCompat(NOTIFY, notification); } /** * This is a wrapper around the new startForeground method, using the older * APIs if it is not available. * * @param id * Integer representing the service to start. * @param notif * Notification to display when service is running. */ public void startForegroundCompat(int id, Notification notif) { Method mStartForeground = null; try { mStartForeground = getClass().getMethod("startForeground", new Class[] { int.class, Notification.class }); } catch (Exception e) { // Should happen in Android OS < 2.0 } // If we have the new startForeground API, then use it. if (mStartForeground != null) { try { mStartForeground.invoke(this, id, notif); } catch (Exception e) { // Should not happen. } return; } // Fall back on the old API. setForeground(true); notificatioManager.notify(id, notif); } /** * This is a wrapper around the new stopForeground method, using the older * APIs if it is not available. * * @param id * Integer of the service to stop. */ public void stopForegroundCompat(int id) { Method mStopForeground = null; try { mStopForeground = getClass().getMethod("stopForeground", new Class[] { boolean.class }); } catch (Exception e) { // Should happen in Android OS < 2.0 } // If we have the new stopForeground API, then use it. if (mStopForeground != null) { try { mStopForeground.invoke(this, true); } catch (Exception e) { // Should not happen. } return; } // Fall back on the old API. Note to cancel BEFORE changing the // foreground state, since we could be killed at that point. notificatioManager.cancel(id); setForeground(false); } private void initNotification() { notification = new Notification(R.drawable.icon, "Pedometer started.", System.currentTimeMillis()); notification.flags = Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT; } private void updateNotification(int steps) { if (!updating.compareAndSet(false, true)) return; notification.number = steps; notification.when = System.currentTimeMillis(); PendingIntent contentIntent = PendingIntent.getActivity(this, 0, passedIntent, 0); notification.setLatestEventInfo(this, getText(R.string.app_name), "Total steps: " + steps, contentIntent); notificatioManager.notify(NOTIFY, notification); updating.set(false); } /** * {@inheritDoc} */ @Override public void onStep() { logger.info("onStep()"); mSteps++; if (!updating.get()) { UpdateNotificationAsyncTask update = new UpdateNotificationAsyncTask(); update.doInBackground(mSteps); } if (mCallbacks != null) { List<IStepServiceCallback> callbacksToRemove = null; for (IStepServiceCallback mCallback : mCallbacks) { try { mCallback.stepsChanged(mSteps); } catch (RemoteException e) { // Remove old callbacks if they failed to unbind callbacksToRemove = new ArrayList<IStepServiceCallback>(); callbacksToRemove.add(mCallback); e.printStackTrace(); } } if (callbacksToRemove != null) { for (IStepServiceCallback mCallback : callbacksToRemove) { mCallbacks.remove(mCallback); } } } } private class UpdateNotificationAsyncTask extends AsyncTask<Integer, Integer, Boolean> { /** * {@inheritDoc} */ @Override protected Boolean doInBackground(Integer... params) { updateNotification(params[0]); return true; } } private final IStepService.Stub mBinder = new IStepService.Stub() { /** * {@inheritDoc} */ @Override public boolean isRunning() throws RemoteException { return running; } /** * {@inheritDoc} */ @Override public void setSensitivity(int sens) throws RemoteException { logger.info("setSensitivity: " + sens); StepDetector.setSensitivity(sens); } /** * {@inheritDoc} */ @Override public void registerCallback(IStepServiceCallback cb) throws RemoteException { if (cb == null) return; logger.info("registerCallback: " + cb.toString()); cb.stepsChanged(mSteps); if (!mCallbacks.contains(cb)) mCallbacks.add(cb); } /** * {@inheritDoc} */ @Override public void unregisterCallback(IStepServiceCallback cb) throws RemoteException { if (cb == null) return; logger.info("unregisterCallback: " + cb.toString()); if (mCallbacks.contains(cb)) mCallbacks.remove(cb); } }; /** * {@inheritDoc} */ @Override public IBinder onBind(Intent intent) { logger.info("onBind()"); return mBinder; } }
Java
package com.jwetherell.pedometer.service; /** * This interface provides a callback mechanism for the StepDetector. * * This code is losely based on http://code.google.com/p/pedometer/ * * @author bagilevi <bagilevi@gmail.com> * @author Justin Wetherell <phishman3579@gmail.com> */ public interface StepListener { /** * Called when the StepDetector detects a step. Based on the sensitivity * setting. */ public void onStep(); }
Java
package com.jwetherell.pedometer.utilities; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.content.Context; import android.content.DialogInterface; /** * This abstract class provides static methods to display messages. * * @author Justin Wetherell <phishman3579@gmail.com> */ public abstract class MessageUtilities { /** Enum representing the confirmation result */ public static enum ConfirmationResult { YES, NO }; /** * Show confirmation box using AlertDialog. * * @param context * Context to show the alert. * @param msg * String to show in the alert. * @param yesClick * OnClickListener to execute on a YES click. * @param noClick * OnClickListener to execute on a NO click. * @throws NullPointerException * if context or msg are NULL. */ public static void confirmUser(Context context, String msg, DialogInterface.OnClickListener yesClick, DialogInterface.OnClickListener noClick) { if (context == null || msg == null) throw new NullPointerException(); Builder alert = new AlertDialog.Builder(context); alert.setIcon(android.R.drawable.ic_dialog_alert).setTitle("Confirmation").setMessage(msg).setPositiveButton("Yes", yesClick) .setNegativeButton("No", noClick).show(); } }
Java
package com.jwetherell.pedometer.activity; import java.util.ArrayList; import java.util.Arrays; import java.util.logging.Logger; import com.jwetherell.pedometer.service.IStepService; import com.jwetherell.pedometer.service.IStepServiceCallback; import com.jwetherell.pedometer.service.StepDetector; import com.jwetherell.pedometer.service.StepService; import com.jwetherell.pedometer.utilities.MessageUtilities; import com.jwetherell.pedometer.R; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.ServiceConnection; import android.content.res.Configuration; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.PowerManager; import android.os.PowerManager.WakeLock; import android.os.RemoteException; import android.view.KeyEvent; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.CompoundButton; import android.widget.Spinner; import android.widget.TextView; import android.widget.ToggleButton; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.CompoundButton.OnCheckedChangeListener; /** * This class extends Activity to handle starting and stopping the pedometer * service and displaying the steps. * * @author Justin Wetherell <phishman3579@gmail.com> */ public class Demo extends Activity { private static final Logger logger = Logger.getLogger(Demo.class.getSimpleName()); private static ToggleButton startStopButton = null; private static ArrayList<String> sensArrayList = null; private static ArrayAdapter<CharSequence> modesAdapter = null; private static TextView text = null; private static PowerManager powerManager = null; private static WakeLock wakeLock = null; public static IStepService mService = null; public static Intent stepServiceIntent = null; private static int sensitivity = 100; /** * {@inheritDoc} */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Demo"); if (stepServiceIntent == null) { Bundle extras = new Bundle(); extras.putInt("int", 1); stepServiceIntent = new Intent(Demo.this, StepService.class); stepServiceIntent.putExtras(extras); } startStopButton = (ToggleButton) this.findViewById(R.id.StartStopButton); startStopButton.setOnCheckedChangeListener(startStopListener); String sensStr = String.valueOf(sensitivity); int idx = 0; if (sensArrayList == null) { String[] sensArray = getResources().getStringArray(R.array.sensitivity); sensArrayList = new ArrayList<String>(Arrays.asList(sensArray)); } if (sensArrayList.contains(sensStr)) { idx = sensArrayList.indexOf(sensStr); } Spinner sensSpinner = (Spinner) findViewById(R.id.input_sensitivity_spinner); modesAdapter = ArrayAdapter.createFromResource(this, R.array.sensitivity, android.R.layout.simple_spinner_item); modesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); sensSpinner.setOnItemSelectedListener(sensListener); sensSpinner.setAdapter(modesAdapter); sensSpinner.setSelection(idx); text = (TextView) this.findViewById(R.id.text); } /** * {@inheritDoc} */ @Override public void onStart() { super.onStart(); if (!wakeLock.isHeld()) wakeLock.acquire(); // Bind without starting the service try { bindService(stepServiceIntent, mConnection, 0); } catch (Exception e) { e.printStackTrace(); } } /** * {@inheritDoc} */ @Override public void onPause() { super.onPause(); if (wakeLock.isHeld()) wakeLock.release(); unbindStepService(); } private OnItemSelectedListener sensListener = new OnItemSelectedListener() { /** * {@inheritDoc} */ @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { CharSequence seq = modesAdapter.getItem(arg2); String sensString = String.valueOf(seq); if (sensString != null) { sensitivity = Integer.parseInt(sensString); StepDetector.setSensitivity(sensitivity); } } /** * {@inheritDoc} */ @Override public void onNothingSelected(AdapterView<?> arg0) { // Ignore } }; /** * {@inheritDoc} */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { try { if (mService != null && mService.isRunning()) { MessageUtilities.confirmUser(Demo.this, "Exit App without stopping pedometer?", yesExitClick, null); } else { stop(); finish(); } } catch (RemoteException e) { e.printStackTrace(); return false; } return true; } return super.onKeyDown(keyCode, event); } /** * {@inheritDoc} */ @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); } private OnCheckedChangeListener startStopListener = new OnCheckedChangeListener() { /** * {@inheritDoc} */ @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { boolean serviceIsRunning = false; try { if (mService != null) serviceIsRunning = mService.isRunning(); } catch (RemoteException e) { e.printStackTrace(); } if (isChecked && !serviceIsRunning) { start(); } else if (!isChecked && serviceIsRunning) { MessageUtilities.confirmUser(Demo.this, "Stop the pedometer?", yesStopClick, noStopClick); } } }; private DialogInterface.OnClickListener yesStopClick = new DialogInterface.OnClickListener() { /** * {@inheritDoc} */ @Override public void onClick(DialogInterface dialog, int which) { stop(); } }; private static final DialogInterface.OnClickListener noStopClick = new DialogInterface.OnClickListener() { /** * {@inheritDoc} */ @Override public void onClick(DialogInterface dialog, int which) { if (mService != null) try { startStopButton.setChecked(mService.isRunning()); } catch (RemoteException e) { e.printStackTrace(); } } }; private DialogInterface.OnClickListener yesExitClick = new DialogInterface.OnClickListener() { /** * {@inheritDoc} */ @Override public void onClick(DialogInterface dialog, int which) { unbindStepService(); finish(); } }; private void start() { logger.info("start"); startStepService(); bindStepService(); } private void stop() { logger.info("stop"); unbindStepService(); stopStepService(); } private void startStepService() { try { startService(stepServiceIntent); } catch (Exception e) { e.printStackTrace(); } } private void stopStepService() { try { stopService(stepServiceIntent); } catch (Exception e) { // Ignore } } private void bindStepService() { try { bindService(stepServiceIntent, mConnection, Context.BIND_AUTO_CREATE); } catch (Exception e) { e.printStackTrace(); } } private void unbindStepService() { try { unbindService(mConnection); } catch (Exception e) { // Ignore } } private static final Handler handler = new Handler() { public void handleMessage(Message msg) { int current = msg.arg1; text.setText("Steps = " + current); } }; private static final IStepServiceCallback.Stub mCallback = new IStepServiceCallback.Stub() { @Override public IBinder asBinder() { return mCallback; } @Override public void stepsChanged(int value) throws RemoteException { logger.info("Steps=" + value); Message msg = handler.obtainMessage(); msg.arg1 = value; handler.sendMessage(msg); } }; private static final ServiceConnection mConnection = new ServiceConnection() { /** * {@inheritDoc} */ @Override public void onServiceConnected(ComponentName className, IBinder service) { logger.info("onServiceConnected()"); mService = IStepService.Stub.asInterface(service); try { mService.registerCallback(mCallback); mService.setSensitivity(sensitivity); startStopButton.setChecked(mService.isRunning()); } catch (RemoteException e) { e.printStackTrace(); } } /** * {@inheritDoc} */ @Override public void onServiceDisconnected(ComponentName className) { logger.info("onServiceDisconnected()"); try { startStopButton.setChecked(mService.isRunning()); } catch (RemoteException e) { e.printStackTrace(); } mService = null; } }; }
Java
/** Automatically generated file. DO NOT MODIFY */ package org.abrysov.annoyingkids; public final class BuildConfig { public final static boolean DEBUG = true; }
Java
package org.abrysov.annoyingkids; import android.media.AudioManager; import android.media.SoundPool; import android.media.SoundPool.OnLoadCompleteListener; import android.os.Bundle; import android.app.Activity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.FrameLayout; import android.widget.MediaController; import android.support.v4.app.NavUtils; public class MainActivity extends Activity implements OnClickListener{ private SoundPool mSoundPool = null; private int mScream01; private int mScream02; private int mScream03; private int mScream04; boolean loaded = false; int num=0; private FrameLayout mKid01 = null; private FrameLayout mKid02 = null; private FrameLayout mKid03 = null; private FrameLayout mKid04 = null; private boolean mKidCrying01 = false; private boolean mKidCrying02 = false; private boolean mKidCrying03 = false; private boolean mKidCrying04 = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //link our volume butt with the app this.setVolumeControlStream(AudioManager.STREAM_MUSIC); mSoundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0); //устанавливаем call-back функцию, которая вызывается по //завершению загрузки файла в память mSoundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() { public void onLoadComplete(SoundPool soundPool, int sampleId, int status) { loaded = true; Log.e("Test", "sampleId=" + sampleId + " status=" + status); } }); // load screams )) mScream01 = mSoundPool.load(this, R.raw.girl_in_medic_room_01 , 1); mScream02 = mSoundPool.load(this, R.raw.girl_in_kidroom_02 , 1); mScream03 = mSoundPool.load(this, R.raw.scream_03_1 , 1); mScream04 = mSoundPool.load(this, R.raw.scream_04_1 , 1); mKid01 = (FrameLayout)findViewById(R.id.main_fl_kid_01); mKid01.setOnClickListener(this); mKid02 = (FrameLayout)findViewById(R.id.main_fl_kid_02); mKid02.setOnClickListener(this); mKid03 = (FrameLayout)findViewById(R.id.main_fl_kid_03); mKid03.setOnClickListener(this); mKid04 = (FrameLayout)findViewById(R.id.main_fl_kid_04); mKid04.setOnClickListener(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_main, menu); return true; } private void scream(int _scream){ AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE); float actualVolume = (float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC); float maxVolume = (float) audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC); float volume = actualVolume / maxVolume; if (loaded) { mSoundPool.play(_scream, volume, volume, 1, 0, 1f); } } public void onClick(View v) { switch (v.getId()) { case R.id.main_fl_kid_01: mKidCrying01 = !mKidCrying01; if(mKidCrying01){ mKid01.setBackgroundResource(R.drawable.bg_cryingkid); scream(mScream01); }else{ mKid01.setBackgroundResource(R.drawable.bg_kid); mSoundPool.stop(mScream01); } break; case R.id.main_fl_kid_02: mKidCrying02 = !mKidCrying02; if(mKidCrying02){ mKid02.setBackgroundResource(R.drawable.bg_cryingkid); scream(mScream02); }else{ mKid02.setBackgroundResource(R.drawable.bg_kid); } break; case R.id.main_fl_kid_03: mKidCrying03 = !mKidCrying03; if(mKidCrying03){ mKid03.setBackgroundResource(R.drawable.bg_cryingkid); scream(mScream03); }else{ mKid03.setBackgroundResource(R.drawable.bg_kid); } break; case R.id.main_fl_kid_04: mKidCrying04 = !mKidCrying04; if(mKidCrying04){ mKid04.setBackgroundResource(R.drawable.bg_cryingkid); scream(mScream04); }else{ mKid04.setBackgroundResource(R.drawable.bg_kid); } break; default: break; } } }
Java
/* * MAI - Multi-document Adjudication Interface * * Copyright Amber Stubbs (astubbs@cs.brandeis.edu) * Department of Computer Science, Brandeis University * * MAI 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 mai; import java.io.*; import java.util.*; import java.util.regex.Pattern; import java.util.regex.Matcher; /** * Provides methods for loading a DTD file into a DTD class * * @author Amber Stubbs * * @see DTD */ class DTDLoader { private DTD dtd; DTDLoader(File f){ dtd=new DTD(); try{ readFile(f); }catch(Exception e){ System.out.println("no file found"); } } public DTD getDTD(){ return dtd; } private void readFile(File f) throws Exception{ Scanner sc = new Scanner(f,"UTF-8"); while (sc.hasNextLine()) { String next = sc.nextLine(); //first, get rid of comments //this assumes that comments are on their own line(s) //needs to be made more flexible if (next.contains("<!--")){ while (next.contains("-->")==false){ next = sc.nextLine(); } //this skips the lines with the comments next= sc.nextLine(); } //then, get all information about a tag into one string String tag = ""; if (next.contains("<")){ tag = tag+next; while (next.contains(">")==false){ next = sc.nextLine(); tag = tag+next; } } tag = tag.replaceAll(" +"," "); process(tag); } } private void process(String tag){ if(tag.startsWith("<!ELEMENT")){ createElement(tag); } if(tag.startsWith("<!ATTLIST")){ addAttribute(tag); } if(tag.startsWith("<!ENTITY")){ addMeta(tag); } } /** * Create a new element in the DTD */ private void createElement(String tag){ String name = tag.split(" ")[1]; if (tag.contains("#PCDATA")){ String idString = getIDString(name); ElemExtent e = new ElemExtent(name, idString); dtd.addElem(e); } else{ String idString = getIDString(name); ElemLink e = new ElemLink(name, idString); dtd.addElem(e); } } private String getIDString(String name){ ArrayList<String> ids = dtd.getElementIDs(); String id = name.substring(0,1); boolean idOK = false; while (idOK == false){ if(ids.contains(id)){ if(id.length()>=name.length()){ id = id+"-"; } else{ id = name.substring(0,id.length()+1); } } else{ idOK=true; } } return id; } private void addMeta(String tag){ if (tag.contains("name ")){ String name= tag.split("name \"")[1]; name = name.split("\"")[0]; dtd.setName(name); } } /** * Add an attribute to an existing string */ private void addAttribute(String tag){ if (tag.contains("(")){ addListAtt(tag); } else{ addDataAtt(tag); } } /** * Creates an AttList object for the DTD * @param tag */ private void addListAtt(String tag){ String elemName = tag.split(" ")[1]; String attName = tag.split(" ")[2]; Elem elem = dtd.getElem(elemName); if(elem!=null){ String listString = tag.split("\\(")[1]; listString = listString.split("\\)")[0]; ArrayList<String> atts = new ArrayList<String>(); String[]list = listString.split("\\|"); for(int i=0;i<list.length;i++){ atts.add(list[i].trim()); } Pattern defaultVal = Pattern.compile("\"[\\w ]+\" *>"); Matcher matcher = defaultVal.matcher(tag); ArrayList<String> defVals = new ArrayList<String>(); String defaultValue = ""; while (matcher.find()){ defVals.add(matcher.group()); } if (defVals.size()>1){ System.out.println("Error in attribute; too many default values found"); System.out.println(tag); } else if (defVals.size()==1){ defaultValue = defVals.get(0).split("\"")[1]; if (!atts.contains(defaultValue)){ System.out.println("Error -- default value not in attribute list"); System.out.println(tag); defaultValue=""; } } boolean req = tag.contains("#REQUIRED"); elem.addAttribute(new AttList(attName,req,atts,defaultValue)); } else{ System.out.println("no match found: '" + elemName + "' is not a valid tag identifier"); } } /** * Creates an AttData object for the DTD * @param tag */ private void addDataAtt(String tag){ String elemName = tag.split(" ")[1]; String attName = tag.split(" ")[2]; boolean req = tag.contains("#REQUIRED"); if(dtd.hasElem(elemName)){ Elem elem = dtd.getElem(elemName); if(attName.equalsIgnoreCase("start")){ if(elem instanceof ElemExtent){ Attrib att = elem.getAttribute("start"); att.setRequired(req); att = elem.getAttribute("end"); att.setRequired(req); } } else if(tag.contains(" ID ")){ AttID att = (AttID)elem.getAttribute("id"); if(tag.contains("prefix")){ String prefix = tag.split("\"")[1]; att.setPrefix(prefix); } } else{ Pattern defaultVal = Pattern.compile("\"[\\w ]+\" *>"); Matcher matcher = defaultVal.matcher(tag); ArrayList<String> defVals = new ArrayList<String>(); String defaultValue = ""; while (matcher.find()){ defVals.add(matcher.group()); } if (defVals.size()>1){ System.out.println("Error in attribute; too many default values found"); System.out.println(tag); } else if (defVals.size()==1){ defaultValue = defVals.get(0).split("\"")[1]; } elem.addAttribute(new AttData(attName,req,defaultValue)); } } else{ System.out.println("no match found"); } } }
Java
/* * MAI - Multi-document Adjudication Interface * * Copyright Amber Stubbs (astubbs@cs.brandeis.edu) * Department of Computer Science, Brandeis University * * MAI 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 mai; import java.io.*; import java.util.*; import org.xml.sax.*; import org.xml.sax.helpers.*; /** * XMLFileLoader reads in any annotated files that are loaded into MAE by * calling the XMLHandler file. * * @author Amber Stubbs * */ class XMLFileLoader{ private XMLHandler xmlfile; XMLFileLoader(File f){ xmlfile = new XMLHandler(); try{ readFile(f); }catch(Exception e){ System.out.println(e.toString()); } } private void readFile(File f) throws Exception{ try { //this will work with java 5 and 6. Java 1.4 is not supported. XMLReader parser = XMLReaderFactory.createXMLReader(); parser.setContentHandler(xmlfile); String docname = f.toString(); try{ parser.parse(docname); }catch(Exception ex){ System.out.println(ex.toString()); System.out.println("parse of " + docname + " failed"); throw new Exception(); } }catch (SAXException e) { System.out.println("e.toString()"); } } public HashCollection<String,Hashtable<String,String>> getTagHash(){ return xmlfile.returnTagHash(); } public String getTextChars(){ return xmlfile.getTextChars(); } }
Java
/* * MAI - Multi-document Adjudication Interface * * Copyright Amber Stubbs (astubbs@cs.brandeis.edu) * Department of Computer Science, Brandeis University * * MAI 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 mai; import javax.swing.table.DefaultTableModel; /** * * AnnTableModel creates a TableModel that * allows the ID column to be uneditable. This * helps prevent user-created database conflicts by * ensuring the IDs being generated will not be changed, * and makes it so that users can double-click on the * ID in order to see where that tag appears in the text. * * @author Amber Stubbs */ class AnnTableModel extends DefaultTableModel{ private static final long serialVersionUID = -3921141969882892250L; //generated by Eclipse private String goldStandardName; /** * Returns true or false depending on whether * the cell is editable or not. Currently the * only cells that are editable are cells for * tags in the Gold Standard that don't * contain the file name (keeping the first * column uneditable enables it to be double-clicked * so extents can be highlighted). */ public boolean isCellEditable(int row, int col){ String val = (String)getValueAt(row,0); if (col == 0){ return false; } if (val.equals(goldStandardName)){ return true; } else if (col == getColumnCount()-1){ return true; } else return false; } public void setGoldStandardName(String gs){ goldStandardName = gs; } public String getGoldStandardName(){ return goldStandardName; } }
Java
/* * MAI - Multi-document Adjudication Interface * * Copyright Amber Stubbs (astubbs@cs.brandeis.edu) * Department of Computer Science, Brandeis University * * MAI 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 mai; import java.util.*; class AttList extends Attrib{ /** * Used for tag attributes that provide a list of options * * @author Amber Stubbs */ AttList(){ } AttList (String name, boolean r, ArrayList<String> c, String d){ setName(name); setRequired(r); setList(c); setDefaultValue(d); } public ArrayList<String> getList(){ return list; } public void setList(ArrayList<String> l){ list=l; } public String toString(){ return("Attribute name =" + getName() + " , required = " + getRequired() + "also list" ); } private ArrayList<String> list; }
Java
/* * MAI - Multi-document Adjudication Interface * * Copyright Amber Stubbs (astubbs@cs.brandeis.edu) * Department of Computer Science, Brandeis University * * MAI 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 mai; import java.sql.*; import java.util.ArrayList; import java.util.Hashtable; import java.util.Collections; import java.util.Enumeration; /** * AdjudDB is the class that handles all the calls to the * SQLite database. AdjudDB in MAI has the following tables: * 1) extents, with columns: location int(5), element_name, id * 2) links, with columns: id,fromid,from_name,toid,to_name,element_name * 3) one table for each tag in the DTD, where information about each * tag in every file that's loaded is stored * * @author Amber Stubbs * */ class AdjudDB { private PreparedStatement extent_insert; private PreparedStatement link_insert; private PreparedStatement overlap_insert; private Connection conn; private Hashtable<String,PreparedStatement> insertSents; private ArrayList<String> currentLinks; //used to keep track of what links are being displayed private HashCollection<String,String>currentHighlights; //used to keep track of highlights /** * Creates all the tables, HashTables, PreparedStatements, and the connection * to the database. */ AdjudDB(){ try{ currentLinks = new ArrayList<String>(); currentHighlights = new HashCollection<String,String>(); insertSents = new Hashtable<String,PreparedStatement>(); Class.forName("org.sqlite.JDBC"); conn = DriverManager.getConnection("jdbc:sqlite:adjud.db"); Statement stat = conn.createStatement(); stat.executeUpdate("drop table if exists extents;"); stat.executeUpdate("create table extents (file_name, location int(5), element_name, id);"); stat.executeUpdate("drop table if exists links;"); stat.executeUpdate("create table links (file_name, id,fromid,from_name,toid,to_name,element_name);"); stat.executeUpdate("drop table if exists extent_overlaps"); stat.executeUpdate("create table extent_overlaps (gsid, element_name, file_name, fileid);"); extent_insert = conn.prepareStatement("insert into extents values (?, ?, ?, ?);"); link_insert = conn.prepareStatement("insert into links values (?, ?, ?, ?, ?, ?, ?);"); overlap_insert = conn.prepareStatement("insert into extent_overlaps values (?, ?, ?, ?);"); }catch(Exception e){ System.out.println(e.toString()); } } /** * Adds a table to the DB for every link in the DTD * There will be a problem if any of those tags/tables is named * "extent", "link", or "extent_overlap" * * @param dtd The DTD object that was loaded into MAI */ void addDTD(DTD dtd){ ArrayList<Elem> elems = dtd.getElements(); for (int i=0;i<elems.size();i++){ try{ addTableToDB(elems.get(i)); }catch(Exception ex){ System.out.println(ex); } } } /** * Creates the table and a PreparedStatement for the table; * PreparedStatements go in the insertSents hashtable for use later. * * @param elem the Elem object being turned into a table * @throws Exception */ private void addTableToDB(Elem elem) throws Exception{ String name = elem.getName(); Statement stat = conn.createStatement(); stat.executeUpdate("drop table if exists "+name+";"); ArrayList<Attrib> atts = elem.getAttributes(); String statement = ("create table "+name+" (file_name, "); String prep_insert = ("insert into "+name+" values (?, "); for(int i=0;i<atts.size();i++){ if(i==atts.size()-1){ statement = statement + atts.get(i).getName() +");"; prep_insert = prep_insert + "?);"; } else{ statement = statement + atts.get(i).getName() +", "; prep_insert = prep_insert + "?, "; } } stat.executeUpdate(statement); PreparedStatement st = conn.prepareStatement(prep_insert); insertSents.put(name, st); } /** * Sends the command that all the tag-specific tables in the * database have their PreparedStatements inserted into the table * * @param dtd the DTD containing all the tag names used to * create the tables * * @throws Exception */ private void batchAll(DTD dtd) throws Exception{ ArrayList<Elem> elements = dtd.getElements(); for (int i=0;i<elements.size();i++){ String name = elements.get(i).getName(); PreparedStatement ps = insertSents.get(name); conn.setAutoCommit(false); ps.executeBatch(); conn.setAutoCommit(true); } } /** * Inserts the PreparedStatements for a single table * * @param e the Elem object describing the table being * updated * * @throws Exception */ void batchElement(Elem e) throws Exception{ PreparedStatement ps = insertSents.get(e.getName()); conn.setAutoCommit(false); ps.executeBatch(); conn.setAutoCommit(true); } /** * When a file is loaded into MAI the tags are turned into a HashCollection * and sent here to be loaded into the database tables. * * @param fullName the name of the file being added * @param dtd the DTD describing the tags in the file * @param newTags the HashCollection containing all the tags being added */ void addTagsFromHash(String fullName, DTD dtd, HashCollection<String,Hashtable<String,String>> newTags){ //for each tag in the DTD, get the ArrayList of Hashtables associated with it ArrayList<Elem> elements = dtd.getElements(); for (int i=0;i<elements.size();i++){ String name = elements.get(i).getName(); Elem elem = dtd.getElem(name); ArrayList<Hashtable<String,String>> tagList = newTags.getList(name); //for each set of tags in the ArrayList, add the tags to the DB //extent tags first if(tagList!=null){ if (elem instanceof ElemExtent){ for(int j=0;j<tagList.size();j++){ //first, add the extent tags with the PreparedStatement for that table Hashtable<String,String> tag = tagList.get(j); usePreparedExtentStatements(fullName,elem,tag); } } } } try{ batchExtents(); batchAll(dtd); }catch(Exception e){ System.out.println(e.toString()); System.out.println("error adding extent tags"); } for (int i=0;i<elements.size();i++){ String name = elements.get(i).getName(); Elem elem = dtd.getElem(name); ArrayList<Hashtable<String,String>> tagList = newTags.getList(name); if(tagList!=null){ if (elem instanceof ElemLink && tagList != null){ for(int j=0;j<tagList.size();j++){ //next, add the links tags with the PreparedStatement for that table Hashtable<String,String> tag = tagList.get(j); usePreparedLinkStatements(fullName,elem,tag); } } } } try{ batchLinks(); batchAll(dtd); }catch(Exception e){ System.out.println(e.toString()); System.out.println("error adding link tags"); } } /** * Uses the previously created PreparedStatements * to enter extent tag information into the database * * @param fullName name of the file being added * @param elem the Elem object describing the tag being added * @param tag the Hashtable containing the tag information */ void usePreparedExtentStatements(String fullName, Elem elem, Hashtable<String,String> tag){ //get PreparedStatement from Hashtable PreparedStatement ps = insertSents.get(elem.getName()); ArrayList<Attrib> atts = elem.getAttributes(); try{ ps.setString(1,fullName);} catch(Exception e){ System.out.println(e.toString()); System.out.println("error adding name"); } //add the tag information to the preparedStatement for(int i=0;i<atts.size();i++){ try{ ps.setString(i+2,tag.get(atts.get(i).getName())); }catch(Exception e){ System.out.println(e.toString()); System.out.println("error setting String for "+tag.get(atts.get(i).getName())); } } try{ //add the set strings to the preparedstatement's batch ps.addBatch(); }catch(Exception e){ System.out.println(e.toString()); System.out.println("error adding extent batch"); } //now, add the tag information to the extent table String startString = tag.get("start"); String endString = tag.get("end"); int start = Integer.valueOf(startString); int end = Integer.valueOf(endString); //if the tag is associated with a span in the text, use this if(start>-1){ for(int i=start;i<end;i++){ try{ add_extent(fullName,i,elem.getName(),tag.get("id")); }catch(Exception e){ System.out.println(e.toString()); System.out.println("error adding extent"); } } } //otherwise (if it's a non-consuming tag), use this else{ try{ add_extent(fullName,-1,elem.getName(),tag.get("id")); }catch(Exception e){ System.out.println(e.toString()); System.out.println("error adding -1 extent"); } } } /** * Uses the previously created PreparedStatements * to enter extent tag information into the database * * @param fullName name of the file being added * @param elem the Elem object describing the tag being added * @param tag the Hashtable containing the tag information */ void usePreparedLinkStatements(String fullName, Elem elem, Hashtable<String,String> tag){ //get PreparedStatement from Hashtable try{ PreparedStatement ps = insertSents.get(elem.getName()); ArrayList<Attrib> atts = elem.getAttributes(); ps.setString(1,fullName); for(int i=0;i<atts.size();i++){ String test = tag.get(atts.get(i).getName()); if (test!=null){ ps.setString(i+2,test); } else{ ps.setString(i+2,""); } } try{ ps.addBatch(); }catch(Exception e){ System.out.println(e.toString()); System.out.println("error adding link batch"); } //add the tag information to the link table String from_id = tag.get("fromID"); String to_id = tag.get("toID"); String from_type = getElementByFileAndID(fullName,from_id); String to_type = getElementByFileAndID(fullName,to_id); try{ add_link(fullName,tag.get("id"),elem.getName(), from_id, from_type,to_id,to_type); }catch(Exception e){ System.out.println(e.toString()); System.out.println("error adding link to link table"); } } catch(Exception e){ System.out.println(e.toString()); System.out.println("error adding link: "+ "filename = "+fullName+ "\ntag id = "+tag.get("id")); } } //returns all the tag information based on file name and id /** * Returns a hashtable of tag information based on the id, * tag name, and filename of the tag * * @param tagname the name of the tag in the DTD * @param id the ID being searched for * @param filename the name of the file the tag is in * @param atts the list of attributes whose values will be put * in the Hashtable. * * @return a Hashtable containing the attribute names and their * values for the tag being searched for. * * @throws Exception */ Hashtable<String,String>getTagsByFileAndID(String tagname, String id, String filename,ArrayList<Attrib> atts) throws Exception{ Statement stat = conn.createStatement(); String query = ("select * from "+ tagname + " where id = '" + id + "' and file_name = '"+ filename+"';"); ResultSet rs = stat.executeQuery(query); Hashtable<String,String> ht = new Hashtable<String,String>(); while(rs.next()){ //for each attribute in the list, get the value and put both in the //hashtable ht for(int i=0;i<atts.size();i++){ ht.put(atts.get(i).getName(),rs.getString(atts.get(i).getName())); } } rs.close(); return ht; } /** * Gets the names of files that have a tag of a particular type * at a specified location. * * @param elem the name of the tag being searched for * @param loc the location being searched for * @return ArrayList of file names that have that tag type at that location * * @throws Exception */ ArrayList<String>getFilesAtLocbyElement(String elem, int loc) throws Exception{ Statement stat = conn.createStatement(); String query = ("select * from extents where location = " + loc + " and element_name ='" + elem +"';"); ResultSet rs = stat.executeQuery(query); ArrayList<String> files = new ArrayList<String>(); while(rs.next()){ files.add(rs.getString("file_name")); } rs.close(); return files; } /** * Returns an ArrayList of extent tags that exist in a particular file * and are of the type specified by the Elem object. * ArrayList contains the tags in String form that are used for writing out * the XML files. * * @param file the name of the file the tag is in * @param elem Elem object defining the type of tag being searched for * @returnArrayList of extent tags that exist in a particular file * and are of the type specified by the Elem object. * * @throws Exception */ ArrayList<String> getExtentTagsByFileAndType(String file, Elem elem) throws Exception{ Statement stat = conn.createStatement(); String query = ("select * from "+elem.getName()+ " where file_name = '" + file + "' order by start;"); ResultSet rs = stat.executeQuery(query); ArrayList<String> tags = makeTagStringsForOutput(rs, elem); rs.close(); return tags; } /** * Returns an ArrayList of link tags that exist in a particular file * and are of the type specified by the Elem object. * ArrayList contains the tags in String form that are used for writing out * the XML files. * * @param file the name of the file the tag is in * @param elem Elem object defining the type of tag being searched for * @returnArrayList of extent tags that exist in a particular file * and are of the type specified by the Elem object. * * @throws Exception */ ArrayList<String> getLinkTagsByFileAndType(String file, Elem elem) throws Exception{ Statement stat = conn.createStatement(); String query = ("select * from "+elem.getName()+ " where file_name = '" + file + "' order by id;"); ResultSet rs = stat.executeQuery(query); ArrayList<String> tags = makeTagStringsForOutput(rs, elem); rs.close(); return tags; } /** * Creates strings containing the tag information being searched for * * * @param rs the ResultSet of a different method (getLinkTagsByFileAndType or * (getExtentTagsByFileAndType) * * @param elem the Elem object describing the tags being retrieved * * @return an ArrayList of Strings containing the tag information */ private ArrayList<String>makeTagStringsForOutput(ResultSet rs, Elem elem){ ArrayList<String> tags = new ArrayList<String>(); ArrayList<Attrib> atts= elem.getAttributes(); try{ while(rs.next()){ String tag = ("<"+elem.getName()+ " "); for(int i=0;i<atts.size();i++){ String attName = atts.get(i).getName(); String attText = rs.getString(attName); //need to get rid of all the information that's //not valid in XML attText=attText.replace("\n"," "); attText=attText.replace("<","&lt;"); attText=attText.replace(">","&gt;"); attText=attText.replace("&","&amp;"); attText=attText.replace("\"","'"); tag = tag+attName+"=\""+attText+"\" "; } tag = tag + "/>\n"; tags.add(tag); } rs.close(); }catch(Exception e){ System.out.println(e); } return tags; } /** * Retrieves a Hashtable of all the locations in a file where tags exist. * Used when assigning colors to the text when a link is selected * * @param filename the name of the file the tags are coming from * @return Hashtable with the locations of tags as keys * @throws Exception */ Hashtable<String,String>getAllExtentsByFile(String filename) throws Exception{ Statement stat = conn.createStatement(); String query = ("select location from extents where file_name = '"+ filename+"';"); ResultSet rs = stat.executeQuery(query); Hashtable<String,String> allLocs = new Hashtable<String,String>(); while(rs.next()){ allLocs.put(rs.getString("location"),""); } rs.close(); return allLocs; } /** * Returns a HashCollection of locations (as keys) and the file names that have * a particular type of tag at each location. * * @param tagname * @return * @throws Exception */ HashCollection<String,String>getExtentAllLocs(String tagname) throws Exception{ HashCollection<String,String>elems = new HashCollection<String,String>(); Statement stat = conn.createStatement(); String query = ("select location, file_name from extents where " + "element_name = '" + tagname + "';"); ResultSet rs = stat.executeQuery(query); while(rs.next()){ elems.putEnt(rs.getString("location"),rs.getString("file_name")); } rs.close(); return elems; } /** * Gets the type of a tag based on its file and ID. Assumes * that no file will have an ID that is used more than once, * even for different tags * * @param file * @param id * @return String containing the element type * @throws Exception */ String getElementByFileAndID(String file,String id) throws Exception{ Statement stat = conn.createStatement(); String query = ("select * from extents where id = '" + id + "'" + " and file_name = '" + file + "';"); ResultSet rs = stat.executeQuery(query); String elemName = rs.getString("element_name"); rs.close(); return elemName; } /** * Used to add a single tag's worth of information to the preparedStatement * for the extent table. Does not add to the database. * * @param file_name name of the file the tag is from * @param location the location of the tag in the text * @param element the type of the tag being added * @param id the ID of the tag being added * @throws Exception */ void add_extent(String file_name, int location, String element_name, String id) throws Exception{ extent_insert.setString(1, file_name); extent_insert.setInt(2, location); extent_insert.setString(3, element_name); extent_insert.setString(4, id); extent_insert.addBatch(); } /** * Adds all the inserts that have been batched into the PreparedStatement * for the extent table in the extent table to the database * * @throws Exception */ void batchExtents() throws Exception{ conn.setAutoCommit(false); extent_insert.executeBatch(); conn.setAutoCommit(true); } /** * Used to add a single tag's worth of information to the preparedStatement * for the extent table and to the database. * * @param file_name name of the file the tag is from * @param location the location of the tag in the text * @param element the type of the tag being added * @param id the ID of the tag being added * @throws Exception */ void insert_extent(String file_name, int location, String element, String id) throws Exception{ extent_insert.setString(1, file_name); extent_insert.setInt(2, location); extent_insert.setString(3, element); extent_insert.setString(4, id); extent_insert.addBatch(); conn.setAutoCommit(false); extent_insert.executeBatch(); conn.setAutoCommit(true); } /** * Adds all the inserts that have been batched into the PreparedStatement * for the link table in the extent table to the database * * @throws Exception */ void batchLinks() throws Exception{ conn.setAutoCommit(false); link_insert.executeBatch(); conn.setAutoCommit(true); } /** * Used to add a single tag's worth of information to the preparedStatement * for the link table. Does not add to the database. * * @param file_name name of the file the added tag is from * @param newID ID of the tag being added * @param linkName type of the tag being added * @param linkFrom the id of the 'from' anchor for the link * @param from_name the type of the 'from' anchor for the link * @param linkTo the id of the 'to' anchor for the link * @param to_name the type of the 'to' anchor for the link * @throws Exception */ void add_link(String file_name, String newID, String linkName, String linkFrom, String from_name, String linkTo, String to_name) throws Exception{ link_insert.setString(1, file_name); link_insert.setString(2, newID); link_insert.setString(3, linkFrom); link_insert.setString(4, from_name); link_insert.setString(5, linkTo); link_insert.setString(6, to_name); link_insert.setString(7, linkName); link_insert.addBatch(); } /** * Used to add a single tag's worth of information to the preparedStatement * for the link table and to the database. * * @param file_name name of the file the added tag is from * @param newID ID of the tag being added * @param linkName type of the tag being added * @param linkFrom the id of the 'from' anchor for the link * @param from_name the type of the 'from' anchor for the link * @param linkTo the id of the 'to' anchor for the link * @param to_name the type of the 'to' anchor for the link * @throws Exception */ void insert_link(String file_name, String newID, String linkName, String linkFrom, String from_name, String linkTo, String to_name) throws Exception{ link_insert.setString(1, file_name); link_insert.setString(2, newID); link_insert.setString(3, linkFrom); link_insert.setString(4, from_name); link_insert.setString(5, linkTo); link_insert.setString(6, to_name); link_insert.setString(7, linkName); link_insert.addBatch(); conn.setAutoCommit(false); link_insert.executeBatch(); conn.setAutoCommit(true); } /** * Closes the connection to the DB */ void close_db(){ try{ conn.close(); }catch(Exception e){ System.out.println(e.toString()); } } /** * Checks to see if the given id exists for the filename. * * @param id the ID being searched for * @param fileName the name of the file being searched i * @return true if the id exists, false if not * * @throws Exception */ boolean idExists(String id, String fileName) throws Exception{ Statement stat = conn.createStatement(); String query = ("select count(id) from extents where " + "id = '" + id + "' and file_name ='"+fileName+"';"); ResultSet rs = stat.executeQuery(query); int num = rs.getInt(1); rs.close(); if (num>0){ return true; } String query2 = ("select count(id) from links where " + "id = '" + id + "' and file_name ='"+fileName+"';"); ResultSet rs2 = stat.executeQuery(query2); int num2 = rs2.getInt(1); rs2.close(); if (num2>0){ return true; } return false; } /** * Checks to see if the file has a tag at the given location * * @param file the name of the file being searched * @param loc the location being searched * @return true or false, depending on if there's a tag there * * @throws Exception */ boolean tagExistsInFileAtLoc(String file, int loc) throws Exception{ Statement stat = conn.createStatement(); String query = ("select count(id) from extents where " + "location = " + loc + " and file_name ='"+file+"';"); ResultSet rs = stat.executeQuery(query); int num = rs.getInt(1); rs.close(); if(num>0){ return true; } return false; } /** * removes a link tag based on file, element name and id. Is currently * only called for the goldStandard file. * * @param fullName name of the file the tag is in * @param element_name type of the tag being removed * @param id ID of the tag being removed * * @throws Exception */ void removeLinkTags(String fullName, String element_name, String id) throws Exception{ print_other(element_name); //remove the tag from the links table Statement stat = conn.createStatement(); String delete = ("delete from links where id = '" +id + "' and element_name = '" + element_name + "' and file_name = '"+fullName+"';"); stat.executeUpdate(delete); //also need to remove it from the table associated with its element name stat = conn.createStatement(); delete = ("delete from " + element_name +" where id = '" +id + "' and file_name = '"+fullName+"';"); stat.executeUpdate(delete); } /** * removes an extent tag based on file, element name and id. Is currently * only called for the goldStandard file. * * @param fullName name of the file the tag is in * @param element_name type of the tag being removed * @param id ID of the tag being removed * * @throws Exception */ void removeExtentTags(String fullName, String element_name, String id) throws Exception{ //remove the tag from the extents table Statement stat = conn.createStatement(); String delete = ("delete from extents where id = '" +id + "' and element_name = '" + element_name + "' and file_name = '"+fullName+"';"); stat.executeUpdate(delete); //also need to remove it from the element_name table stat = conn.createStatement(); delete = ("delete from " + element_name +" where id = '" +id + "' and file_name = '"+fullName+"';"); stat.executeUpdate(delete); //finally, remove it from the overlap_extents if(fullName.equals("goldStandard.xml")){ stat = conn.createStatement(); delete = ("delete from extent_overlaps where gsid = '" +id + "' and element_name = '"+element_name+"';"); stat.executeUpdate(delete); } } /** * Checks to see if the provided tag overlaps with tags of the same type * from other files. * * @param fullname the name of the file being checked for overlaps, * currently only used for the goldStandard file * @param e the element describing the tag being added * @param tag the Hashtable of tag information * * @throws Exception */ void add_overlaps(String fullname, Elem e, Hashtable<String,String> tag) throws Exception{ Statement stat = conn.createStatement(); int start = Integer.parseInt(tag.get("start")); int end = Integer.parseInt(tag.get("end")); String gsid = tag.get("id"); String query = ("select distinct(id), file_name from extents where "+ "element_name = '" + e.getName() +"' and location >= " + start + " and location <=" + end + " and file_name !='goldStandard.xml';"); ResultSet rs = stat.executeQuery(query); while (rs.next()){ String filename = rs.getString("file_name"); String id = rs.getString("id"); overlap_insert.setString(1,gsid); overlap_insert.setString(2,e.getName()); overlap_insert.setString(3,filename); overlap_insert.setString(4,id); overlap_insert.addBatch(); } rs.close(); conn.setAutoCommit(false); overlap_insert.executeBatch(); conn.setAutoCommit(true); } /** * Finds all the overlaps with the goldStandard and other files. * Called when a new goldStandard file is loaded into MAI * * @throws Exception */ void findAllOverlaps() throws Exception{ //first, clear out the table Statement stat = conn.createStatement(); String delete = ("delete from extent_overlaps;"); stat.executeUpdate(delete); //then, find the ids and types of the GS links String findGSIDs = ("select distinct(id), element_name from extents where file_name = 'goldStandard.xml';"); ResultSet rs = stat.executeQuery(findGSIDs); while(rs.next()){ String e_name = rs.getString("element_name"); String gsid = rs.getString("id"); int start = (getStartOrEnd(rs.getString("id"), "goldStandard.xml", e_name,"start")); int end = (getStartOrEnd(rs.getString("id"), "goldStandard.xml", e_name,"end")); Statement stat2 = conn.createStatement(); //then, find the tags from other files that overlap with the one in the GS String query = ("select distinct(id), file_name from extents where "+ "element_name = '" + e_name +"' and location >= " + start + " and location <=" + end + " and file_name !='goldStandard.xml';"); ResultSet rs2 = stat2.executeQuery(query); while (rs2.next()){ String filename = rs2.getString("file_name"); String id = rs2.getString("id"); overlap_insert.setString(1,gsid); overlap_insert.setString(2,e_name); overlap_insert.setString(3,filename); overlap_insert.setString(4,id); overlap_insert.addBatch(); } rs2.close(); } rs.close(); //add the tags to the table conn.setAutoCommit(false); overlap_insert.executeBatch(); conn.setAutoCommit(true); } /** * gets the start and end locations of a tag by the file and id, * concatenated into a string: start,end * * @param file the file the tag is in * @param id the id of the tag * @return * @//add the tags to the tablethrows Exception */ String getLocByFileAndID(String file,String id) throws Exception{ Statement stat = conn.createStatement(); String query = ("select * from extents where id = '" + id + "' and file_name = '" + file + "';"); ResultSet rs = stat.executeQuery(query); ArrayList<Integer>locs = new ArrayList<Integer>(); while (rs.next()){ locs.add(Integer.parseInt(rs.getString("location"))); } //sort the ArrayList Collections.sort(locs); rs.close(); //return the first and last elements in the list as a string return locs.get(0)+","+(locs.get(locs.size()-1)); } /** * Returns the start or the end of the string, whichever is asked for * * @param id the id of the tag * @param filename the name of the file the tag is in * @param elemname the type of the tag * @param attribute the attribute being searched for, here only used for "start" or "end" * * @return */ private int getStartOrEnd(String id, String filename, String elemname, String attribute){ try{ Statement stat = conn.createStatement(); String query = ("select * from " + elemname + " where file_name = '" + filename + "' and id = '" + id + "';"); ResultSet rs = stat.executeQuery(query); String att = rs.getString(attribute); rs.close(); return(Integer.parseInt(att)); }catch(Exception e){ System.out.println(e.toString()); return -2; } } /** * Gets all instances of the requested link tag that exist in the gold standard. * This method is called when a link tag is selected from the radio buttons in MAI. * This is a complicated procedure, because it has to determine what link tags from the * files being adjudicated have anchors that overlap with extents in the gold standard, and * return a list of the locations in the gold standard that overlap with the link anchors * from the other files. * * It also fills in the information in the currentLinks hash, which keeps track of what links * from other files have overlaps so that when extents are selected the process of filling in the * adjudication table is sped up. * * TODO: refactor to make more efficient, use multiple database connections * * @param tagname the name of the tag being evaluated * * @return a hashcollection with all the locations and file names where * link anchors overlap with the gold standard * @throws Exception */ HashCollection<String,String> getGSLinksByType(String tagname) throws Exception{ //keep track of relevant links, reset each time a //new link tag is selected currentLinks.clear(); HashCollection<String,String>links = new HashCollection<String,String>(); Statement stat = conn.createStatement(); String query = ("select * from links where element_name = '" + tagname + "';"); ResultSet rs = stat.executeQuery(query); Hashtable<String,String>inGS = new Hashtable<String,String>(); Hashtable<String,String>inOther = new Hashtable<String,String>(); while(rs.next()){ //this needs to be re-written if(rs.getString("file_name").equals("goldStandard.xml")){ String newid = (rs.getString("file_name")+"@#@"+rs.getString("fromid") +"@#@"+rs.getString("from_name")); inGS.put(newid,""); newid = (rs.getString("file_name")+"@#@"+rs.getString("toid") +"@#@"+rs.getString("to_name")); inGS.put(newid,""); currentLinks.add(rs.getString("file_name")+"@#@"+rs.getString("id")); } else{ //if the link isn't in the GS, we only want to highlight //these extents if they both have overlaps in the GS String newid = (rs.getString("file_name")+"@#@"+rs.getString("fromid") +"@#@"+rs.getString("from_name")+"@#@"+ rs.getString("file_name")+"@#@"+rs.getString("toid") +"@#@"+rs.getString("to_name")+"@#@"+rs.getString("id")); inOther.put(newid,""); } } rs.close(); for(Enumeration<String> ids = inOther.keys() ; ids.hasMoreElements() ;) { //if the ids being examined don't come from a GS link, //we need to get the corresponding GS id (based on overlaps) //both IDs must have overlaps for either to be included //in the hashtable String id = (String)ids.nextElement(); boolean hasToOverlap = false; boolean hasFromOverlap = false; ArrayList<String> overlaps = new ArrayList<String>(); String filename = id.split("@#@")[0]; String filetagid = id.split("@#@")[1]; query = ("select gsid from extent_overlaps where element_name ='" + id.split("@#@")[2]+"' and file_name ='" + filename + "'and fileid='" + filetagid +"';"); rs=stat.executeQuery(query); while (rs.next()){ String newid = (filename+"@#@"+rs.getString("gsid") +"@#@"+id.split("@#@")[2]); overlaps.add(newid); hasToOverlap = true; } rs.close(); filetagid = id.split("@#@")[4]; query = ("select gsid from extent_overlaps where element_name ='" + id.split("@#@")[5]+"' and file_name ='" + filename + "'and fileid='" + filetagid +"';"); rs=stat.executeQuery(query); while (rs.next()){ String newid = (filename+"@#@"+rs.getString("gsid") +"@#@"+id.split("@#@")[5]); overlaps.add(newid); hasFromOverlap = true; } rs.close(); if (hasToOverlap && hasFromOverlap){ for(int i=0;i<overlaps.size();i++){ inGS.put(overlaps.get(i),""); currentLinks.add(filename+"@#@"+id.split("@#@")[6]); } } } //now that we have all the overlapping GS ids, we can for (Enumeration<String> ids = inGS.keys() ; ids.hasMoreElements() ;) { String id = (String)ids.nextElement(); String filename = id.split("@#@")[0]; query = ("select location from extents where file_name = '" + "goldStandard.xml" + "' and element_name = '" + id.split("@#@")[2] + "' and id = '" + id.split("@#@")[1] + "';"); rs = stat.executeQuery(query); while (rs.next()){ links.putEnt(rs.getString("location"),filename); } rs.close(); } return links; } /** * Returns a HashCollection of link IDs from a file where the given extent id is an anchor * * @param file the name of the file being searched * @param element_name the type of element being searched for in the anchor * @param id the id of the anchor being searched for * @return A HashCollection where the keys are the type of element and the * values are link IDs * @throws Exception */ HashCollection<String,String> getLinksByFileAndExtentID(String file, String element_name, String id) throws Exception{ HashCollection<String,String>links = new HashCollection<String,String>(); //first get the links where the extent being searched for is the //'from' anchor Statement stat = conn.createStatement(); String query = ("select id,element_name from links where fromid = '" + id + "' and from_name ='" + element_name + "' and file_name = '"+ file + "';"); ResultSet rs = stat.executeQuery(query); while(rs.next()){ links.putEnt(rs.getString("element_name"),rs.getString("id")); } rs.close(); //then get the ones where the extent is the 'to' anchor String query2 = ("select id,element_name from links where toid = '" + id + "' and to_name ='" + element_name + "' and file_name = '"+ file + "';"); ResultSet rs2 = stat.executeQuery(query2); while(rs2.next()){ links.putEnt(rs2.getString("element_name"),rs2.getString("id")); } rs2.close(); return links; } /** * Finds the tags of a particular type that exist in an extent and * returns the filenames as keys and the IDs as values. Used to fill * in the table in MAI when an extent is selected. * * @param begin the starting offset of the selected extent * @param end the ending offset of the selected extent * @param tagName the type of tag being searched for * @return HashCollection with file names as keys and IDs as values * * @throws Exception */ HashCollection<String,String> getTagsInSpanByType(int begin, int end, String tagName) throws Exception{ Statement stat = conn.createStatement(); String query = ""; if(begin!=end){ query = ("select distinct(id), file_name from extents " + "where element_name = '"+tagName+"' and location >= " + begin + " and location <=" + end + ";"); } else{ query = ("select distinct(id), file_name from extents where location = " + begin + " and element_name = '"+tagName+"';"); } ResultSet rs = stat.executeQuery(query); HashCollection<String,String> tags = new HashCollection<String,String>(); while(rs.next()){ tags.putEnt(rs.getString("file_name"),rs.getString("id")); } rs.close(); return tags; } /** * This function is called when a user selects an extent in the text window * and returns the tag information that will be used to fill in the table. * While links are collected from all the files entered into the adjudication, * the text and extent IDs that are shown in the links are ones from the GoldStandard. * This helps ensure that only links with both anchors in (or at least overlapping with * the goldStandard are displayed, but it does make the function much more complicated. * * <p> * This method also tracks the locations of the extents that should be * highlighted in the text to reflect where the annotations and gold standard * placed the other extents associated with the selected text. This information * is kept in the currentHighlights hash. * <p> * TODO: refactor, use more nested DB queries, remove assumption about * link ends only having one tag per document * <p> * @param begin the beginning offset of the selected extent * @param end the ending offset of the selected extent * @param tagname the type of tag being searched for * @param atts the attributes of the tag being searched for * @return a HashCollection of tag information, keyed by filename * @throws Exception */ HashCollection<String,Hashtable<String,String>> getLinkTagsInSpanByType (int begin, int end, String tagname,ArrayList<Attrib> atts) throws Exception{ //based on the new selection, the highlights in the text window will //be changed; keep track of those here currentHighlights.clear(); HashCollection<String,Hashtable<String,String>> gsLinkExtents = new HashCollection<String,Hashtable<String,String>>(); HashCollection<String,Hashtable<String,String>> gsTempLinkExtents = new HashCollection<String,Hashtable<String,String>>(); Statement stat = conn.createStatement(); for(int i=0;i<currentLinks.size();i++){ String link = currentLinks.get(i); String filename = link.split("@#@")[0]; String linkid = link.split("@#@")[1]; //first, grab the info for each of the links that are being considered String query = ("select * from "+ tagname + " where id = '" + linkid + "' and file_name = '"+ filename+"';"); ResultSet rs = stat.executeQuery(query); Hashtable<String,String> linkelems = new Hashtable<String,String>(); while (rs.next()){ for(int j=0;j<atts.size();j++){ linkelems.put(atts.get(j).getName(),rs.getString(atts.get(j).getName())); } //use TempLinkExtents so that only links with overlaps will be //passed back gsTempLinkExtents.putEnt(filename,linkelems); } rs.close(); } //next, go through each link, check to see if either end overlaps with //the selected text, then //find the GS replacements for the From ArrayList<String> filenames = gsTempLinkExtents.getKeyList(); for(int i = 0;i<filenames.size();i++){ String filename = filenames.get(i); ArrayList<Hashtable<String,String>> links = gsTempLinkExtents.get(filename); for(int j=0;j<links.size();j++){ boolean overlap = false; Hashtable<String,String> link = links.get(j); String fromid = link.get("fromID"); //need to get type of extent to ensure compatibility String query = ("select * from extents where file_name = '" + filename + "' and id = '" + fromid + "';"); ResultSet rs = stat.executeQuery(query); String fromElemName = rs.getString("element_name"); rs.close(); //check to see if fromID overlaps with selected text query = ("select start, end from " + fromElemName + " where id = '" + fromid + "' and file_name = '" + filename + "';"); rs = stat.executeQuery(query); int fromStart = Integer.parseInt(rs.getString("start")); int fromEnd = Integer.parseInt(rs.getString("end")); rs.close(); boolean fromOverlap = false; if((fromStart >= begin && fromStart<=end) || (fromEnd >= begin && fromEnd <=end) || (fromStart<=begin && fromEnd>=end)){ overlap=true; fromOverlap = true; } //do the same for the toID //need to get type of extent to ensure compatibility String toid = link.get("toID"); query = ("select * from extents where file_name = '" + filename + "' and id = '" + toid + "';"); rs = stat.executeQuery(query); String toElemName = rs.getString("element_name"); rs.close(); //check to see if toID overlaps with selected text query = ("select start, end from " + toElemName + " where id = '" + toid + "' and file_name = '" + filename + "';"); rs = stat.executeQuery(query); int toStart = Integer.parseInt(rs.getString("start")); int toEnd = Integer.parseInt(rs.getString("end")); rs.close(); boolean toOverlap = false; if((toStart >= begin && toStart<=end) || (toEnd >= begin && toEnd <=end) || (toStart<=begin && toEnd>=end)){ overlap=true; toOverlap = true; } //if there's an overlap, proceed with replacing the ids and text if(overlap){ //add overlaps to currentHighlights if (!fromOverlap){ currentHighlights.putEnt(filename,fromStart+"@#@"+fromEnd); } if (!toOverlap){ currentHighlights.putEnt(filename,toStart+"@#@"+toEnd); } //first, swap out fromID and fromText query = ("select distinct(id) from extents " + "where element_name = '"+fromElemName+"' and file_name = '" + "goldStandard.xml" + "' and location >= " + fromStart + " and location <=" + fromEnd + ";"); rs = stat.executeQuery(query); //NOTE: assumes there will be a one-to-one overlap //may need to be fixed in later versions String newFromID = rs.getString("id"); rs.close(); links.get(j).put("fromID",newFromID); String newFromText = ""; try{ newFromText = getTextByFileElemAndID("goldStandard.xml",fromElemName,newFromID); }catch(Exception e){ } links.get(j).put("fromText",newFromText); //now, do the same for toID and toText //get location of toID extent query = ("select distinct(id) from extents " + "where element_name = '"+toElemName+"' and file_name = '" + "goldStandard.xml" + "' and location >= " + toStart + " and location <=" + toEnd + ";"); rs = stat.executeQuery(query); //NOTE: assumes there will be a one-to-one overlap //may need to be fixed in later versions String newToID = rs.getString("id"); rs.close(); links.get(j).put("toID",newToID); String newToText = ""; try{ newToText = getTextByFileElemAndID("goldStandard.xml",toElemName,newToID); }catch(Exception e){ } links.get(j).put("toText", newToText); //add new link info to HashCollection being sent back to MAI gsLinkExtents.putEnt(filename,links.get(j)); } } } return gsLinkExtents; } /** * Retrieves the text of an extent tag by using the id, type, and file * of the tag * * @param file name of the file the tag is in * @param elem type of the tag being searched for * @param id ID of the tag * @return the text of the tag * @throws Exception */ String getTextByFileElemAndID(String file, String elem, String id) throws Exception{ Statement stat = conn.createStatement(); String query = ("select text from " + elem + " where file_name = '"+ file +"' and id = '" + id + "';"); ResultSet rs = stat.executeQuery(query); String text = rs.getString("text"); rs.close(); return text; } /** * Returns IDs of all the tags located over an extent, as well as * all non-consuming tags from that file. * * @param file the file being searched * @param begin the beginning of the selected extent * @param end the end of the selected extent * @return a HashCollection of tag information keyed by element_name * @throws Exception */ HashCollection<String,String> getFileTagsInSpanAndNC(String file,int begin, int end) throws Exception{ Statement stat = conn.createStatement(); String query = ""; if(begin!=end){ query = ("select distinct(id), element_name from extents where location >= " + begin + " and location <=" + end + " and file_name ='" + file + "';"); } else{ query = ("select distinct(id), element_name from extents where location = " + begin + " and file_name = '" + file+ "';"); } ResultSet rs = stat.executeQuery(query); HashCollection<String,String> tags = new HashCollection<String,String>(); while(rs.next()){ tags.putEnt(rs.getString("element_name"),rs.getString("id")); } rs.close(); //now get the non-consuming tags query = ("select distinct(id), element_name from extents where location = -1;"); rs = stat.executeQuery(query); while(rs.next()){ tags.putEnt(rs.getString("element_name"),rs.getString("id")); } rs.close(); return tags; } /** * Returns the HashCollection currentHighlights for use * in highlighting the appropriate extents in MAI's text area. * * @return */ public HashCollection<String,String>getCurrentHighlights(){ return currentHighlights; } //Below are a series of methods for printing the information in the //database. They aren't terribly useful because it's easier and //more accureate to check the DB through the command line if necessary, //but they're nice to have around. /** * Prints the extent table */ public void print_extents(){ System.out.println("Extents in DB:"); try{ Statement stat = conn.createStatement(); ResultSet rs = stat.executeQuery("select * from extents;"); while (rs.next()) { System.out.println("file name = " + rs.getString("file_name")); System.out.println("location = " + rs.getString("location")); System.out.println("element = " + rs.getString("element_name")); System.out.println("id = " + rs.getString("id")); } rs.close(); }catch(Exception e){ System.out.println(e.toString()); } } /** * Prints the unique ids in the extent table */ public void print_unique_extents(){ System.out.println("Extents in DB:"); try{ Statement stat = conn.createStatement(); ResultSet rs = stat.executeQuery("select distinct(id), file_name, element_name from extents;"); while (rs.next()) { System.out.println("file name = " + rs.getString("file_name")); System.out.println("element_name = " + rs.getString("element_name")); System.out.println("id = " + rs.getString("id")); } rs.close(); }catch(Exception e){ System.out.println(e.toString()); } } /** * Prints the links in the DB */ public void print_links(){ System.out.println("Links in DB:"); //links (id,fromid,from_name,toid,to_name,element_name);"); try{ Statement stat = conn.createStatement(); ResultSet rs = stat.executeQuery("select * from links;"); while (rs.next()) { System.out.println("file name = " + rs.getString("file_name")); System.out.println("id = " + rs.getString("id")); System.out.println("from = " + rs.getString("fromid")); System.out.println("from_name = " + rs.getString("from_name")); System.out.println("to = " + rs.getString("toid")); System.out.println("to_name = " + rs.getString("to_name")); System.out.println("element_name = " + rs.getString("element_name")); } rs.close(); }catch(Exception e){ System.out.println(e.toString()); } } /** * Prints the extent_overlaps table */ public void print_overlaps(){ System.out.println("\nExtent overlaps:"); try{ Statement stat = conn.createStatement(); ResultSet rs = stat.executeQuery("select * from extent_overlaps;"); while (rs.next()) { System.out.println("gsid = " + rs.getString("gsid")); System.out.println("element_name = " + rs.getString("element_name")); System.out.println("file_name = " + rs.getString("file_name")); System.out.println("fileid = " + rs.getString("fileid")); } rs.close(); } catch(Exception e){ System.out.println(e.toString()); } } /** * Prints basic information about the table with the * provided tag name. * * @param extent_name the name of the tag/table to be printed. */ private void print_other(String extent_name){ System.out.println("\nTag info:"); try{ Statement stat = conn.createStatement(); ResultSet rs = stat.executeQuery("select * from "+ extent_name + ";"); while (rs.next()) { System.out.println("id = " + rs.getString("id")); System.out.println("file_name = " + rs.getString("file_name")); } rs.close(); } catch(Exception e){ System.out.println(e.toString()); } } }
Java
/* * MAI - Multi-document Adjudication Interface * * Copyright Amber Stubbs (astubbs@cs.brandeis.edu) * Department of Computer Science, Brandeis University * * MAI 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 mai; /** * FileOperations handles turning the MAI databases into XML, UTF-8 encoded files. * * @author Amber Stubbs */ import java.io.*; import java.util.*; import javax.swing.*; import java.io.File; class FileOperations { /** * Checks to see if there are tags in a file * @param f the file being checked * @return true if the file has tags (in the MAE/MAI format), false if not * * @throws Exception */ public static boolean areTags(File f) throws Exception{ Scanner scan = new Scanner(f,"UTF-8"); while (scan.hasNextLine()){ String line = scan.nextLine(); if(line.equals("<TAGS>")==true){ scan.close(); return true; } } scan.close(); return false; } /** * Writes the current goldStandard to a file * * @param f the file being written * @param pane the pane containing the text being adjudicated * @param adjudicationTask the interface with the database */ public static void saveAdjudXML(File f, JTextPane pane, AdjudicationTask adjudicationTask){ String paneText = pane.getText(); ArrayList<Elem> elements = adjudicationTask.getElements(); String dtdName = adjudicationTask.getDTDName(); try{ //first, create the OutputStreamWriter and write the header information OutputStreamWriter fw = new OutputStreamWriter(new FileOutputStream(f),"UTF-8"); String t = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"; t = t + "<"+dtdName+">\n"; t = t + "<TEXT><![CDATA["; fw.write(t,0,t.length()); //then, write what's in the text fw.write(paneText,0,paneText.length()); t = "]]></TEXT>\n"; fw.write(t,0,t.length()); String s = "<TAGS>\n"; fw.write(s,0,s.length()); //now to put in the tags for(int i=0;i<elements.size();i++){ if(elements.get(i) instanceof ElemExtent){ //get tags of this type from the GoldStandard ArrayList<String>tags = adjudicationTask.getExtentTagsByFileAndType("goldStandard.xml",elements.get(i)); arrayWrite(tags,fw); } else{ ArrayList<String>tags = adjudicationTask.getLinkTagsByFileAndType("goldStandard.xml",elements.get(i)); arrayWrite(tags,fw); } } s = "</TAGS>\n</"+dtdName+">"; fw.write(s,0,s.length()); fw.close(); }catch(Exception ex){ System.out.println(ex.toString()); } } /** * */ public static void saveAdjudXMLperfile(String filename, JTextPane pane, AdjudicationTask adjudicationTask){ String paneText = pane.getText(); ArrayList<Elem> elements = adjudicationTask.getElements(); String dtdName = adjudicationTask.getDTDName(); try{ //first, create the OutputStreamWriter and write the header information File savingdir = new File("goldstdfiles\\"); if(!savingdir.exists()) savingdir.mkdir(); OutputStreamWriter fw = new OutputStreamWriter(new FileOutputStream("goldstdfiles\\" + filename),"UTF-8"); String t = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"; t = t + "<"+dtdName+">\n"; t = t + "<TEXT><![CDATA["; fw.write(t,0,t.length()); //then, write what's in the text fw.write(paneText,0,paneText.length()); t = "]]></TEXT>\n"; fw.write(t,0,t.length()); String s = "<TAGS>\n"; fw.write(s,0,s.length()); //now to put in the tags for(int i=0;i<elements.size();i++){ if(elements.get(i) instanceof ElemExtent){ //get tags of this type from the GoldStandard ArrayList<String>tags = adjudicationTask.getExtentTagsByFileAndType("goldStandard.xml",elements.get(i)); arrayWrite(tags,fw); } else{ ArrayList<String>tags = adjudicationTask.getLinkTagsByFileAndType("goldStandard.xml",elements.get(i)); arrayWrite(tags,fw); } } s = "</TAGS>\n</"+dtdName+">"; fw.write(s,0,s.length()); fw.close(); }catch(Exception ex){ System.out.println(ex.toString()); } } /** * writes the contents of an array to the file * * @param tags * @param fw * @throws Exception */ private static void arrayWrite(ArrayList<String> tags,OutputStreamWriter fw ) throws Exception{ for (int i=0;i<tags.size();i++){ String tag = tags.get(i); fw.write(tag,0,tag.length()); } } }
Java
/* * MAI - Multi-document Adjudication Interface * * Copyright Amber Stubbs (astubbs@cs.brandeis.edu) * Department of Computer Science, Brandeis University * * MAI 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 mai; import java.util.*; import org.xml.sax.*; import org.xml.sax.helpers.*; /** * XMLHandler extends the sax DefaultHandler to work specifically with * the stand-off XML format used in MAE/MAI. * * @author Amber Stubbs */ class XMLHandler extends DefaultHandler { private HashCollection<String,Hashtable<String,String>> newTags = new HashCollection<String,Hashtable<String,String>>(); private boolean text = false; private String textChars=""; XMLHandler (){ } public void startElement(String nsURI, String strippedName, String tagName, Attributes atts) throws SAXException { if (tagName.equalsIgnoreCase("text")){ text = true; } Hashtable<String,String> tag = new Hashtable<String,String>(); for(int i=0;i<atts.getLength();i++){ String name = atts.getQName(i); String value = atts.getValue(i); tag.put(name,value); newTags.putEnt(tagName,tag); } } public void endElement(String nsURI, String localName, String tagName){ } public void characters(char[] ch, int start, int length) { if (text) { textChars = new String(ch, start, length); text = false; } } HashCollection<String,Hashtable<String,String>> returnTagHash(){ return newTags; } public String getTextChars(){ return textChars; } }
Java
/* * MAI - Multi-document Adjudication Interface * * Copyright Amber Stubbs (astubbs@cs.brandeis.edu) * Department of Computer Science, Brandeis University * * MAI 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 mai; /** * A class that describes tag attributes that * only contain text data (such as comments) * * @author Amber Stubbs * */ class AttData extends Attrib{ AttData(){ } AttData (String name, boolean r){ setName(name); setRequired(r); setData(""); setDefaultValue(""); } AttData (String name, boolean r, String d){ setName(name); setRequired(r); setData(""); setDefaultValue(d); } public String getData(){ return data; } public void setData(String c){ data=c; } public void printInfo(){ System.out.println("Attribute name =" + getName() + " \n\trequired = " + getRequired() + "\n\tdata = " + data); } public String toString(){ return("Attribute name =" + getName() + " , required = " + getRequired() + " data = " + data ); } private String data; }
Java
/* * MAI - Multi-document Adjudication Interface * * Copyright Amber Stubbs (astubbs@cs.brandeis.edu) * Department of Computer Science, Brandeis University * * MAI 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 mai; import java.util.*; /** * Parent class for DTD elements (generally referred to as "tags") * * @author Amber Stubbs */ class Elem extends Object{ Elem(){ setName("no name"); attributes=new ArrayList<Attrib>(); } public String getName(){ return name; } public void setName(String t){ name=t; } public String toString(){ return("name " + getName()); } public void addAttribute(Attrib a){ attributes.add(a); } public ArrayList<Attrib> getAttributes(){ return attributes; } public Attrib getAttribute(String name){ for(int i=0;i<attributes.size();i++){ if ((attributes.get(i).getName()).equalsIgnoreCase(name)){ return attributes.get(i); } } return null; } public boolean hasAttribute(String name){ for(int i=0;i<attributes.size();i++){ if ((attributes.get(i).getName()).equalsIgnoreCase(name)){ return true; } } return false; } public void printInfo(){ System.out.println(name); System.out.println("Attributes:"); for(int i=0;i<attributes.size();i++){ attributes.get(i).printInfo(); System.out.println("\n"); } } private ArrayList<Attrib> attributes; private String name; }
Java
/* * MAI - Multi-document Adjudication Interface * * Copyright Amber Stubbs (astubbs@cs.brandeis.edu) * Department of Computer Science, Brandeis University * * MAI 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 mai; import java.util.*; /** * * Provides a description of the annotation task information * stored in a DTD. The DTD describes the annotation * task, specifically the tags and attributes. * * @author Amber Stubbs * */ class DTD extends Object{ DTD(){ elements=new ArrayList<Elem>(); name="XML"; } public String getName(){ return name; } public void setName(String t){ name=t; } public String toString(){ return("name " + getName()); } public void addElem(Elem t){ elements.add(t); } public Elem getElem(String name){ for(int i=0;i<elements.size();i++){ Elem e = elements.get(i); if (e.getName().equalsIgnoreCase(name)){ return e; } } return null; } public boolean hasElem(String name){ for(int i=0;i<elements.size();i++){ Elem e = elements.get(i); if (e.getName().equalsIgnoreCase(name)){ return true; } } return false; } public ArrayList<Elem> getElements(){ return elements; } /** * Returns a list of all the elements in the DTD * @return */ public ArrayList<String> getElementIDs(){ ArrayList<String> ids = new ArrayList<String>(); for (int i=0;i<elements.size();i++){ Elem e = elements.get(i); AttID a = (AttID)e.getAttribute("id"); ids.add(a.getPrefix()); } return ids; } /** * Returns a list of non-consuming extent tags * * @return */ public ArrayList<Elem> getNCElements(){ ArrayList<Elem> NCElems = new ArrayList<Elem>(); for(int i=0;i<elements.size();i++){ Elem e = elements.get(i); if(e instanceof ElemExtent){ ElemExtent ex = (ElemExtent)e; Attrib start = ex.getAttribute("start"); if(!(start.getRequired())){ NCElems.add(e); } } } return NCElems; } public void printInfo(){ System.out.println(name); System.out.println("Elements:"); for(int i=0;i<elements.size();i++){ System.out.println(" Element " + i); elements.get(i).printInfo(); System.out.println("\n"); } } private ArrayList<Elem> elements; private String name; }
Java
/* * MAI - Multi-document Adjudication Interface * * Copyright Amber Stubbs (astubbs@cs.brandeis.edu) * Department of Computer Science, Brandeis University * * MAI 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/>. * */ /* compiling: javac -Xlint:unchecked -cp sqlitejdbc-v056.jar *.java java -cp .:sqlitejdbc-v056.jar MaiGui java 1.5: javac -target 1.5 -Xlint:unchecked -cp sqlitejdbc-v056.jar *.java making the .jar file (after compiling): jar cvfm Mai.jar manifest.txt *.class java -jar Mai.jar */ package mai; import java.awt.*; import java.awt.event.*; import java.lang.Exception; import javax.swing.*; import javax.swing.text.*; import javax.swing.event.*; import javax.swing.table.TableColumn; import javax.swing.table.DefaultTableModel; import java.io.*; import java.util.*; //import org.eclipse.wb.swing.FocusTraversalOnArray; /** * MaiGui is the main class for MAI; it manages all the GUI attributes * and manages how the annotation/adjudication information is loaded, interacted with, * and displayed. * <p> * All files loaded into MAI must be UTF-8 encoded, otherwise the character offsets * cannot be gauranteed to work. * * * @author Amber Stubbs * @version 0.7.1 May 10, 2012 */ public class MaiGui extends JPanel{ /** * */ private static final long serialVersionUID = -6122390155866896831L; private Hashtable<String, Color> colorTable; private Color[] colors = {Color.magenta, new Color(153,102,0), new Color(255,204,51), new Color(0,172,188),new Color (234,160,0), new Color(102,75,153),Color.lightGray}; //private Hashtable<String,Object> highlighterTable; //keeps track of what parts of the text //have been visited by the user when //looking at link tags. private HashCollection<String,Integer> visitedLocs; private ArrayList<String> goldstdAdjudSet; private ArrayList<String> filesSet; private int current; private String folderOneInitial; private String folderTwoInitial; private boolean textSelected; private boolean ctrlPressed; private int loc1; private boolean hasFile; private boolean hasFolder1; private boolean hasFolder2; private boolean goldStdadded; private String linkFrom; private String linkName; private String linkTo; private int start; private int end; private int tableRow; private int tableCol; private JFileChooser fcDtd; private JFileChooser fcFile; private JFileChooser fcSave; private JFileChooser fcFolder; private static JFrame frame; private JPanel annotatePane; private JTextPane displayAnnotation; private JScrollPane scrollPane; private JLabel mouseLabel; private JFrame linkFrame; private JPanel tagPanel; private ButtonGroup tagButtons; private JLabel lbSerialNumber; private JPanel infoPanel; private TableListener tablelistener; private AnnJTable tagTable; private JMenuBar mb; private JMenu fileMenu; private JMenu display; //private JMenu nc_tags; private JMenu helpMenu; private JPopupMenu popup1; private JPopupMenu popup2; private static AdjudicationTask adjudicationTask; private ArrayList<String> filenames; private File[] filesSetOne; private File[] filesSetTwo; public MaiGui(){ super(new BorderLayout()); visitedLocs = new HashCollection<String,Integer>(); goldstdAdjudSet = new ArrayList<String>(); /*global variable assignments*/ hasFile = false; hasFolder1 = false; hasFolder2 = false; start=-1; end=-1; loc1 = -1; linkFrom=""; linkName=""; linkTo=""; textSelected=false; ctrlPressed=false; tableRow = -1; tableCol = -1; filenames = new ArrayList<String>(); filenames.add("goldStandard.xml"); colorTable = new Hashtable<String,Color>(); linkFrame = new JFrame(); /*GUI parts*/ fcDtd = new JFileChooser("."); fcDtd.setFileSelectionMode(JFileChooser.FILES_ONLY); fcFile = new JFileChooser("."); fcFile.setFileSelectionMode(JFileChooser.FILES_ONLY); fcSave = new JFileChooser("."); fcSave.setFileSelectionMode(JFileChooser.FILES_ONLY); fcFolder = new JFileChooser("."); fcFolder.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); popup1 = new JPopupMenu(); popup2 = new JPopupMenu(); tagTable = new AnnJTable(); tablelistener = new TableListener(); adjudicationTask = new AdjudicationTask(); mouseLabel = new JLabel("Highlighted text: (-1,-1)"); annotatePane = new JPanel(new BorderLayout()); displayAnnotation = new JTextPane(new DefaultStyledDocument()); displayAnnotation.setEditable(false); displayAnnotation.setContentType("text/plain; charset=UTF-8"); displayAnnotation.addKeyListener(new ModKeyListener()); displayAnnotation.addCaretListener(new AnnCaretListener()); displayAnnotation.addMouseListener(new PopupListener()); scrollPane = new JScrollPane(displayAnnotation); annotatePane.add(scrollPane,BorderLayout.CENTER); annotatePane.add(mouseLabel,BorderLayout.SOUTH); tagPanel = new JPanel(new GridLayout(0,1)); tagButtons = new ButtonGroup(); JLabel lab = new JLabel("DTD tags"); tagPanel.add(lab); infoPanel = new JPanel(new GridLayout(0,1)); mb = new JMenuBar(); fileMenu = createFileMenu(); display = createDisplayMenu(); helpMenu = createHelpMenu(); mb.add(fileMenu); mb.add(display); mb.add(helpMenu); JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,annotatePane,infoPanel); JPanel buttonPanel = new JPanel(); annotatePane.add(buttonPanel, BorderLayout.NORTH); GridBagLayout gbl_buttonPanel = new GridBagLayout(); gbl_buttonPanel.columnWidths = new int[]{358, 0, 0}; gbl_buttonPanel.rowHeights = new int[]{0, 0, 0}; gbl_buttonPanel.columnWeights = new double[]{1.0, 0.0, Double.MIN_VALUE}; gbl_buttonPanel.rowWeights = new double[]{0.0, 0.0, Double.MIN_VALUE}; buttonPanel.setLayout(gbl_buttonPanel); JButton btnNext = new JButton("Next"); GridBagConstraints gbc_btnNext = new GridBagConstraints(); gbc_btnNext.anchor = GridBagConstraints.EAST; gbc_btnNext.fill = GridBagConstraints.VERTICAL; gbc_btnNext.gridx = 1; gbc_btnNext.gridy = 1; btnNext.addActionListener(new getButtonActions()); JButton btnPrevious = new JButton("Previous"); GridBagConstraints gbc_btnPrevious = new GridBagConstraints(); gbc_btnPrevious.anchor = GridBagConstraints.WEST; gbc_btnPrevious.insets = new Insets(0, 0, 0, 5); gbc_btnPrevious.gridx = 0; gbc_btnPrevious.gridy = 1; btnPrevious.addActionListener(new getButtonActions()); lbSerialNumber = new JLabel(""); GridBagConstraints gbc_lbSerialNumber = new GridBagConstraints(); gbc_lbSerialNumber.insets = new Insets(0, 0, 5, 0); gbc_lbSerialNumber.gridx = 1; gbc_lbSerialNumber.gridy = 0; buttonPanel.add(lbSerialNumber, gbc_lbSerialNumber); buttonPanel.add(btnPrevious, gbc_btnPrevious); buttonPanel.add(btnNext, gbc_btnNext); //annotatePane.setFocusTraversalPolicy(new FocusTraversalOnArray(new Component[]{scrollPane, displayAnnotation, mouseLabel, btnPrevious, btnNext, buttonPanel})); this.addKeyListener(new ModKeyListener()); add(mb,BorderLayout.NORTH); add(tagPanel,BorderLayout.WEST); add(splitPane,BorderLayout.CENTER); splitPane.setDividerLocation(400); } // ******************************************************* // This section of MAI code contains the classes used in MAI /** * Handles the actions in the File menu; loading DTDs, starting new * adjudication tasks, adding files/gold standards to the adjudication task. * */ private class getFile implements ActionListener{ public void actionPerformed(ActionEvent e){ if (e.getActionCommand().equals("Load DTD")){ int returnVal = fcDtd.showOpenDialog(MaiGui.this); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fcDtd.getSelectedFile(); try{ displayAnnotation.setStyledDocument(new DefaultStyledDocument()); DTDLoader dtdl = new DTDLoader(file); adjudicationTask.reset_db(); adjudicationTask.setDTD(dtdl.getDTD()); makeRadioTags(); //reset visitedLocs visitedLocs = new HashCollection<String,Integer>(); updateMenus(); hasFile=false; hasFolder1 = false; hasFolder2 = false; adjudicationTask.addDTDtoDB(); resetInfoPanel(); }catch(Exception o){ System.out.println("Error loading DTD"); System.out.println(o.toString()); } } }//end if "Load DTD" else if (e.getActionCommand().equals("start adjud")){ int returnVal = fcFile.showOpenDialog(MaiGui.this); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fcFile.getSelectedFile(); String fullName = file.getName(); try{ frame.setTitle(fullName); hasFile = true; updateMenus(); visitedLocs = new HashCollection<String,Integer>(); adjudicationTask.reset_db(); adjudicationTask.addDTDtoDB(); adjudicationTask.reset_IDTracker(); colorTable.clear(); colorTable.put("goldStandard.xml",Color.yellow); colorTable.put("allOtherFiles",Color.cyan); colorTable.put("someOtherFiles",Color.pink); Highlighter high = displayAnnotation.getHighlighter(); high.removeAllHighlights(); filenames = new ArrayList<String>(); filenames.add(fullName); filenames.add("goldStandard.xml"); frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); displayAnnotation.setStyledDocument(new DefaultStyledDocument()); displayAnnotation.setContentType("text/plain; charset=UTF-8"); resetInfoPanel(); if (FileOperations.areTags(file)){ XMLFileLoader xfl = new XMLFileLoader(file); StyledDocument d = displayAnnotation.getStyledDocument(); Style def = StyleContext.getDefaultStyleContext().getStyle( StyleContext.DEFAULT_STYLE ); Style regular = d.addStyle( "regular", def ); d.insertString(0, xfl.getTextChars(), regular); HashCollection<String,Hashtable<String,String>> newTags = xfl.getTagHash(); if (newTags.size()>0){ adjudicationTask.addTagsFromHash(fullName, newTags); } } }catch(Exception ex){ hasFile=false; System.out.println("Error loading file"); System.out.println(ex.toString()); } if (tagButtons.getSelection()!=null){ String command = tagButtons.getSelection().getActionCommand(); assignTextColors(command); } } frame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); displayAnnotation.setCaretPosition(0); }//end start adjud else if (e.getActionCommand().equals("add file")){ int returnVal = fcFile.showOpenDialog(MaiGui.this); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fcFile.getSelectedFile(); try{ String fullName = file.getName(); frame.setTitle(frame.getTitle() + ", "+fullName); frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); //check to make sure the text is the same as the first file int textLen = displayAnnotation.getStyledDocument().getLength(); String text= displayAnnotation.getStyledDocument().getText(0,textLen); XMLFileLoader xfl = new XMLFileLoader(file); String text2 = xfl.getTextChars(); int textLen2 = text2.length(); if(textLen != textLen2){ throw new Exception("File length mismatch!"); } else{ if(text.equals(text2)==false){ throw new Exception("error matching text!"); } } updateMenus(); //check to make sure name isn't already there while(filenames.contains(fullName)){ fullName = "x"+fullName; } filenames.add(0,fullName); assignColors(fullName); //add the new file to the DB if (FileOperations.areTags(file)){ HashCollection<String,Hashtable<String,String>> newTags = xfl.getTagHash(); if (newTags.size()>0){ adjudicationTask.addTagsFromHash(fullName, newTags); } } //update the display resetInfoPanel(); if (tagButtons.getSelection()!=null){ String command = tagButtons.getSelection().getActionCommand(); assignTextColors(command); } }catch(Exception ex){ System.out.println("Error loading file"); System.out.println(ex.toString()); } } frame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); displayAnnotation.setCaretPosition(0); }//end addfile else if (e.getActionCommand().equals("add GS")){ int returnVal = fcFile.showOpenDialog(MaiGui.this); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fcFile.getSelectedFile(); try{ String fullName = file.getName(); frame.setTitle(frame.getTitle() + ", "+fullName); frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); //check to make sure the text is the same as the first file int textLen = displayAnnotation.getStyledDocument().getLength(); String text= displayAnnotation.getStyledDocument().getText(0,textLen); XMLFileLoader xfl = new XMLFileLoader(file); String text2 = xfl.getTextChars(); int textLen2 = text2.length(); if(textLen != textLen2){ throw new Exception("File length mismatch!"); } else{ if(text.equals(text2)==false){ throw new Exception("error matching text!"); } } String tempHack = "goldStandard.xml"; updateMenus(); if (FileOperations.areTags(file)){ HashCollection<String,Hashtable<String,String>> newTags = xfl.getTagHash(); if (newTags.size()>0){ adjudicationTask.addTagsFromHash(tempHack, newTags); } } //update the display resetInfoPanel(); adjudicationTask.findAllOverlaps(); if (tagButtons.getSelection()!=null){ String command = tagButtons.getSelection().getActionCommand(); assignTextColors(command); } }catch(Exception ex){ System.out.println("Error loading file"); System.out.println(ex.toString()); } } frame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); displayAnnotation.setCaretPosition(0); }//end addGS else if(e.getActionCommand().equals("start adjud folder")){ int returnVal = fcFolder.showOpenDialog(MaiGui.this); if (returnVal == JFileChooser.APPROVE_OPTION) { try{ filesSet = new ArrayList<String>(); File folder = fcFolder.getSelectedFile(); frame.setTitle(folder.getName()); File[] fileList = folder.listFiles(); filesSetOne = fileList; for(File file : fileList){ String filename = (file.getName().split("_"))[1]; folderOneInitial = (file.getName().split("_"))[0]; filesSet.add(filename); } if(filesSet.size() > 0) { hasFolder1 = true; current = 0; lbSerialNumber.setText((current+1) + " / " + filesSet.size()); System.out.println(" No: " + current); LoadFiles(current); System.out.println("Folder One files SET!!!"); } else { System.out.println("No files found in the folder....!"); return ; } }catch(Exception ex){ ex.printStackTrace(); } } }//end start adjud folder else if(e.getActionCommand().equals("add folder")){ int returnVal = fcFolder.showOpenDialog(MaiGui.this); if (returnVal == JFileChooser.APPROVE_OPTION) { try{ File folder = fcFolder.getSelectedFile(); File[] fileList = folder.listFiles(); //int count = 0; for(File file : fileList){ if(!filesSet.contains((file.getName().split("_"))[1])) { //System.out.println("Files in both the folder not matching...."); filesSet.add((file.getName().split("_"))[1]); folderTwoInitial = (file.getName().split("_"))[0]; } } if(fileList.length > 0 ){ hasFolder2 = true; filesSetTwo = fileList; current = 0; lbSerialNumber.setText((current+1) + " / " + filesSet.size()); System.out.println(" No: " + current); LoadFiles(current); System.out.println("Folder two files SET!!!"); } else{ System.out.println("No files found in current folder...!"); return ; } }catch(Exception ex){ ex.printStackTrace(); } } }//end add adjud folder else if(e.getActionCommand().equals("Save XML")){ fcSave.setSelectedFile(new File("goldStandard.xml")); int returnVal = fcSave.showSaveDialog(MaiGui.this); if(returnVal == JFileChooser.APPROVE_OPTION){ File file = fcSave.getSelectedFile(); String fullName = file.getName(); try{ FileOperations.saveAdjudXML(file,displayAnnotation,adjudicationTask); frame.setTitle(fullName); }catch(Exception e2){ System.out.println(e2.toString()); } } } }//end actionPerformed }//end class getFile /** * Handles the actions of Next and Previous buttons * */ private class getButtonActions implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if(hasFolder1==true) { int rowcount = checkifGoldStdrowPresent(); //System.out.println("Number of rows - " + rowcount); if(rowcount==0) { //delete this file //if(goldstdAdjudSet.contains(filesSet.get(current))){ File deletefile = new File("goldstdfiles\\" + filesSet.get(current)); if(deletefile.exists()) { //System.out.println(filesSet.get(current) + " exist!!!"); deletefile.delete(); } } if(e.getActionCommand() == "Next") { if(goldStdadded == true){ String filename = filesSet.get(current); //goldstdAdjudSet.put(filename, adjudicationTask); if(!goldstdAdjudSet.contains(filename)) { goldstdAdjudSet.add(filename); } //if(adjudicationTask.) FileOperations.saveAdjudXMLperfile(filename,displayAnnotation,adjudicationTask); goldStdadded = false; } current = (current + 1)%filesSet.size(); lbSerialNumber.setText((current + 1) + " / " + filesSet.size()); System.out.println(" No: " + current); LoadFiles(current); //System.out.println("Here in next btn click"); } else if(e.getActionCommand() =="Previous"){ if(goldStdadded==true){ String filename = filesSet.get(current); //goldstdAdjudSet.put(filename, adjudicationTask); if(!goldstdAdjudSet.contains(filename)) { goldstdAdjudSet.add(filename); } FileOperations.saveAdjudXMLperfile(filename,displayAnnotation,adjudicationTask); goldStdadded = false; } if(current <= 0) current = filesSet.size() - 1; else { current = (current - 1)%filesSet.size(); } lbSerialNumber.setText((current + 1) + " / " + filesSet.size()); System.out.println(" No: " + current); LoadFiles(current); //System.out.println("Here in previous btn click"); } } } } /** * Method to check the number of goldstd rows for this file * */ private int checkifGoldStdrowPresent(){ int count = 0; for(int i = 0;i<=displayAnnotation.getText().length();i++){ if(adjudicationTask.tagExistsInFileAtLoc("goldStandard.xml",i)){ //setColorAtLocation(Color.magenta,i,1,false); //System.out.println("Gold std found"); count++; //visitedLocs.putEnt(command,new Integer(i)); } } return count; } /** * Loading all the files * */ private void LoadFiles(int index) { String partialfilename = filesSet.get(index); File f1 = null; File f2=null; String Filename; if(hasFolder1) { Filename = folderOneInitial + "_" + partialfilename; for(int i=0;i<filesSetOne.length;i++){ if(filesSetOne[i].getName().equals(Filename)){ f1 = filesSetOne[i]; } } } if(hasFolder1 && hasFolder2) { Filename = folderTwoInitial + "_" + partialfilename; for(int i=0;i<filesSetTwo.length;i++){ if(filesSetTwo[i].getName().equals(Filename)){ f2 = filesSetTwo[i]; } } } if(f1 != null && f2 == null) { try{ frame.setTitle(f1.getName()); //hasFolder2 = true; updateMenus(); visitedLocs = new HashCollection<String,Integer>(); adjudicationTask.reset_db(); adjudicationTask.addDTDtoDB(); adjudicationTask.reset_IDTracker(); colorTable.clear(); colorTable.put("goldStandard.xml",Color.yellow); colorTable.put("allOtherFiles",Color.cyan); colorTable.put("someOtherFiles",Color.pink); Highlighter high = displayAnnotation.getHighlighter(); high.removeAllHighlights(); filenames = new ArrayList<String>(); filenames.add(f1.getName()); filenames.add("goldStandard.xml"); frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); displayAnnotation.setStyledDocument(new DefaultStyledDocument()); displayAnnotation.setContentType("text/plain; charset=UTF-8"); resetInfoPanel(); if (FileOperations.areTags(f1)){ XMLFileLoader xfl = new XMLFileLoader(f1); StyledDocument d = displayAnnotation.getStyledDocument(); Style def = StyleContext.getDefaultStyleContext().getStyle( StyleContext.DEFAULT_STYLE ); Style regular = d.addStyle( "regular", def ); d.insertString(0, xfl.getTextChars(), regular); HashCollection<String,Hashtable<String,String>> newTags = xfl.getTagHash(); if (newTags.size()>0){ adjudicationTask.addTagsFromHash(f1.getName(), newTags); } } }catch(Exception ex){ hasFile=false; System.out.println("Error loading file"); System.out.println(ex.toString()); } if (tagButtons.getSelection()!=null){ String command = tagButtons.getSelection().getActionCommand(); assignTextColors(command); } frame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); displayAnnotation.setCaretPosition(0); File goldstdfile = new File("goldstdfiles\\" + partialfilename); if(goldstdfile.exists()) { addGoldStdfile(goldstdfile); } } else if(f2!= null && f1==null) { try{ frame.setTitle(f2.getName()); //hasFolder2 = true; updateMenus(); visitedLocs = new HashCollection<String,Integer>(); adjudicationTask.reset_db(); adjudicationTask.addDTDtoDB(); adjudicationTask.reset_IDTracker(); // if(goldstdAdjudSet.containsKey(partialfilename)) // { // adjudicationTask = goldstdAdjudSet.get(partialfilename); // } colorTable.clear(); colorTable.put("goldStandard.xml",Color.yellow); colorTable.put("allOtherFiles",Color.cyan); colorTable.put("someOtherFiles",Color.pink); Highlighter high = displayAnnotation.getHighlighter(); high.removeAllHighlights(); filenames = new ArrayList<String>(); filenames.add(f2.getName()); filenames.add("goldStandard.xml"); frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); displayAnnotation.setStyledDocument(new DefaultStyledDocument()); displayAnnotation.setContentType("text/plain; charset=UTF-8"); resetInfoPanel(); if (FileOperations.areTags(f2)){ XMLFileLoader xfl = new XMLFileLoader(f2); StyledDocument d = displayAnnotation.getStyledDocument(); Style def = StyleContext.getDefaultStyleContext().getStyle( StyleContext.DEFAULT_STYLE ); Style regular = d.addStyle( "regular", def ); d.insertString(0, xfl.getTextChars(), regular); HashCollection<String,Hashtable<String,String>> newTags = xfl.getTagHash(); if (newTags.size()>0){ adjudicationTask.addTagsFromHash(f1.getName(), newTags); } } }catch(Exception ex){ hasFile=false; System.out.println("Error loading file"); System.out.println(ex.toString()); } if (tagButtons.getSelection()!=null){ String command = tagButtons.getSelection().getActionCommand(); assignTextColors(command); } frame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); displayAnnotation.setCaretPosition(0); File goldstdfile = new File("goldstdfiles\\" + partialfilename); if(goldstdfile.exists()) { addGoldStdfile(goldstdfile); } } else if(f1!=null && f2!=null) { try{ //loading 1st file frame.setTitle(f1.getName()); //hasFolder2 = true; updateMenus(); visitedLocs = new HashCollection<String,Integer>(); adjudicationTask.reset_db(); adjudicationTask.addDTDtoDB(); adjudicationTask.reset_IDTracker(); // if(goldstdAdjudSet.containsKey(partialfilename)) // { // adjudicationTask = goldstdAdjudSet.get(partialfilename); // } colorTable.clear(); colorTable.put("goldStandard.xml",Color.yellow); colorTable.put("allOtherFiles",Color.cyan); colorTable.put("someOtherFiles",Color.pink); Highlighter high = displayAnnotation.getHighlighter(); high.removeAllHighlights(); filenames = new ArrayList<String>(); filenames.add(f1.getName()); filenames.add("goldStandard.xml"); frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); displayAnnotation.setStyledDocument(new DefaultStyledDocument()); displayAnnotation.setContentType("text/plain; charset=UTF-8"); resetInfoPanel(); if (FileOperations.areTags(f1)){ XMLFileLoader xfl = new XMLFileLoader(f1); StyledDocument d = displayAnnotation.getStyledDocument(); Style def = StyleContext.getDefaultStyleContext().getStyle( StyleContext.DEFAULT_STYLE ); Style regular = d.addStyle( "regular", def ); d.insertString(0, xfl.getTextChars(), regular); HashCollection<String,Hashtable<String,String>> newTags = xfl.getTagHash(); if (newTags.size()>0){ adjudicationTask.addTagsFromHash(f1.getName(), newTags); } } if (tagButtons.getSelection()!=null){ String command = tagButtons.getSelection().getActionCommand(); assignTextColors(command); } frame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); displayAnnotation.setCaretPosition(0); //loading 2nd file String fullName = f2.getName(); frame.setTitle(f1.getName() + ", "+fullName); frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); //check to make sure the text is the same as the first file int textLen = displayAnnotation.getStyledDocument().getLength(); String text= displayAnnotation.getStyledDocument().getText(0,textLen); XMLFileLoader xfl = new XMLFileLoader(f2); String text2 = xfl.getTextChars(); int textLen2 = text2.length(); if(textLen != textLen2){ throw new Exception("File length mismatch!"); } else{ if(text.equals(text2)==false){ throw new Exception("error matching text!"); } } updateMenus(); //check to make sure name isn't already there while(filenames.contains(fullName)){ fullName = "x"+fullName; } filenames.add(0,fullName); assignColors(fullName); //add the new file to the DB if (FileOperations.areTags(f2)){ HashCollection<String,Hashtable<String,String>> newTags = xfl.getTagHash(); if (newTags.size()>0){ adjudicationTask.addTagsFromHash(fullName, newTags); } } //update the display resetInfoPanel(); if (tagButtons.getSelection()!=null){ String command = tagButtons.getSelection().getActionCommand(); assignTextColors(command); } }catch(Exception ex){ System.out.println("Error loading file"); System.out.println(ex.toString()); } frame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); displayAnnotation.setCaretPosition(0); File goldstdfile = new File("goldstdfiles\\" + partialfilename); if(goldstdfile.exists()) { addGoldStdfile(goldstdfile); } } } /** * */ private void addGoldStdfile(File goldstdfile){ try{ String fullName = goldstdfile.getName(); frame.setTitle(frame.getTitle() + ", "+fullName); frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); //check to make sure the text is the same as the first file int textLen = displayAnnotation.getStyledDocument().getLength(); String text= displayAnnotation.getStyledDocument().getText(0,textLen); XMLFileLoader xfl = new XMLFileLoader(goldstdfile); String text2 = xfl.getTextChars(); int textLen2 = text2.length(); if(textLen != textLen2){ throw new Exception("File length mismatch!"); } else{ if(text.equals(text2)==false){ throw new Exception("error matching text!"); } } String tempHack = "goldStandard.xml"; updateMenus(); if (FileOperations.areTags(goldstdfile)){ HashCollection<String,Hashtable<String,String>> newTags = xfl.getTagHash(); if (newTags.size()>0){ adjudicationTask.addTagsFromHash(tempHack, newTags); } } //update the display resetInfoPanel(); adjudicationTask.findAllOverlaps(); if (tagButtons.getSelection()!=null){ String command = tagButtons.getSelection().getActionCommand(); assignTextColors(command); } }catch(Exception ex){ System.out.println("Error loading file"); System.out.println(ex.toString()); } frame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); displayAnnotation.setCaretPosition(0); } /** * Listens for the command to increase/decrease the size of the font */ private class DisplayListener implements ActionListener{ public void actionPerformed(ActionEvent e){ String action = e.getActionCommand(); if (action.equals("Font++")){ Font font = displayAnnotation.getFont(); Font font2 = new Font(font.getName(),font.getStyle(),font.getSize()+1); displayAnnotation.setFont(font2); } if (action.equals("Font--")){ Font font = displayAnnotation.getFont(); Font font2 = new Font(font.getName(),font.getStyle(),font.getSize()-1); displayAnnotation.setFont(font2); } } } /** * Creates a highlighter object that can be added to the text display * */ private class TextHighlightPainter extends DefaultHighlighter.DefaultHighlightPainter { private TextHighlightPainter(Color color) { super(color); } } /** * Listens for the request from the Help Menu */ private class AboutListener implements ActionListener{ public void actionPerformed(ActionEvent e){ showAboutDialog(); } } /** * Listens to the table to determine if a button has been clicked * */ private class TableListener implements ListSelectionListener { public void valueChanged(ListSelectionEvent event) { if (event.getValueIsAdjusting()) { return; } //first, determine if we actually want to trigger an event if (!(tableRow == tagTable.getSelectedRow() && tableCol == tagTable.getSelectedColumn())){ //if we do, figure out what event we're triggering if (tagTable.getSelectedColumn()==tagTable.getColumnCount()-1){ ButtonEditor b = (ButtonEditor)tagTable.getCellEditor(tagTable.getSelectedRow(),tagTable.getSelectedColumn()); if (b.getLabel().startsWith("add")){ goldStdadded=true; checkForAddition(tagTable.getSelectedColumn(),tagTable.getSelectedRow()); } else if (b.getLabel().startsWith("copy")){ goldStdadded = true; //get data for new row and add directly to the GS String[]newdata = makeRow(tagTable.getSelectedColumn(),tagTable.getSelectedRow()); DefaultTableModel tableModel = (DefaultTableModel)tagTable.getModel(); int i = tableModel.getRowCount(); tableModel.addRow(newdata); checkForAddition(tagTable.getSelectedColumn(),i); } } } tableRow = tagTable.getSelectedRow(); tableCol = tagTable.getSelectedColumn(); } } /** * This is the class that's called whenever a * radio button is pressed. */ private class RadioButtonListener implements ActionListener{ public void actionPerformed(ActionEvent e){ resetInfoPanel(); assignTextColors(e.getActionCommand()); Highlighter high = displayAnnotation.getHighlighter(); high.removeAllHighlights(); } } /** * Listens to the table to determine when a tag is double-clicked, and * calls the function to highlight the related extents. Also determines * if the user right-clicked and should be given the option to remove * a tag from the database. * */ private class JTableListener extends MouseAdapter { public void mousePressed(MouseEvent e){ maybeShowRemovePopup(e); } public void mouseReleased(MouseEvent e) { maybeShowRemovePopup(e); } public void mouseClicked(MouseEvent e) { if(e.getClickCount()==2){ Highlighter high = displayAnnotation.getHighlighter(); try{ high.removeAllHighlights(); }catch(Exception b){ } String title = tagButtons.getSelection().getActionCommand(); Elem el = adjudicationTask.getElem(title); if(el instanceof ElemExtent){ try{ high.addHighlight(start,end,new TextHighlightPainter(Color.orange)); displayAnnotation.scrollRectToVisible(displayAnnotation.modelToView(start)); }catch (Exception b) { } }//end if ElemExtent if(el instanceof ElemLink){ //if a link is selected, the locations of the from and to anchors //need to be found and highlighted int selectedRow = tagTable.getSelectedRow(); String fromSelect = (String)tagTable.getValueAt(selectedRow,2); String toSelect = (String)tagTable.getValueAt(selectedRow,4); String fromLoc = adjudicationTask.getLocByFileAndID("goldStandard.xml",fromSelect); String toLoc = adjudicationTask.getLocByFileAndID("goldStandard.xml",toSelect); if (fromLoc != null){ String [] locs = fromLoc.split(","); int startSelect = Integer.parseInt(locs[0]); int endSelect = Integer.parseInt(locs[1]); try{ high.addHighlight(startSelect,endSelect+1,new TextHighlightPainter(Color.orange)); displayAnnotation.scrollRectToVisible(displayAnnotation.modelToView(startSelect)); }catch(Exception ex){ System.out.println(ex); } } if (toLoc != null){ String [] locs = toLoc.split(","); int startSelect = Integer.parseInt(locs[0]); int endSelect = Integer.parseInt(locs[1]); try{ high.addHighlight(startSelect,endSelect+1,new TextHighlightPainter(Color.orange)); }catch(Exception ex){ System.out.println(ex); } } }//end if ElemLink } } //if the user right-clicks on a link private void maybeShowRemovePopup(MouseEvent e) { if (e.isPopupTrigger()) { popup2 = removePopup(); popup2.show(e.getComponent(), e.getX(), e.getY()); } } } /** * Listens for mouse events in the text area; if the * mouse situation meets popup requirements, * give the option to create a new tag. * */ private class PopupListener extends MouseAdapter { public void mousePressed(MouseEvent e) { maybeShowPopup(e); } public void mouseReleased(MouseEvent e) { maybeShowPopup(e); } private void maybeShowPopup(MouseEvent e) { if (e.isPopupTrigger() && textSelected){ popup1 = populatePopup(); popup1.show(e.getComponent(), e.getX(), e.getY()); } } } /** * If the user decides to remove the highlighted table rows, * this method is called. It removes the tags from the table * as well as the database, and for extent tags it also * removes any link tags the extent is participating in. * */ private class removeSelectedTableRows implements ActionListener{ public void actionPerformed(ActionEvent actionEvent) { boolean check = showDeleteWarning(); if (check){ goldStdadded = true; String action = tagButtons.getSelection().getActionCommand(); Elem elem = adjudicationTask.getElem(action); int[] selectedViewRows = tagTable.getSelectedRows(); //convert the rows of the table view into the rows of the //table model so that the correct rows are deleted int[] selectedRows = new int[selectedViewRows.length]; for (int i=0;i<selectedRows.length;i++){ selectedRows[i]=tagTable.convertRowIndexToModel(selectedViewRows[i]); } DefaultTableModel tableModel = (DefaultTableModel)tagTable.getModel(); //find the id column int cols = tableModel.getColumnCount(); int idCol = -1; int sourceCol = -1; for(int i=0;i<cols;i++){ String colname = tableModel.getColumnName(i); if(colname.equalsIgnoreCase("id")){ idCol = i; } if(colname.equalsIgnoreCase("source")){ sourceCol = i; } } //get the id for each selected row and remove id String id = ""; String source = ""; for (int i=selectedRows.length-1;i>=0;i--){ int row = selectedRows[i]; id = (String)tableModel.getValueAt(row,idCol); source = (String)tableModel.getValueAt(row,sourceCol); //don't want to delete tags that come from the files //being adjudicated if (source.equalsIgnoreCase("goldStandard.xml")){ if(elem instanceof ElemExtent){ adjudicationTask.removeExtentByFileAndID(source,action,id); int start = Integer.parseInt(((String)tableModel.getValueAt(row,2))); int end = Integer.parseInt(((String)tableModel.getValueAt(row,3))); assignTextColor(action,start,end); HashCollection<String,String> links = adjudicationTask.getLinksByFileAndExtentID(source,action,id); //remove links that use the tag being removed ArrayList<String> keys = links.getKeyList(); for (int k=0;k<keys.size();k++){ String tag = keys.get(k); ArrayList<String> ids = links.get(tag); for(int j=0;j<ids.size();j++){ String idl = ids.get(j); adjudicationTask.removeLinkByFileAndID(source,tag,idl); } //also, remove those locations from the visitedLocs //HashCollection ArrayList<Integer> vlocs = visitedLocs.get(tag); for(int j=start;j<=end;j++){ vlocs.remove(new Integer(j)); } } } else{ adjudicationTask.removeLinkByFileAndID(source,action,id); } tableModel.removeRow(selectedRows[i]); } } if(elem instanceof ElemExtent){ assignTextColors(action); } } } } /** * Keeps track of whether the CTRL key (or the equivalent Mac key) * is being pressed in order to determine if the link creation window * should be displayed. */ private class ModKeyListener implements KeyListener{ public void keyPressed(KeyEvent e) { int keyCode = e.getKeyCode(); String p = System.getProperty("os.name"); if(p.toLowerCase().contains("mac")){ if (keyCode == 18 || keyCode == 157){ ctrlPressed = true; } } else{ if ( keyCode == 17){ ctrlPressed = true; } } } public void keyReleased(KeyEvent e){ String p = System.getProperty("os.name"); int keyCode = e.getKeyCode(); if(p.toLowerCase().contains("mac")){ if (keyCode == 18 || keyCode == 157){ ctrlPressed = false; } } else{ if ( keyCode == 17){ ctrlPressed = false; } } } public void keyTyped(KeyEvent e){ //do nothing } } /** * Keeps track of what extents in the text are highlighted by the user * in order to refresh the tag tables, and assigns highlights based * on the tag and extent selected. * */ private class AnnCaretListener implements CaretListener{ public void caretUpdate(CaretEvent e) { Highlighter high = displayAnnotation.getHighlighter(); high.removeAllHighlights(); tagTable.getColumnModel().getSelectionModel().removeListSelectionListener(tablelistener); tagTable.getSelectionModel().removeListSelectionListener(tablelistener); tableRow = -1; tableCol = -1; resetInfoPanel(); int dot = e.getDot(); int mark = e.getMark(); if((ctrlPressed==true) && (loc1 == -1)){ loc1 = dot; } else if(ctrlPressed==true && loc1 != -1){ showLinkWindow(loc1,dot); ctrlPressed = false; loc1=-1; } if (dot!=mark){ textSelected=true; if(dot<mark){ start=dot; end=mark; } else{ start=mark; end=dot; } mouseLabel.setText("Highlighted text: "+ Integer.toString(start) +","+Integer.toString(end)+")"); findRelatedTags(); try{ high.addHighlight(start, end, DefaultHighlighter.DefaultPainter); }catch(BadLocationException b){ } } else{ textSelected=false; start=-1; end=-1; mouseLabel.setText("Highlighted text: (-1,-1)"); } } }//end AnnCaretListener /** * A quick and dirty way to change global variables based * on what's going on in the link creation window so that * a new link can be created more easily. * */ private class jboxListener implements ActionListener{ public void actionPerformed(ActionEvent e){ JComboBox box = (JComboBox)e.getSource(); String select = (String)box.getSelectedItem(); if (e.getActionCommand() == "fromID"){ linkFrom = select; } else if (e.getActionCommand() == "link"){ linkName = select; } else if (e.getActionCommand() == "toID"){ linkTo = select; } } } /** * This is the class that's associated with the make link button * in the popup window created in showLinkWindow() * */ private class linkListener implements ActionListener{ public void actionPerformed(ActionEvent e){ clearTableSelections(); //check to make sure that linkFrom, linkName, and linkTo //are all valid ids/link names linkFrom = linkFrom.split(" \\(")[0]; String from_id = linkFrom.split(" - ")[1]; String from_type = linkFrom.split(" - ")[0]; linkTo = linkTo.split(" \\(")[0]; String to_id = linkTo.split(" - ")[1]; String to_type = linkTo.split(" - ")[0]; String from_text = adjudicationTask.getTextByFileElemAndID("goldStandard.xml",from_type,from_id); String to_text = adjudicationTask.getTextByFileElemAndID("goldStandard.xml",to_type,to_id); //add link to appropriate table DefaultTableModel tableModel = (DefaultTableModel)tagTable.getModel(); String[] newdata = new String[tableModel.getColumnCount()]; for(int i=0;i<tableModel.getColumnCount();i++){ newdata[i]=""; } //get the Elem that the table was based on, and go through //the attributes. Put in the start and end bits Hashtable<String,Elem> elements = adjudicationTask.getElemHash(); Elem elem = elements.get(linkName); //get ID number for link String newID = ""; for(int k=0;k<tableModel.getColumnCount();k++){ String colName = tableModel.getColumnName(k); if(colName.equals("id")){ newID=adjudicationTask.getNextID(elem.getName(),"goldStandard.xml"); newdata[k]=newID; } else if(colName.equals("fromID")){ newdata[k]=from_id; } else if(colName.equals("toID")){ newdata[k]=to_id; } else if(colName.equals("fromText")){ newdata[k]=from_text; } else if(colName.equals("toText")){ newdata[k]=to_text; } else if (colName.equals("source")){ newdata[k] = "goldStandard.xml"; } } newdata[tableModel.getColumnCount()-1] = "add/moddify"; tableModel.addRow(newdata); tagTable.clearSelection(); tagTable.setRowSelectionInterval(tableModel.getRowCount()-1,tableModel.getRowCount()-1); Rectangle rect = tagTable.getCellRect(tableModel.getRowCount()-1, 0, true); tagTable.scrollRectToVisible(rect); //add the new tag to the database addRowToGoldStandard(0,tableModel.getRowCount()-1,elem); //reset variables linkFrom=""; linkName=""; linkTo=""; linkFrame.setVisible(false); } } //end of classes section //******************************************************** /** * Assigns colors to each file being adjudicated. * * @param filename */ private void assignColors(String filename){ //assigns int col = colorTable.size(); int cols = colors.length; if (col>=cols){ col = col%cols; } colorTable.put(filename,colors[col]); } /** * This is the class that's called when an extent tag is * selected from the popup menu * */ private class MakeTagListener implements ActionListener{ public void actionPerformed(ActionEvent actionEvent) { clearTableSelections(); String action = actionEvent.getActionCommand(); //if the tag being added is non-consuming, make sure //start and end are set to -1 if(action.contains("NC-")){ start=-1; end=-1; action = action.split("-")[1]; } DefaultTableModel tableModel = (DefaultTableModel)tagTable.getModel(); //clear out the rest of the table tableModel.getDataVector().removeAllElements(); //create array for data for row*/ String[] newdata = new String[tableModel.getColumnCount()]; for(int i=0;i<tableModel.getColumnCount();i++){ newdata[i]=""; } //get the Elem that the table was based on, and go through // the attributes. Put in the start and end bits Hashtable<String,Elem> elements = adjudicationTask.getElemHash(); Elem elem = elements.get(action); //get ID number. This also isn't as hard-coded as it looks: // the columns for the table are created from the Attributes array list String newID = ""; ArrayList<Attrib> attributes = elem.getAttributes(); for(int i=0;i<attributes.size();i++){ if(attributes.get(i) instanceof AttID){ newID=adjudicationTask.getNextID(elem.getName(),"goldStandard.xml"); newdata[i+1]=newID; } if(attributes.get(i).hasDefaultValue()){ newdata[i+1]=attributes.get(i).getDefaultValue(); } } //put in start and end values if (elem instanceof ElemExtent){ attributes = elem.getAttributes(); for(int k=0;k<tableModel.getColumnCount();k++){ String colName = tableModel.getColumnName(k); //this isn't as hard-coded as it looks, because //all extent elements have these attributes if (colName.equals("start")){ newdata[k]=Integer.toString(start); } else if (colName.equals("end")){ newdata[k]=Integer.toString(end); } else if (colName.equals("text") && start != -1){ newdata[k] = getText(start,end); } else if (colName.equals("source")){ newdata[k] = "goldStandard.xml"; } } newdata[tableModel.getColumnCount()-1] = "add/moddify"; tableModel.addRow(newdata); tagTable.clearSelection(); tagTable.setRowSelectionInterval(tableModel.getRowCount()-1,tableModel.getRowCount()-1); Rectangle rect = tagTable.getCellRect(tableModel.getRowCount()-1, 0, true); tagTable.scrollRectToVisible(rect); addRowToGoldStandard(0,tableModel.getRowCount()-1,elem); if(start!=-1){ assignTextColor(action,start,end); } } } } /** * fetches the string from the text panel based on character offsets * * @param start the start of the span * @param end the end of the span * @return the text at the specified location */ private String getText(int start, int end){ DefaultStyledDocument styleDoc = (DefaultStyledDocument)displayAnnotation.getStyledDocument(); String text = ""; try{ text = styleDoc.getText(start,end-start); }catch(Exception e){ System.out.println(e.toString()); } return text; } /** * Updates the colors in the text area when a new tag is chosen from the radio buttons * * When a tag is selected, the colors are based on which/how many * files include it in the annotation (if it's in the Gold Standard, the * text is green, if it's in all the files but the Gold Standard the text * is blue, and if it's some but not all the files the text is red). * * @param tagname The name of the selected tag */ private void assignTextColors(String tagname){ //reset all text to black, then set new colors setColorAtLocation(Color.black,0,displayAnnotation.getStyledDocument().getLength(),false); //check to see if the tagname is a non-consuming tag if(tagname.startsWith("NC-")){ //no colors will be set if an non-consuming tag is chosen; instead //skip straight to filling in the table String command = tagname.substring(3); HashCollection<String,String> idHash = adjudicationTask.getTagsSpanByType(-1, -1,command); fillInTable(idHash,command); } else{ Elem e = adjudicationTask.getElem(tagname); if (e instanceof ElemExtent){ HashCollection<String,String>elems = adjudicationTask.getExtentAllLocs(tagname); ArrayList<String> locations = elems.getKeyList(); for (int i=0;i<locations.size();i++) { String location = locations.get(i); ArrayList<String> files = elems.getList(location); if (files.contains("goldStandard.xml")){ setColorAtLocation(Color.green,Integer.parseInt(location),1,false); } else if (files.size()>0){ boolean allfiles = true; for(int f=0;f<filenames.size();f++){ if(files.contains(filenames.get(f))==false && filenames.get(f).equals("goldStandard.xml")==false){ allfiles = false; } } if (allfiles==true){ setColorAtLocation(Color.blue,Integer.parseInt(location),1,false); } else{ setColorAtLocation(Color.red,Integer.parseInt(location),1,false); } } } } else{//if selected tag is a link //first, get all the places where there are extent tags in the //gold standard Hashtable<String,String> allLocs = adjudicationTask.getAllExtentsByFile("goldStandard.xml"); for (Enumeration<String> locs = allLocs.keys(); locs.hasMoreElements();){ int loc = Integer.parseInt(locs.nextElement()); setColorAtLocation(Color.lightGray,loc,1,false); } //then, figure out what extents are already in links and //highlight them appropriately HashCollection<String,String>elems = adjudicationTask.findGoldStandardLinksByType(tagname); ArrayList<String> locations = elems.getKeyList(); for (int i=0;i<locations.size();i++) { String location = locations.get(i); ArrayList<String> files = elems.getList(location); if (files.contains("goldStandard.xml")){ setColorAtLocation(Color.green,Integer.parseInt(location),1,false); } else if (files.size()>0){ boolean allfiles = true; for(int f=0;f<filenames.size();f++){ if(files.contains(filenames.get(f))==false && filenames.get(f).equals("goldStandard.xml")==false){ allfiles = false; } } if (allfiles==true){ setColorAtLocation(Color.blue,Integer.parseInt(location),1,false); } else{ setColorAtLocation(Color.red,Integer.parseInt(location),1,false); } } } //finally, go over everything that's already been looked at colorVisitedLocs(tagname); } } } /** * Goes over the text when a link is selected and colors the locations * that the adjudicator has already examined. * * @param tagname that tag that's been selected */ private void colorVisitedLocs(String tagname){ ArrayList<Integer> visitlocs = visitedLocs.get(tagname); if(visitlocs !=null){ for(int i=0;i<visitlocs.size();i++){ setColorAtLocation(Color.magenta,visitlocs.get(i).intValue(),1,false); } } } /** * This method is for coloring/underlining text * in the text window. It detects overlaps, and * should be called every time a tag is added * or removed. * * @param tagname the selected tagname * @param beginColor the beginning of the text span being assigned a color * @param endColor the end of the text span being assigned a color */ private void assignTextColor(String tagname, int beginColor, int endColor){ // go through each part of the word being changed and // find what tags are there, and what color it should be. Elem e = adjudicationTask.getElem(tagname); if (e instanceof ElemExtent){ for(int i=0;i<endColor-beginColor;i++){ ArrayList<String>files = adjudicationTask.getFilesAtLocbyElement(tagname,beginColor+i); //if there is a gold standard tag in that location, the text will be gree if (files.contains("goldStandard.xml")){ setColorAtLocation(Color.green,beginColor+i,1,false); } else if (files.size()>0){ boolean allfiles = true; // check to see if there's a tag at that location from each // of the files being adjudicated for(int f=0;f<filenames.size();f++){ if(files.contains(filenames.get(f))==false && filenames.get(f).equals("goldStandard.xml")==false){ allfiles = false; } } //if a tag exists in all files, the text is blue if (allfiles==true){ setColorAtLocation(Color.blue,beginColor+i,1,false); } //otherwise it's red else{ setColorAtLocation(Color.red,beginColor+i,1,false); } } else{ setColorAtLocation(Color.black,beginColor+i,1,false); } } } } /** * Used to set the text in a span to a determined color * * @param color the color being assigned * @param s the start of the span * @param e the end of the span * @param b whether or not the text will be underlined */ private void setColorAtLocation(Color color, int s, int e, boolean b){ DefaultStyledDocument styleDoc = (DefaultStyledDocument)displayAnnotation.getStyledDocument(); SimpleAttributeSet aset = new SimpleAttributeSet(); StyleConstants.setForeground(aset, color); StyleConstants.setUnderline(aset, b); styleDoc.setCharacterAttributes(s,e,aset,false); } /** * Creates the popup menu that allows users to create new * tags from the text window * @return popup menu */ private JPopupMenu populatePopup(){ JPopupMenu jp = new JPopupMenu(); //create a menuitem for the selected RadioButton String name = tagButtons.getSelection().getActionCommand(); JMenuItem menuItem = new JMenuItem(name); menuItem.addActionListener(new MakeTagListener()); jp.add(menuItem); return jp; } /** * Shows the warning when deleting a tag. This will be * displayed even if the extent does not participate in any links. * @return true or false */ private boolean showDeleteWarning(){ String text = ("Deleting extent tag(s) will also delete \n" + "any links that use these extents. Would you like to continue?"); int message = JOptionPane.showConfirmDialog(frame, text, "Warning!", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); if (message==0){ return true; } return false; } /** * Fills in the table based on the extent selected in the text window */ private void findRelatedTags(){ //first, get files and ids of elements in selected extents by type\ if (tagButtons.getSelection()!=null){ String command = tagButtons.getSelection().getActionCommand(); Elem e = adjudicationTask.getElem(command); if (e instanceof ElemExtent){ HashCollection<String,String> idHash = adjudicationTask.getTagsSpanByType(start, end,command); fillInTable(idHash,command); } else if(e instanceof ElemLink){ //for location between start and end, if there is an extent tag //there in the gold standard, change color to magenta and add //to visitedLocs for(int i = start;i<=end;i++){ if(adjudicationTask.tagExistsInFileAtLoc("goldStandard.xml",i)){ setColorAtLocation(Color.magenta,i,1,false); visitedLocs.putEnt(command,new Integer(i)); } } HashCollection<String,Hashtable<String,String>> idHash = adjudicationTask.getLinkTagsSpanByType(start,end,command); fillInLinkTable(idHash,command); } else{ //do nothing, it's a non-consuming tag } } } /** * Removes the bottom table and creates a new one based on the * selected tag. */ private void resetInfoPanel(){ infoPanel.removeAll(); JComponent tableComp = makeTable(); infoPanel.add(tableComp); infoPanel.updateUI(); } /** * Builds and displays the link creation window by getting the tags * at the two locations the user clicked while holding the CTRL key * * @param loc the first location clicked * @param loc2 the second location clicked */ private void showLinkWindow(int loc, int loc2){ JPanel linkPane = new JPanel(new BorderLayout()); JPanel boxPane = new JPanel(new GridLayout(3,2)); linkFrame = new JFrame(); //first, get all the tags in the gold standard at the first location //non-consuming tags are included, because those can also be linked to/from JComboBox fromList = new JComboBox(); fromList.addActionListener(new jboxListener()); fromList.setActionCommand("fromID"); HashCollection<String,String> idHash = adjudicationTask.getFileTagsSpanAndNC("goldStandard.xml",loc,loc+1); ArrayList<String> elements = idHash.getKeyList(); if (elements.size()>0){ if (elements.size()>1){ fromList.addItem(""); } for(int i=0; i<elements.size();i++){ ArrayList<String> tags = idHash.get(elements.get(i)); for(int j=0;j<tags.size();j++){ //create the string for the table list String puttag = (elements.get(i) + " - " + tags.get(j)); //get the text for the words by id and element String text = adjudicationTask.getTextByFileElemAndID("goldStandard.xml",elements.get(i),tags.get(j)); puttag = puttag + " ("+text+")"; //add string to JComboBox fromList.addItem(puttag); } } } //the, create the combobox that contains the link types //(in MAI, this is the tag that's been selected, not all the link tags) JComboBox linkList = new JComboBox(); linkList.setActionCommand("link"); linkList.addActionListener(new jboxListener()); linkList.addItem(tagButtons.getSelection().getActionCommand()); //then, fill in the tag and NC information for the second location JComboBox toList = new JComboBox(); toList.setActionCommand("toID"); toList.addActionListener(new jboxListener()); idHash = adjudicationTask.getFileTagsSpanAndNC("goldStandard.xml",loc2,loc2+1); elements = idHash.getKeyList(); if (elements.size()>0){ if (elements.size()>1){ toList.addItem(""); } for(int i=0; i<elements.size();i++){ ArrayList<String> tags = idHash.get(elements.get(i)); for(int j=0;j<tags.size();j++){ String puttag = (elements.get(i) + " - " + tags.get(j)); //get the text for the words by id and element String text = adjudicationTask.getTextByFileElemAndID("goldStandard.xml",elements.get(i),tags.get(j)); puttag = puttag + " ("+text+")"; toList.addItem(puttag); } } } //pack everything into the window and make it visible JButton makeLink = new JButton("Create Link"); makeLink.addActionListener(new linkListener()); boxPane.add(new JLabel("Link from:")); boxPane.add(fromList); boxPane.add(new JLabel("Link type:")); boxPane.add(linkList); boxPane.add(new JLabel("Link to:")); boxPane.add(toList); linkPane.add(boxPane,BorderLayout.CENTER); linkPane.add(makeLink,BorderLayout.SOUTH); linkFrame.setBounds(90,70,400,300); linkFrame.getContentPane().add(linkPane); linkFrame.setVisible(true); } /** * Creates the table and table model for the data that will be displayed * based on the selected RadioButton. */ private JComponent makeTable(){ AnnTableModel model = new AnnTableModel(); model.setGoldStandardName("goldStandard.xml"); tagTable = new AnnJTable(model); JScrollPane scroll = new JScrollPane(tagTable); tagTable.addMouseListener(new JTableListener()); //check to make sure that a tag has been selected if (tagButtons.getSelection()!=null){ String tagCommand = tagButtons.getSelection().getActionCommand(); if(tagCommand.startsWith("NC-")){ tagCommand = tagCommand.substring(3); } Elem e = adjudicationTask.getElem(tagCommand); ArrayList<Attrib> attributes = e.getAttributes(); //for some reason, it's necessary to add the columns first, //then go back and add the cell renderers. model.addColumn("source"); for (int i=0;i<attributes.size();i++){ model.addColumn(attributes.get(i).getName()); } model.addColumn("action"); for (int i=0;i<attributes.size();i++){ Attrib a = attributes.get(i); TableColumn c = tagTable.getColumnModel().getColumn(i+1); if (a instanceof AttList){ AttList att = (AttList)a; JComboBox options = makeComboBox(att); c.setCellEditor(new DefaultCellEditor(options)); } } //add buttons to end of rows TableColumn c= tagTable.getColumnModel().getColumn(tagTable.getColumnCount()-1); c.setCellRenderer(new ButtonRenderer()); c.setCellEditor(new ButtonEditor(new JCheckBox())); } //need to add the same listener to both, //otherwise the table events won't trigger correctly tagTable.getSelectionModel().addListSelectionListener(tablelistener); tagTable.getColumnModel().getSelectionModel().addListSelectionListener(tablelistener); return(scroll); } /** * Link tables are more complicated to fill in because they require that the * links from the files being adjudicated contain the IDs and text of the overlapping * tags from the goldStandard * * @param idHash the hashtable containing IDs * @param tagname the name of the tag whose information is being filled in */ private void fillInLinkTable(HashCollection<String,Hashtable<String,String>> idHash, String tagname){ //first, clear out existing table and listener, otherwise the changes to the table //trigger conflicting events tagTable.getColumnModel().getSelectionModel().removeListSelectionListener(tablelistener); tagTable.getSelectionModel().removeListSelectionListener(tablelistener); tableRow = -1; tableCol = -1; DefaultTableModel tableModel = (DefaultTableModel)tagTable.getModel(); tableModel.getDataVector().removeAllElements(); //idHash is a HashCollection containing the filenames as keys //and HaahTables with attribute info as data String[] newdata = new String[tableModel.getColumnCount()]; ArrayList<String> keys = idHash.getKeyList(); for(int i=0;i<keys.size();i++){ String source = keys.get(i); ArrayList<Hashtable<String,String>>links = idHash.getList(source); if(links!=null){ for(int j=0;j<links.size();j++){ Hashtable<String,String> attributes = links.get(j); newdata[0] = source; for(int k=1;k<tableModel.getColumnCount();k++){ String colName = tableModel.getColumnName(k); String value = attributes.get(colName); if(value!=null){ newdata[k]=value; } else{ newdata[k]=""; } } //create the appropriate buttons if (source.equals("goldStandard.xml")){ newdata[tableModel.getColumnCount()-1]="add/modify"; } else{ newdata[tableModel.getColumnCount()-1]="copy to GS"; } tableModel.addRow(newdata); } } } //also, highlight the appropriate related extents HashCollection<String,String> currentHighlights = adjudicationTask.getCurrentHighlights(); //keep the gold standard highlights separate for dealing with afterwards ArrayList<String>gsLocs = currentHighlights.get("goldStandard.xml"); currentHighlights.remove("goldStandard.xml"); Highlighter high = displayAnnotation.getHighlighter(); high.removeAllHighlights(); if(gsLocs!=null){ for(int i=0;i<gsLocs.size();i++){ String loc = gsLocs.get(i); //split the string into start and end ints int start = Integer.parseInt(loc.split("@#@")[0]); int end = Integer.parseInt(loc.split("@#@")[1]); //now, add those to the highlighter try{ high.addHighlight(start,end,new TextHighlightPainter(colorTable.get("goldStandard.xml"))); }catch(BadLocationException b){ System.out.println(b); } } } ArrayList<String> files = currentHighlights.getKeyList(); for (int i=0;i<files.size();i++){ String file = files.get(i); ArrayList<String> highLocs = currentHighlights.get(file); for(int j=0;j<highLocs.size();j++){ String loc = highLocs.get(j); //split the string into start and end ints int start = Integer.parseInt(loc.split("@#@")[0]); int end = Integer.parseInt(loc.split("@#@")[1]); //now, add those to the highlighter try{ high.addHighlight(start,end,new TextHighlightPainter(colorTable.get(file))); }catch(BadLocationException b){ System.out.println(b); } } } //add the listeners back to the table tagTable.getSelectionModel().addListSelectionListener(tablelistener); tagTable.getColumnModel().getSelectionModel().addListSelectionListener(tablelistener); } /** * Fills in the table when an extent tag is selected from the * RadioButtons and a new span is highlighted in the text area. * * @param idHash a HashCollection containing relevent IDs * @param tagname the type of the tag information being filled in */ private void fillInTable(HashCollection<String,String> idHash, String tagname){ //first, clear out existing table and listener, otherwise the changes to the table //trigger conflicting events tagTable.getColumnModel().getSelectionModel().removeListSelectionListener(tablelistener); tagTable.getSelectionModel().removeListSelectionListener(tablelistener); tableRow = -1; tableCol = -1; DefaultTableModel tableModel = (DefaultTableModel)tagTable.getModel(); tableModel.getDataVector().removeAllElements(); //idHash is a HashCollection containing the filenames as keys and tag ids //as data String[] newdata = new String[tableModel.getColumnCount()]; ArrayList<String> keys = idHash.getKeyList(); //for each file source, add all tags in the idHash for(int i=0;i<keys.size();i++){ String source = keys.get(i); ArrayList<String>ids=idHash.getList(source); if(ids!=null){ for(int j=0;j<ids.size();j++){ Hashtable<String,String> ht = adjudicationTask.getTagsByFileAndID(tagname,ids.get(j),source); newdata[0]=source; for(int k=1;k<tableModel.getColumnCount();k++){ String colName = tableModel.getColumnName(k); String value = ht.get(colName); if(value!=null){ newdata[k]=value; } else{ newdata[k]=""; } } if (source.equals("goldStandard.xml")){ newdata[tableModel.getColumnCount()-1]="add/modify"; } else{ newdata[tableModel.getColumnCount()-1]="copy to GS"; } tableModel.addRow(newdata); } } } tagTable.getSelectionModel().addListSelectionListener(tablelistener); tagTable.getColumnModel().getSelectionModel().addListSelectionListener(tablelistener); } /** * If a new file is being added to the gold standard, this method * checks to make sure all the necessary information is there. * * @param col the column where the "add" button was pressed (will be 0 * if this is being called from somewhere outside the tag display table) * @param buttonRow the row being checked for inclusion to the gold standard */ private void checkForAddition(int col, int buttonRow){ //get array of tag attributes String tagCommand = tagButtons.getSelection().getActionCommand(); //if we're dealing with an NC tag, the checks are the same as a regular tag //but the triggering command is different and needs to be fixed. if(tagCommand.startsWith("NC-")){ tagCommand = tagCommand.substring(3); } Elem e = adjudicationTask.getElem(tagCommand); if(e instanceof ElemExtent){ //check for start boolean hasStart = false; boolean hasEnd = false; //TO DO: make this checking more robust: check that //start and end are integers, that start comes before //end and that both are within the bounds of the text for (int i=0;i<tagTable.getColumnCount();i++){ String header = tagTable.getColumnName(i); if (header.equals("start")){ String val = (String)tagTable.getValueAt(buttonRow,i); if(val!=""){ hasStart=true; } } else if (header.equals("end")){ String val = (String)tagTable.getValueAt(buttonRow,i); if(val!=""){ hasEnd=true; } } } if (hasStart && hasEnd){ addRowToGoldStandard(col,buttonRow,e); } else{ JOptionPane.showMessageDialog(tagTable,"parameters missing"); } } else{//if it's a link boolean hasFromID = false; boolean hasToID = false; for (int i=0;i<tagTable.getColumnCount();i++){ String header = tagTable.getColumnName(i); if (header.equals("fromID")){ String val = (String)tagTable.getValueAt(buttonRow,i); if(val!=""){ hasFromID=true; } } else if (header.equals("toID")){ String val = (String)tagTable.getValueAt(buttonRow,i); if(val!=""){ hasToID=true; } } } if(hasFromID && hasToID){ addRowToGoldStandard(col,buttonRow,e); }else{ JOptionPane.showMessageDialog(tagTable,"parameters missing"); } } } /** * Adds a new row to the gold standard, or resubmits an existing row * if attributes have been changed. * * @param col the column of the button that triggered this method being called * (0 if the table was not used) * @param buttonRow the row being added/modified * @param e the type of tag being added */ private void addRowToGoldStandard(int col, int buttonRow, Elem e){ boolean hasID = false; String id = ""; int idLoc = -1; for (int i=0;i<tagTable.getColumnCount();i++){ String header = tagTable.getColumnName(i); if (header.equals("id")){ idLoc = i; id = (String)tagTable.getValueAt(buttonRow,i); if (id!=""){ hasID = true; } } } if (hasID){ //remove previous tag from DB //this might not be necessary if the start and end aren't being //changed if (e instanceof ElemExtent){ adjudicationTask.removeExtentByFileAndID("goldStandard.xml", e.getName(),id); } else{ adjudicationTask.removeLinkByFileAndID("goldStandard.xml", e.getName(),id); } } else{ //if no id exists in the row, get the next one id = adjudicationTask.getNextID(e.getName(),"goldStandard.xml"); tagTable.setValueAt(id,buttonRow,idLoc); } //create hashtable of element attributes Hashtable<String,String> tag = new Hashtable<String,String>(); if (e instanceof ElemExtent){ int startT = -1; int endT = -1; for (int i=0;i<tagTable.getColumnCount();i++){ String header = tagTable.getColumnName(i); tag.put(header,(String)tagTable.getValueAt(buttonRow,i)); if (header.equals("start")){ startT = Integer.parseInt((String)tagTable.getValueAt(buttonRow,i)); } if (header.equals("end")){ endT = Integer.parseInt((String)tagTable.getValueAt(buttonRow,i)); } } //add the column to the DB adjudicationTask.addTagFromHash("goldStandard.xml",e,tag); //color the new location appropriately assignTextColor(e.getName(),startT,endT); } else{//if it's a link for (int i=0;i<tagTable.getColumnCount();i++){ String header = tagTable.getColumnName(i); tag.put(header,(String)tagTable.getValueAt(buttonRow,i)); } //add the column to the DB adjudicationTask.addTagFromHash("goldStandard.xml",e,tag); String command = tagButtons.getSelection().getActionCommand(); assignTextColors(command); } } /** * remove all highlights from rows */ private void clearTableSelections(){ DefaultTableModel tableModel = (DefaultTableModel)tagTable.getModel(); int rows = tableModel.getRowCount(); if(rows>0) tagTable.removeRowSelectionInterval(0,rows-1); } /** * Creates a new row for the Gold Standard, usually from a button click from the table. * * @param col the column where the clicked button exists * @param row the row being copied to the Gold Standard * @return an array of the correct size with the some of the information filled in */ private String[] makeRow(int col, int row){ DefaultTableModel tableModel = (DefaultTableModel)tagTable.getModel(); String[] newdata = new String[tableModel.getColumnCount()]; for (int i=0;i<tableModel.getColumnCount()-1;i++){ if(i==0){ newdata[i]="goldStandard.xml"; } else if (tagTable.getColumnName(i).equals("id")){ newdata[i]=""; } else{ newdata[i] = (String)tagTable.getValueAt(row,i); } } newdata[tableModel.getColumnCount()-1]="add/modify"; return newdata; } /** * The pop-up that appears when a tag table is right-clicked to give the * user the option to delete tags from the gold standard * * @return popup menu */ private JPopupMenu removePopup(){ JPopupMenu jp = new JPopupMenu(); String title = tagButtons.getSelection().getActionCommand(); if(title.startsWith("NC-")){ title = title.substring(3); } String action = "Remove selected " + title + " rows"; JMenuItem menuItem = new JMenuItem(action); menuItem.setActionCommand(title); menuItem.addActionListener(new removeSelectedTableRows()); jp.add(menuItem); return jp; } /** * Provides information about MAI */ private void showAboutDialog(){ JOptionPane about = new JOptionPane(); about.setLocation(100,100); about.setAlignmentX(Component.CENTER_ALIGNMENT); about.setAlignmentY(Component.CENTER_ALIGNMENT); String text = ("MAI \nMulti-document Adjudication Interface \nVersion 0.7.1 \n\n" + "Copyright Amber Stubbs\nastubbs@cs.brandeis.edu \n Lab for " + "Linguistics and Computation, Brandeis University 2010-2012." + "\n\nThis distribution of MAI (the software and the source code) \n" + " is covered under the GNU General Public License version 3.\n" + "http://www.gnu.org/licenses/"); JOptionPane.showMessageDialog(frame, text); } /** * Makes a comboBox from List-type attribute * @param att The Attlist being turned into a combobox * @return jcombobox */ private JComboBox makeComboBox(AttList att){ JComboBox options = new JComboBox(); options.addItem(""); for(int j=0;j<att.getList().size();j++){ options.addItem(att.getList().get(j)); } return options; } /** * Creates the radiobutton options on the left side of the display. */ private void makeRadioTags(){ tagPanel.removeAll(); ArrayList<Elem> elements = adjudicationTask.getElements(); tagButtons = new ButtonGroup(); //first, add the regular tags for (int i = 0;i<elements.size();i++){ Elem e = elements.get(i); JRadioButton button = new JRadioButton(e.getName()); button.setActionCommand(e.getName()); button.addActionListener(new RadioButtonListener()); tagButtons.add(button); tagPanel.add(button); } //then, add the NC elements ArrayList<Elem> ncElements = adjudicationTask.getNCElements(); for (int i = 0;i<ncElements.size();i++){ Elem e = ncElements.get(i); JRadioButton button = new JRadioButton("NC-"+e.getName()); button.setActionCommand("NC-"+e.getName()); button.addActionListener(new RadioButtonListener()); tagButtons.add(button); tagPanel.add(button); } } /** * Create the file menu with associated listeners and * commands. */ private JMenu createFileMenu() { JMenu menu = new JMenu("File"); JMenuItem loadDTD = new JMenuItem("Load DTD"); loadDTD.setActionCommand("Load DTD"); loadDTD.addActionListener(new getFile()); menu.add(loadDTD); JMenuItem startAdjud = new JMenuItem("Start new adjudication"); startAdjud.setActionCommand("start adjud"); startAdjud.addActionListener(new getFile()); if(adjudicationTask.hasDTD()==false){ startAdjud.setEnabled(false); } else{ startAdjud.setEnabled(true); } menu.add(startAdjud); JMenuItem addFile = new JMenuItem("Add file to adjudication"); addFile.setActionCommand("add file"); addFile.addActionListener(new getFile()); if(hasFile==false){ addFile.setEnabled(false); } else{ addFile.setEnabled(true); } menu.add(addFile); JMenuItem addGS = new JMenuItem("Add gold standard file"); addGS.setActionCommand("add GS"); addGS.addActionListener(new getFile()); if(hasFile==false && hasFolder1==false){ addGS.setEnabled(false); } else{ addGS.setEnabled(true); } menu.add(addGS); JMenuItem startAdjudFolder = new JMenuItem("Start new adjudication (folder)"); startAdjudFolder.addActionListener(new getFile()); startAdjudFolder.setActionCommand("start adjud folder"); //add condition to enable and disable //@@@ if(adjudicationTask.hasDTD()==false){ startAdjudFolder.setEnabled(false); } else{ startAdjudFolder.setEnabled(true); } menu.add(startAdjudFolder); JMenuItem addFolder = new JMenuItem("Add folder to adjudication"); addFolder.addActionListener(new getFile()); addFolder.setActionCommand("add folder"); //add condition to enable and disable if(hasFolder1==false){ addFolder.setEnabled(false); } else{ addFolder.setEnabled(true); } menu.add(addFolder); menu.addSeparator(); JMenuItem saveFileXML = new JMenuItem("Save Gold Standard As XML"); saveFileXML.setActionCommand("Save XML"); saveFileXML.addActionListener(new getFile()); if(hasFile==false){ saveFileXML.setEnabled(false); } else{ saveFileXML.setEnabled(true); } menu.add(saveFileXML); return menu; } /** * Creates the menu for changing the font size */ private JMenu createDisplayMenu(){ JMenu menu = new JMenu("Display"); JMenuItem increaseFont = new JMenuItem("Font Size ++"); increaseFont.setActionCommand("Font++"); increaseFont.addActionListener(new DisplayListener()); menu.add(increaseFont); JMenuItem decreaseFont = new JMenuItem("Font Size --"); decreaseFont.setActionCommand("Font--"); decreaseFont.addActionListener(new DisplayListener()); menu.add(decreaseFont); return menu; } /** * Creates the menu describing MAI */ private JMenu createHelpMenu(){ JMenu menu = new JMenu("Help"); JMenuItem about = new JMenuItem("About MAI"); about.addActionListener(new AboutListener()); menu.add(about); return menu; } /** * Updates the menus when new files are added */ private void updateMenus(){ mb.remove(display); mb.remove(fileMenu); mb.remove(helpMenu); fileMenu = createFileMenu(); mb.add(fileMenu); mb.add(display); mb.add(helpMenu); mb.updateUI(); } /** * Create the GUI */ private static void createAndShowGUI() { JFrame.setDefaultLookAndFeelDecorated(true); //Create and set up the window. frame = new JFrame("MAI"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Create and set up the content pane. JComponent newContentPane = new MaiGui(); newContentPane.setOpaque(true); //content panes must be opaque frame.setContentPane(newContentPane); //Display the window. frame.pack(); frame.setSize(900,700); frame.setVisible(true); } public static void main(String[] args) { javax.swing.SwingUtilities.invokeLater( new Runnable() { public void run() { createAndShowGUI(); } }); } }
Java
/* * MAI - Multi-document Adjudication Interface * * Copyright Amber Stubbs (astubbs@cs.brandeis.edu) * Department of Computer Science, Brandeis University * * MAI 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 mai; class AttID extends Attrib{ /** * * ID attributes have special properties, so they * have their own class that keeps track of the * prefix. * * @author Amber Stubbs * */ AttID(){ } AttID (String name, String pre, boolean r){ setName(name); setRequired(r); setPrefix(pre); setDefaultValue(""); } public String getID(){ return(prefix + Integer.toString(number)); } public void setPrefix(String pre){ prefix=pre; } public String getPrefix(){ return prefix; } public void setNumber(int i){ number=i; } public void checkNumber(int i){ if(i>=number){ number=i+1; } } public int getNumber(){ return number; } public void incrementNumber(){ number++; } public void printInfo(){ System.out.println("Attribute name =" + getName() + " , required = " + getRequired()); } public String toString(){ return("Attribute name =" + getName() + " , required = " + getRequired() ); } private String prefix; private int number; }
Java
/* * MAI - Multi-document Adjudication Interface * * Copyright Amber Stubbs (astubbs@cs.brandeis.edu) * Department of Computer Science, Brandeis University * * MAI 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 mai; import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * Creates the button that will go in the AnnJTable * */ class ButtonEditor extends DefaultCellEditor { private static final long serialVersionUID = 8354224138590694483L; private JButton button; private String label; private boolean isPushed; private String command; ButtonEditor(JCheckBox checkBox) { super(checkBox); command = ""; button = new JButton(); button.setOpaque(true); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { fireEditingStopped(); } }); } public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { if (isSelected) { button.setForeground(table.getSelectionForeground()); button.setBackground(table.getSelectionBackground()); } else{ button.setForeground(table.getForeground()); button.setBackground(table.getBackground()); } label = (value ==null) ? "" : value.toString(); button.setText( label ); isPushed = true; return button; } public Object getCellEditorValue() { if (isPushed) { //System.out.println("hey!"); // // //JOptionPane.showMessageDialog(button ,label + ": Ouch!"); // System.out.println(label + ": Ouch!"); } isPushed = false; return new String( label ) ; } public boolean stopCellEditing() { isPushed = false; return super.stopCellEditing(); } protected void fireEditingStopped() { super.fireEditingStopped(); } public String getLabel(){ return label; } public void setCommand(String c){ command = c; } public String getCommand(){ return command; } }
Java
/* * MAI - Multi-document Adjudication Interface * * Copyright Amber Stubbs (astubbs@cs.brandeis.edu) * Department of Computer Science, Brandeis University * * MAI 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 mai; /** * Extents Elem to provid information about tags that are * used to label extents in a text (as well as non-consuming * tags). * * @author Amber Stubbs * */ class ElemExtent extends Elem{ ElemExtent(String name, String pre){ setName(name); //extent tags always have id, start, and end AttID id = new AttID("id", pre, true); AttData start = new AttData("start", true); AttData end = new AttData("end", true); AttData text = new AttData("text", false); addAttribute(id); addAttribute(start); addAttribute(end); addAttribute(text); } public void setStart(int s){ start=s; } public int getStart(){ return start; } public void setEnd(int e){ end=e; } public int getEnd(){ return end; } public void printInfo(){ System.out.println("\tname = " + getName()); System.out.println("\tStart = " + getStart()); System.out.println("\tEnd = " + getEnd()); } private int start; private int end; }
Java
/* * MAI - Multi-document Adjudication Interface * * Copyright Amber Stubbs (astubbs@cs.brandeis.edu) * Department of Computer Science, Brandeis University * * MAI 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 mai; import java.awt.*; import javax.swing.*; import javax.swing.table.*; /** * The renderer for the ButtonEditor * */ class ButtonRenderer extends JButton implements TableCellRenderer { // Auto-generated by Eclipse private static final long serialVersionUID = 6376135242614843146L; public ButtonRenderer() { setOpaque(true); } public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (isSelected) { setForeground(table.getSelectionForeground()); setBackground(table.getSelectionBackground()); } else{ setForeground(table.getForeground()); setBackground(UIManager.getColor("Button.background")); } setText( (value ==null) ? "" : value.toString() ); return this; } }
Java
/* * MAI - Multi-document Adjudication Interface * * Copyright Amber Stubbs (astubbs@cs.brandeis.edu) * Department of Computer Science, Brandeis University * * MAI 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 mai; import java.util.*; /** * AdjudicationTask serves as a go-between for MaiGui and the * SQLite interface adjudDB, and also manages the ID * assignments for the gold standard file. * <p> * The majority of methods in this file just provide error * catching for the methods in AdjudDB. * * @author Amber Stubbs * @version 0.7 April 19, 2012 */ class AdjudicationTask { private Hashtable<String,Elem> elements; private Hashtable<String,AttID> idTracker; private AdjudDB tagTable; private DTD dtd; private boolean hasDTD; /** * Creates a new AdjudicationTask object and accompanying database */ AdjudicationTask(){ tagTable = new AdjudDB(); hasDTD = false; } /** * resets the database */ void reset_db(){ tagTable.close_db(); tagTable = new AdjudDB(); } /** * Clears the idTracker hashtable */ void reset_IDTracker(){ idTracker = createIDTracker(); } /** * Calls the DB to create all the necessary tables */ void addDTDtoDB(){ tagTable.addDTD(dtd); } /** * * @param fullName * @param newTags */ void addTagsFromHash(String fullName, HashCollection<String,Hashtable<String,String>> newTags){ tagTable.addTagsFromHash(fullName, dtd, newTags); } /** * called when a goldStandard file is added to the task */ void findAllOverlaps(){ try{ tagTable.findAllOverlaps(); } catch(Exception e){ System.out.println("help, error finding extent overlaps!"); System.out.println(e.toString()); } } /** * Adds a tag (with information about attribute values in a Hashtable) * to the database * * @param fullName name of the file the tag is from * @param e the type of Elem (tag) being added * @param tag Hashtable with information about the tag */ void addTagFromHash(String fullName,Elem e, Hashtable<String,String> tag){ if (e instanceof ElemExtent){ tagTable.usePreparedExtentStatements(fullName, e,tag); try{ tagTable.batchExtents(); }catch(Exception ex){ System.out.println("help, error in batch extents!"); System.out.println(ex.toString()); } try{ tagTable.batchElement(e); }catch(Exception ex){ System.out.println("help, error in batchelement extent!"); System.out.println(ex.toString()); } //also, check for overlaps and add them to the extent_overlaps table if(fullName.equals("goldStandard.xml")){ try{ tagTable.add_overlaps(fullName,e,tag); }catch(Exception exe){ System.out.println("help, error in finding extent overlaps!"); System.out.println(exe.toString()); } } } else if (e instanceof ElemLink){ tagTable.usePreparedLinkStatements(fullName, e, tag); try{ tagTable.batchLinks(); }catch(Exception ex){ System.out.println("help, error in batchLinks link!"); System.out.println(ex.toString()); } try{ tagTable.batchElement(e); }catch(Exception ex){ System.out.println("help, error in batchElement link!"); System.out.println(ex.toString()); } } else{ System.out.println("error! element type not found"); } } /** * Creates the hastable of DTD Elements * @return */ private Hashtable<String,Elem> createHash(){ Hashtable<String,Elem> es=new Hashtable<String,Elem>(); ArrayList<Elem>elems = dtd.getElements(); for(int i=0;i<elems.size();i++){ es.put(elems.get(i).getName(),elems.get(i)); } return(es); } /** * The IDTracker hashtable keeps one ID for each element that * has an ID, and increments the number so that no two * tags of the same type will have the same ID. In MAI this * is used only for the Gold Standard file (other files can't be edited and * are assumed to already have only one tag per ID) * * @return */ private Hashtable<String,AttID> createIDTracker(){ Hashtable<String,AttID> ids = new Hashtable<String,AttID>(); ArrayList<Elem>elems = dtd.getElements(); for(int i=0;i<elems.size();i++){ ArrayList<Attrib> attribs = elems.get(i).getAttributes(); for(int j=0;j<attribs.size();j++){ if (attribs.get(j) instanceof AttID){ AttID oldid = (AttID)attribs.get(j); AttID id = new AttID(oldid.getName(), oldid.getPrefix(),true); id.setNumber(0); ids.put(elems.get(i).getName(),id); } } } return ids; } /** * Finds the next available ID for an element and returns it. * * @param element tag type * @param fileName name of the file the ID is for * @return the next ID for that element */ String getNextID(String element,String fileName){ AttID id = idTracker.get(element); String nextid = id.getID(); id.incrementNumber(); //check to see if nextid is already in db //this will catch cases where two tags have //the same prefix try{ while(tagTable.idExists(nextid,fileName)){ nextid = id.getID(); id.incrementNumber(); } }catch(Exception e){ System.out.println(e.toString()); } return nextid; } HashCollection<String,String> getExtentAllLocs(String tagname){ try{ return(tagTable.getExtentAllLocs(tagname)); }catch(Exception e){ System.out.println(e.toString()); } return (new HashCollection<String,String>()); } ArrayList<String> getFilesAtLocbyElement(String elem, int loc){ try{ ArrayList<String>files = tagTable.getFilesAtLocbyElement(elem,loc); return files; }catch(Exception e){ System.out.println(e.toString()); return null; } } ArrayList<String> getExtentTagsByFileAndType(String file, Elem elem){ try{ ArrayList<String>tags = tagTable.getExtentTagsByFileAndType(file,elem); return tags; }catch(Exception e){ System.out.println(e.toString()); return null; } } ArrayList<String> getLinkTagsByFileAndType(String file, Elem elem){ try{ ArrayList<String>tags = tagTable.getLinkTagsByFileAndType(file,elem); return tags; }catch(Exception e){ System.out.println(e.toString()); return null; } } String getTextByFileElemAndID(String file, String elem, String id){ String text = ""; try{ text = tagTable.getTextByFileElemAndID(file,elem,id); }catch(Exception e){ System.out.println(e.toString()); } return text; } Hashtable<String,String> getAllExtentsByFile(String file){ Hashtable<String,String> allExtents = new Hashtable<String,String>(); try{ allExtents = tagTable.getAllExtentsByFile(file); }catch(Exception e){ System.out.println(e.toString()); } return allExtents; } boolean tagExistsInFileAtLoc(String file, int loc){ try{ return tagTable.tagExistsInFileAtLoc(file,loc); }catch(Exception e){ System.out.println("help!"); System.out.println(e.toString()); return false; } } Hashtable<String,String> getTagsByFileAndID(String tagname, String id, String filename){ try{ ArrayList<Attrib> atts = dtd.getElem(tagname).getAttributes(); return tagTable.getTagsByFileAndID(tagname,id,filename,atts); }catch(Exception e){ System.out.println(e.toString()); return null; } } String getLocByFileAndID(String file, String id){ try{ String loc = tagTable.getLocByFileAndID(file,id); return loc; }catch(Exception e){ System.out.println(e.toString()); return null; } } HashCollection<String,String>findGoldStandardLinksByType(String tagname){ try{ HashCollection<String,String> gslinks = tagTable.getGSLinksByType(tagname); return gslinks; }catch(Exception e){ System.out.println(e); } return new HashCollection<String,String>(); } void removeExtentByFileAndID(String fullName,String e_name,String id){ try{ tagTable.removeExtentTags(fullName,e_name,id); }catch(Exception e){ System.out.println(e.toString()); } } void removeLinkByFileAndID(String fullName,String e_name,String id){ try{ tagTable.removeLinkTags(fullName,e_name,id); }catch(Exception e){ System.out.println(e.toString()); } } HashCollection<String,String> getLinksByFileAndExtentID(String file,String e_name,String id){ try{ return(tagTable.getLinksByFileAndExtentID(file,e_name,id)); }catch(Exception e){ System.out.println(e.toString()); } return (new HashCollection<String,String>()); } /** * Sets the DTD for the Adjudication Task so * information about the files being adjudicated * are easily available. * * @param d the object describing the task's DTD */ public void setDTD(DTD d){ dtd=d; elements = createHash(); idTracker = createIDTracker(); hasDTD=true; } /** * Returns all the Elem objects in the DTD * * @return */ public ArrayList<Elem> getElements(){ return dtd.getElements(); } HashCollection<String,String> getTagsSpanByType(int begin, int end, String tag){ try{ return (tagTable.getTagsInSpanByType(begin,end,tag)); }catch(Exception e){ System.out.println(e.toString()); } return null; } HashCollection<String,Hashtable<String,String>> getLinkTagsSpanByType (int begin, int end, String tagname){ try{ ArrayList<Attrib> atts = dtd.getElem(tagname).getAttributes(); return (tagTable.getLinkTagsInSpanByType(begin,end,tagname,atts)); }catch(Exception e){ System.out.println(e.toString()); } return null; } HashCollection<String,String> getFileTagsSpanAndNC(String file, int begin, int end){ try{ return (tagTable.getFileTagsInSpanAndNC(file, begin,end)); }catch(Exception e){ System.out.println(e.toString()); } return null; } public HashCollection<String,String>getCurrentHighlights(){ return tagTable.getCurrentHighlights(); } public ArrayList<String> getExtentElements(){ ArrayList<String> extents = new ArrayList<String>(); ArrayList<Elem> elems = dtd.getElements(); for(int i=0;i<elems.size();i++){ Elem e = elems.get(i); if(e instanceof ElemExtent){ extents.add(e.getName()); } } return extents; } /** * Returns only non-consuming elements in the DTD * * @return */ public ArrayList<Elem> getNCElements(){ return dtd.getNCElements(); } public ArrayList<String> getLinkElements(){ ArrayList<String> links = new ArrayList<String>(); ArrayList<Elem> elems = dtd.getElements(); for(int i=0;i<elems.size();i++){ Elem e = elems.get(i); if(e instanceof ElemLink){ links.add(e.getName()); } } return links; } public Hashtable<String,Elem> getElemHash(){ return elements; } Elem getElem(String name){ return elements.get(name); } boolean hasDTD(){ return hasDTD; } public String getDTDName(){ return dtd.getName(); } }
Java
/* * MAI - Multi-document Adjudication Interface * * Copyright Amber Stubbs (astubbs@cs.brandeis.edu) * Department of Computer Science, Brandeis University * * MAI 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 mai; /** * Extends Elem; used for describing link tags * * @author Amber Stubbs * */ class ElemLink extends Elem{ ElemLink(){ } ElemLink(String name, String pre){ setName(name); AttID id = new AttID("id", pre, true); AttData from = new AttData("fromID", true); AttData fromText = new AttData("fromText",true); AttData to = new AttData("toID", true); AttData toText = new AttData("toText",true); addAttribute(id); addAttribute(from); addAttribute(fromText); addAttribute(to); addAttribute(toText); } public void setFrom(String f){ fromID=f; } public String getFrom(){ return fromID; } public void setFromText(String f){ fromText=f; } public String getFromText(){ return fromText; } public void setTo(String t){ toID=t; } public String getTo(){ return toID; } public void setToText(String t){ toText=t; } public String getToText(){ return toText; } public void printInfo(){ System.out.println("\tname = " + getName()); System.out.println("\tFrom = " + getFrom()); System.out.println("\tTo = " + getTo()); } private String fromID; private String fromText; private String toID; private String toText; }
Java
/* * MAI - Multi-document Adjudication Interface * * Copyright Amber Stubbs (astubbs@cs.brandeis.edu) * Department of Computer Science, Brandeis University * * MAI 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 mai; class Attrib extends Object{ /** * The parent class for tag attributes * * @author Amber Stubbs * */ Attrib(){ } public String getName(){ return name; } public void setName(String n){ name=n; } public boolean getRequired(){ return required; } public void setRequired(boolean r){ required=r; } public String getDefaultValue(){ return defaultValue; } public void setDefaultValue(String d){ defaultValue = d; } public boolean hasDefaultValue(){ if (defaultValue.length()==0){ return false; } return true; } public void printInfo(){ System.out.println("Attribute name =" + getName() + " , required = " + getRequired()); } public String toString(){ return("Attribute name =" + getName() + " , required = " + getRequired() ); } private String name; private boolean required; private String defaultValue; }
Java
/* * MAI - Multi-document Adjudication Interface * * Copyright Amber Stubbs (astubbs@cs.brandeis.edu) * Department of Computer Science, Brandeis University * * MAI 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 mai; import java.util.*; /** * This is an implementation of a Hashtable that * stores more than one value per key. This is done by * having every key associated with an ArrayList, and every * new value being stored in the array is added to the end of * the list (unless the list already contains that value) * */ class HashCollection<K,V>{ private Hashtable<K,ArrayList<V>> hc; HashCollection(){ hc = new Hashtable<K,ArrayList<V>>(); } /** * Associate yet another value with a key in a Hashtable that allows duplicates. * Also use to put the first key/value. * * @param key Key to lookup by * @param value yet another associated value for this key. */ void putEnt (K key, V value) { ArrayList<V> existing = getList(key); if ( existing == null ){ ArrayList<V> newlist = new ArrayList<V>(); newlist.add(value); hc.put(key, newlist); } else { //just add to tail end of existing ArrayList //but only if it's not already there if(!existing.contains(value)){ existing.add(value); } } } public void putAllEnt (K key, V value) { ArrayList<V> existing = getList(key); if ( existing == null ){ ArrayList<V> newlist = new ArrayList<V>(); newlist.add(value); hc.put(key, newlist); } else { //just add to tail end of existing ArrayList //even if the value is already there existing.add(value); } } public Hashtable<V,String> getValueHash(){ Hashtable<V,String> values = new Hashtable<V,String>(); Iterator<ArrayList<V>> it = hc.values().iterator(); while(it.hasNext()){ ArrayList<V> a1 = it.next(); if(a1!=null){ for (int j=0;j<a1.size();j++){ if(a1.get(j)!=null){ values.put(a1.get(j),""); } } } } return(values); } public void printKeys(){ for (Enumeration<K> e = hc.keys() ; e.hasMoreElements() ;) { System.out.println(e.nextElement()); } } public ArrayList<K> getKeyList(){ ArrayList<K> keys = new ArrayList<K>(); for (Enumeration<K> e = hc.keys() ; e.hasMoreElements() ;) { keys.add(e.nextElement()); } return(keys); } public void printHash(){ for (Enumeration<K> e = hc.keys() ; e.hasMoreElements() ;) { K ent = e.nextElement(); System.out.println((String)ent + ":"); ArrayList<V> list = getList(ent); for (int i=0;i<list.size();i++){ System.out.println("\t" + list.get(i).toString()); } } } public void putAll(HashCollection<K,V> h){ for (Enumeration<K> e = hc.keys() ; e.hasMoreElements() ;) { K ent = e.nextElement(); if (hc.containsKey(ent)){ ArrayList<V> vals = h.getList(ent); if(vals !=null){ for(int i=0;i<vals.size();i++){ putEnt(ent,vals.get(i)); } } } else{ ArrayList<V> vals = h.getList(ent); if(vals !=null){ for(int i=0;i<vals.size();i++){ putEnt(ent,vals.get(i)); } } } } } public void putList(K key, ArrayList<V> list){ for(int i=0;i<list.size();i++){ putEnt(key,list.get(i)); } } ArrayList<V> getList(K key){ ArrayList<V> k = hc.get(key); if (k==null){ return(null); } else{ return(k); } } int size(){ return(hc.size()); } void remove(K key){ hc.remove(key); } void clear(){ for (Enumeration<K> e = hc.keys() ; e.hasMoreElements() ;) { K ent = e.nextElement(); remove(ent); } } public boolean containsKey(K key){ return(hc.containsKey(key)); } ArrayList<V> get(K key){ return(hc.get(key)); } public Enumeration<K> keys(){ return(hc.keys()); } }
Java
/* * MAI - Multi-document Adjudication Interface * * Copyright Amber Stubbs (astubbs@cs.brandeis.edu) * Department of Computer Science, Brandeis University * * MAI 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 mai; import javax.swing.JTable; import javax.swing.table.*; /** * * AnnJModel creates a JTable that * can have a button in the desired location. * * @author Amber Stubbs */ class AnnJTable extends JTable{ private static final long serialVersionUID = -436162326023724236L;//generated by Eclipse AnnJTable(){ setModel(new AnnTableModel()); } AnnJTable(AnnTableModel model){ setModel(model); } public TableCellRenderer getCellRenderer(int row, int column){ DefaultTableModel tableModel = (DefaultTableModel)getModel(); if (column==tableModel.getColumnCount()-1){ return new ButtonRenderer(); } else{ return super.getCellRenderer(row,column); } } }
Java
package utils; import java.io.File; import java.io.FileFilter; import java.io.FilenameFilter; public class ExtensionFilter implements FilenameFilter, FileFilter { private String extension; public ExtensionFilter( String extension ) { this.extension = extension; } @Override public boolean accept(File dir, String name) { return (name.endsWith(extension)); } @Override public boolean accept(File file) { return file.toString().endsWith(extension); } }
Java
package utils; public class BeatAnn { public String annid; public int start; public int end; public String annType; public String conceptId; public String conceptName; public String text; public String relatedDrug; public String targetDrug; public String c_level; // public String getAnnid() // { // return annid; // } // // public int getStartindex() // { // return start; // } // // public int getEndIndex() // { // return end; // } // // public String getAnnType() // { // return annType; // } // // public String getAnnid() // { // return annid; // } // public String getAnnid() // { // return annid; // } // public String getAnnid() // { // return annid; // } // public String getAnnid() // { // return annid; // } }
Java
package utils; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * This is a class to convert BEAT output files to XML format * */ public class XMLGeneration { HashMap<String,ArrayList<String>> conceptMap; /** * Main class to run the conversion. * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub // XMLGeneration p = new XMLGeneration(); // List<BeatAnn> annotationList = p.parseDSInputFile("inputfiles\\karen\\annotations.tsv"); // //p.CreateXMLFilesforDS("outputfiles\\karen\\", annotationList, "k" ); // p.CreateXMLFilesforDS2("outputfiles\\karen\\", annotationList, "k" ); // System.out.println("Karen's Task Completed for Daily Strength!!"); // // List<String> twitterannList = p.parseTwitterFile("inputfiles\\karen\\binaryannotations.tsv"); // p.CreateXMLFilesforTwitter("twitterOutputfiles\\karen\\", twitterannList, "k"); // System.out.println("Karen's Task completed for Twitter!!"); // // annotationList = p.parseDSInputFile("inputfiles\\robert\\annotations.tsv"); // //p.CreateXMLFilesforDS("outputfiles\\robert\\", annotationList, "r" ); // p.CreateXMLFilesforDS2("outputfiles\\robert\\", annotationList, "r"); // System.out.println("Robert's Task Completed for Daily Strength!!"); // // twitterannList = p.parseTwitterFile("inputfiles\\robert\\binaryannotations.tsv"); // p.CreateXMLFilesforTwitter("twitterOutputfiles\\robert\\", twitterannList, "r"); // System.out.println("Robert's Task completed for Twitter!!"); } /** * Method to get the concept name for concept id * */ private void getConceptName(){ //String conceptName = null; conceptMap = new HashMap<String, ArrayList<String>>(); try{ File conceptFile = new File("inputfiles\\conceptNames.tsv"); if(conceptFile.exists()) { BufferedReader reader = new BufferedReader(new FileReader(conceptFile)); String line; while((line=reader.readLine())!=null){ String[] splitdata = line.split("\t"); if(splitdata.length == 2){ if(!conceptMap.containsKey(splitdata[0])){ ArrayList<String> list = new ArrayList<String>(); list.add(splitdata[1]); conceptMap.put(splitdata[0], list); } else { ArrayList<String> list = conceptMap.get(splitdata[0]); list.add(splitdata[1]); conceptMap.put(splitdata[0], list); } } } reader.close(); } else { System.out.println("Problem in Loading concept file"); return ; } }catch(Exception e) { e.printStackTrace(); } //return conceptName; } /* * Method to parse the input BEAT files * */ private List<BeatAnn> parseDSInputFile(File file){//String path){ List<BeatAnn> annotationsList = new ArrayList<BeatAnn>(); try{ BufferedReader reader = new BufferedReader(new FileReader(file)); String line; while((line = reader.readLine())!= null) { String[] splitdata = line.split("\t"); if(splitdata.length == 8 || splitdata.length == 9) { BeatAnn obj = new BeatAnn(); obj.annid = splitdata[0]; obj.start = Integer.parseInt(splitdata[1]) + 1; obj.end = Integer.parseInt(splitdata[2]) + 1; obj.annType = splitdata[3]; obj.conceptId = splitdata[4]; if(conceptMap.containsKey(obj.conceptId)) { String conceptnames = ""; ArrayList<String> list = conceptMap.get(obj.conceptId); for(int i=0;i<list.size();i++){ if(conceptnames.equals("")) { conceptnames = list.get(i); } else { conceptnames = conceptnames + ", " + list.get(i); } } obj.conceptName = conceptnames; } else obj.conceptName = ""; obj.text = splitdata[5]; obj.relatedDrug = splitdata[6]; obj.targetDrug = splitdata[7]; if(splitdata.length == 9) obj.c_level = splitdata[8]; else obj.c_level = "3"; annotationsList.add(obj); } } reader.close(); }catch(Exception e){ e.printStackTrace(); } return annotationsList; } /* * Method to convert the BEAT output file into XML format and store it in a folder * */ // private void CreateXMLFilesforDS(String folderPath, List<BeatAnn> inputList, String inifilename){ // try{ // HashMap<String,String> map = MapText("inputfiles\\DStexts.tsv"); // // HashMap<String,HashMap<String,Integer>> countHash = new HashMap<String,HashMap<String,Integer>>(); // // BufferedWriter writer = null; // for(BeatAnn objbeatann : inputList){ // String path = folderPath + inifilename + "_" + objbeatann.annid +".xml"; // File file = new File(path); // // // if(!file.exists()) // { // file.createNewFile(); // writer = new BufferedWriter(new FileWriter(path,true)); // writer.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?> \n<DSAdverseDrugReactions> \n<TEXT><![CDATA[\n"); // writer.append(map.get(objbeatann.annid)); // writer.append("\n]]></TEXT>\n"); // writer.append("<TAGS>\n"); // } // else // { // writer = new BufferedWriter(new FileWriter(path,true)); // } // // String id; // if(countHash.containsKey(objbeatann.annid)) // { // HashMap<String,Integer> innerHash = countHash.get(objbeatann.annid); // int count = (innerHash.get(objbeatann.annType) + 1); // id = objbeatann.annType + "" + count; // innerHash.put(objbeatann.annType, count); // countHash.put(objbeatann.annid, innerHash); // } // else // { // HashMap<String,Integer> innerHash = new HashMap<String, Integer>(); // innerHash.put("ADR", 0); // innerHash.put("Beneficial", 0); // innerHash.put("Other", 0); // innerHash.put("Indication", 0); // innerHash.put("Drug", 0); // innerHash.put("Interaction", 0); // countHash.put(objbeatann.annid, innerHash); // int count = (innerHash.get(objbeatann.annType) + 1); // id = objbeatann.annType + "" + count; // innerHash.put(objbeatann.annType, count); // countHash.put(objbeatann.annid, innerHash); // } // // writer.append("<" + objbeatann.annType + " id=\"" + id +"\" start=\"" + objbeatann.start + "\" end=\"" + // objbeatann.end + "\" text=\"" + objbeatann.text + "\" conceptID=\"" + objbeatann.conceptId + // "\" relatedDrug=\"" + objbeatann.relatedDrug + "\" targetDrug=\"" + objbeatann.targetDrug +"\" />"); // writer.append("\n"); // writer.close(); // } // // //String files; // File folder = new File(folderPath); // File[] listOfFiles = folder.listFiles(); // for (int i = 0; i < listOfFiles.length; i++) // { // if (listOfFiles[i].isFile()) // { // //files = listOfFiles[i].getName(); // writer = new BufferedWriter(new FileWriter(folderPath + listOfFiles[i].getName(),true)); // writer.append("</TAGS>\n</DSAdverseDrugReactions>\n"); // writer.close(); // //System.out.println(files); // } // } // // }catch(Exception ex){ // ex.printStackTrace(); // } // } /* * Method to convert the BEAT output file into XML format type 2.... * */ public String CreateXMLFilesforDS2(File inputfile,File inputTextFile, File outputDir){ String result; getConceptName(); List<BeatAnn> inputList = parseDSInputFile(inputfile); try{ HashMap<String,String> map = MapText(inputTextFile); //HashMap<String,HashMap<String,Integer>> countHash = new HashMap<String,HashMap<String,Integer>>(); BufferedWriter writer = null; int count = 0; for(BeatAnn objbeatann : inputList){ String path = outputDir.getPath() + "\\" + outputDir.getName() + "_" + objbeatann.annid +".xml"; File file = new File(path); if(!file.exists()) { file.createNewFile(); writer = new BufferedWriter(new FileWriter(path,true)); writer.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?> \n<DSAdverseDrugReactions> \n<TEXT><![CDATA[\n"); writer.append(map.get(objbeatann.annid)); writer.append("\n]]></TEXT>\n"); writer.append("<TAGS>\n"); } else { writer = new BufferedWriter(new FileWriter(path,true)); } int level = Integer.parseInt(objbeatann.c_level); String confLevel = ""; if(level == 3) confLevel = "High"; else if(level == 2 ) confLevel = "Moderate"; else if(level == 1) confLevel = "Low"; writer.append("<Annotation id=\"id" + count +"\" start=\"" + objbeatann.start + "\" end=\"" + objbeatann.end + "\" text=\"" + objbeatann.text + "\" type=\"" + objbeatann.annType +"\" conceptID=\"" + objbeatann.conceptId + "\" conceptName=\"" + objbeatann.conceptName + "\" relatedDrug=\"" + objbeatann.relatedDrug + "\" targetDrug=\"" + objbeatann.targetDrug +"\" confidence=\"" + confLevel +"\" />"); writer.append("\n"); writer.close(); count++; } //String files; File folder = new File(outputDir.getPath()); File[] listOfFiles = folder.listFiles(); for (int i = 0; i < listOfFiles.length; i++) { if (listOfFiles[i].isFile()) { //files = listOfFiles[i].getName(); writer = new BufferedWriter(new FileWriter(outputDir.getPath() + "\\" + listOfFiles[i].getName(),true)); writer.append("</TAGS>\n</DSAdverseDrugReactions>\n"); writer.close(); //System.out.println(files); } } }catch(Exception ex){ ex.printStackTrace(); } result = "XML files created!!!!"; return result; } /* * Method to map the input annotations * */ private HashMap<String,String> MapText(File file){ HashMap<String,String> map = new HashMap<String,String>(); try{ BufferedReader reader = new BufferedReader(new FileReader(file)); String line; while((line = reader.readLine())!= null){ String[] splitdata = line.split("\t"); if(splitdata.length == 2) { map.put(splitdata[0].trim(), splitdata[1].trim()); } } reader.close(); }catch(Exception ex){ ex.printStackTrace(); } return map; } /* * Method to parse the annotated input file for Twitter data * */ private List<String> parseTwitterFile(File file) { List<String> binaryannList = new ArrayList<String>(); try{ BufferedReader reader = new BufferedReader(new FileReader(file)); String line; while((line=reader.readLine())!=null){ if(line.split("\t").length == 2){ binaryannList.add(line); } } }catch(Exception ex){ ex.printStackTrace(); } return binaryannList; }//twitterOutputfiles /* * Method to convert the BEAT output file into XML format and store it in a folder * */ public String CreateXMLFilesforTwitter(File inputfile, File inputTextfile, File outputDir){ List<String> binaryinputList = parseTwitterFile(inputfile); HashMap<String,String> map = MapText(inputTextfile); try { for(String line : binaryinputList){ String[] splitdata = line.split("\t"); if(map.containsKey(splitdata[0].trim())) { BufferedWriter writer = new BufferedWriter(new FileWriter(outputDir.getPath() + "\\"+ outputDir.getName() + "_" + splitdata[0]+".xml")); writer.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?> \n<TwitterAdverseDrugReactions> \n<TEXT><![CDATA[\n"); writer.append(map.get(splitdata[0].trim())); writer.append("\n]]></TEXT>\n"); writer.append("<TAGS>\n"); writer.append("<ELE id=\"1\" start=\"1\" end=\"" + ((map.get(splitdata[0].trim())).length() + 1) + "\" text=\"" + map.get(splitdata[0].trim()) + "\" type=\"" + splitdata[1] +"\" />"); writer.append("\n</TAGS>\n</TwitterAdverseDrugReactions>\n"); writer.close(); } else { System.out.println("Error in input files"); return ""; } } }catch(Exception ex){ ex.printStackTrace(); } return "XML file conversion completed!!!"; } }
Java
package utils; import java.io.BufferedReader; import java.io.BufferedInputStream; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import edu.umass.cs.mallet.base.pipe.iterator.FileIterator; public class FileUtils { /** * Create new file if not exists * @param path * @return true if new file created */ public static boolean createFileIfNotExists(String path) { boolean result = false; File modelFile = new File(path); if (!modelFile.exists()) { try { result = modelFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } return result; } public static void createFileIfNotExists(String path, List<String> contentLines) { File file = new File(path); if (!file.exists()) { try { file.createNewFile(); BufferedWriter writer = new BufferedWriter(new FileWriter(file)); for(int i=0;i<contentLines.size();i++) { String line = contentLines.get(i); writer.write(line+"\n"); } writer.flush(); writer.close(); } catch (IOException e) { e.printStackTrace(); } } } public static void createFile(String path, List<String> contentLines) { File file = new File(path); try { file.delete(); file.createNewFile(); BufferedWriter writer = new BufferedWriter(new FileWriter(file)); for(int i=0;i<contentLines.size();i++) { String line = contentLines.get(i); writer.write(line+"\n"); } writer.flush(); writer.close(); } catch (IOException e) { e.printStackTrace(); } } public static void appendLine(String path, String line) throws UnsupportedEncodingException, FileNotFoundException { File file = new File(path); Writer writer = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(file, true), "UTF-8")); try { writer.write(line+"\n"); writer.flush(); writer.close(); } catch (IOException e) { e.printStackTrace(); } } public static void createFileWithFormat(String path,String format, List<String> contentLines) { File file = new File(path); try { file.delete(); file.createNewFile(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file),format)); for(int i=0;i<contentLines.size();i++) { String line = contentLines.get(i); writer.write(line+"\n"); } writer.flush(); writer.close(); } catch (IOException e) { e.printStackTrace(); } } /** * * @param path * @return true if created */ public static boolean createFolderIfNotExists(String path) { boolean result = false; File modelFolder = new File(path); if (!modelFolder.exists() || !modelFolder.isDirectory()) { result = modelFolder.mkdir(); } return result; } public static String deleteAndCreateFolder(String path) throws IOException { boolean success_del; File modelFolder = new File(path); success_del = deleteDirectory(modelFolder); if (!success_del) { // Deletion failed throw new IOException(); } File new_modelFolder = new File(path); if (new_modelFolder.mkdir()==true) { return path; } else{ throw new IOException(); } } static boolean deleteDirectory(File path) { if( path.exists() ) { File[] files = path.listFiles(); for(int i=0; i<files.length; i++) { if(files[i].isDirectory()) { deleteDirectory(files[i]); } else { files[i].delete(); } } } return( path.delete() ); } public static void CopyFileToDirectory(String file_name, String from_directory, String to_directory) { InputStream inStream = null; OutputStream outStream = null; try{ File afile =new File(from_directory+"/"+file_name); File bfile =new File(to_directory+"/"+file_name); inStream = new FileInputStream(afile); outStream = new FileOutputStream(bfile); byte[] buffer = new byte[1024]; int length; //copy the file content in bytes while ((length = inStream.read(buffer)) > 0){ outStream.write(buffer, 0, length); } inStream.close(); outStream.close(); System.out.println("File is copied successful!"); }catch(IOException e){ e.printStackTrace(); } } /** * Read whole file content into a string * @param filePath * @return The File content * @throws IOException */ public static String readWholeFile(String filePath) throws IOException { StringBuffer fileData = new StringBuffer(1000); FileReader fr = new FileReader(filePath); BufferedReader reader = new BufferedReader(fr); char[] buf = new char[1024]; int numRead=0; while((numRead=reader.read(buf)) != -1){ String readData = String.valueOf(buf, 0, numRead); fileData.append(readData); buf = new char[1024]; } reader.close(); fr.close(); return fileData.toString(); } public static FileIterator getFilesInDirectory(String root) { ExtensionFilter filter = new ExtensionFilter(".txt"); FileIterator file_iterator = new FileIterator(new File(root), filter, FileIterator.LAST_DIRECTORY); return file_iterator; } public static FileIterator getFilesInDirectory(String root,String extension) { ExtensionFilter filter = new ExtensionFilter("."+extension); FileIterator file_iterator = new FileIterator(new File(root), filter, FileIterator.LAST_DIRECTORY); return file_iterator; } public static List<String> getFilesListInDirectory(String root,String extension) { FileIterator file_iterator = getFilesInDirectory(root,extension); ArrayList<String> files = new ArrayList<String>(); while (file_iterator.hasNext()) { String file_path = file_iterator.nextFile().getPath(); files.add(file_path); } return files; } public static List<String> getDirectories(String root) { List<String> directories = new ArrayList<String>(); File dir = new File(root); File listDir[] = dir.listFiles(); for (int i = 0; i < listDir.length; i++) { if (listDir[i].isDirectory()) { directories.add(listDir[i].getPath()); } } return directories; } public static List<String> loadLineByLine(String file_path) { List<String> lines = new ArrayList<String>(); try { File f = new File(file_path); if(!f.exists()) return lines; BufferedReader br1 = new BufferedReader( new FileReader(f)); while (br1.ready()) { String line = br1.readLine(); lines.add(line); } br1.close(); } catch (Exception e) { e.printStackTrace(); } return lines; } public static List<String> loadLineByLineAndTrim(String file_path) { List<String> lines = new ArrayList<String>(); try { File f = new File(file_path); if(!f.exists()) return lines; BufferedReader br1 = new BufferedReader( new FileReader(f)); while (br1.ready()) { String line = br1.readLine(); lines.add(line.trim()); } br1.close(); } catch (Exception e) { e.printStackTrace(); } return lines; } public static boolean fileExists(String path) { File modelFile = new File(path); return modelFile.exists(); } public static String getFilePathInDirectory(String directory, String fileName) { String file_path = directory; file_path += "/"+fileName; return file_path; } public static void logLine(String filePath, String line) { if(filePath==null) { String log = (new Date())+" : "+line+"\n"; System.out.print(log); }else { try { BufferedWriter writer = new BufferedWriter( new FileWriter( filePath , true ) ); writer.write((new Date())+" : "+line+"\n"); writer.flush(); writer.close(); } catch (IOException e) { e.printStackTrace(); } } } public static String ReadFileInToString(String filePath) throws IOException { //create file object File file = new File(filePath); BufferedInputStream bin = null; String strFileContents = null; StringBuffer fileData = new StringBuffer(); BufferedReader reader = new BufferedReader( new FileReader(filePath)); char[] buf = new char[1024]; int numRead=0; while((numRead=reader.read(buf)) != -1){ String readData = String.valueOf(buf, 0, numRead); fileData.append(readData); } reader.close(); return fileData.toString(); } public static String getTextFileName(String FilePath) { String file_name= getFileNameWithoutPath(FilePath); String text_file = "/"+file_name+".txt"; return text_file; } public static String getFileNameWithoutPath(String FilePath) { String file_name=""; Pattern p = Pattern.compile("(.*/)(.+)\\.\\w\\w\\w.?(txt)?$"); Matcher m = p.matcher(FilePath); if (m.matches()) { file_name = m.group(2); } return file_name; } public static String createDirectory(String rootPath,String directoryName) { File dir = new File(rootPath+"/"+directoryName); dir.mkdir(); String directory_path = dir.getPath(); return directory_path; } public static String createFolderAndGetPath(String path) { boolean result = false; File modelFolder = new File(path); if (!modelFolder.exists() || !modelFolder.isDirectory()) { result = modelFolder.mkdir(); } if (result == true || modelFolder.exists()) return path; else return null; } public static FileIterator getallFilesInDirectory(String root) { FileIterator file_iterator = new FileIterator(new File(root), null, FileIterator.LAST_DIRECTORY); return file_iterator; } }
Java
package utils; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import java.awt.GridBagLayout; import javax.swing.JSplitPane; import java.awt.GridBagConstraints; import javax.swing.JTextField; import java.awt.Insets; import javax.swing.JFileChooser; import javax.swing.JTextPane; import javax.swing.JScrollPane; import javax.swing.JLabel; import javax.swing.JButton; import javax.swing.JComboBox; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.io.File; public class XMLGenerateGui extends JFrame { private JPanel contentPane; private JTextField tbannfile; private JTextField tboutputfile; private File inputFile; private File outputDir; private File inputTextFile; private String filetype; private JComboBox comboBox; private JTextPane consolePane; private JTextField tbtextfile; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { XMLGenerateGui frame = new XMLGenerateGui(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public XMLGenerateGui() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 600, 400); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); GridBagLayout gbl_contentPane = new GridBagLayout(); gbl_contentPane.columnWidths = new int[]{0, 0}; gbl_contentPane.rowHeights = new int[]{0, 0}; gbl_contentPane.columnWeights = new double[]{1.0, Double.MIN_VALUE}; gbl_contentPane.rowWeights = new double[]{1.0, Double.MIN_VALUE}; contentPane.setLayout(gbl_contentPane); JSplitPane splitPane = new JSplitPane(); splitPane.setOrientation(JSplitPane.VERTICAL_SPLIT); GridBagConstraints gbc_splitPane = new GridBagConstraints(); gbc_splitPane.fill = GridBagConstraints.BOTH; gbc_splitPane.gridx = 0; gbc_splitPane.gridy = 0; contentPane.add(splitPane, gbc_splitPane); JPanel upperPanel = new JPanel(); splitPane.setLeftComponent(upperPanel); GridBagLayout gbl_upperPanel = new GridBagLayout(); gbl_upperPanel.columnWidths = new int[]{0, 0, 0, 0}; gbl_upperPanel.rowHeights = new int[]{0, 0, 0, 0, 0, 0}; gbl_upperPanel.columnWeights = new double[]{0.0, 1.0, 0.0, Double.MIN_VALUE}; gbl_upperPanel.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE}; upperPanel.setLayout(gbl_upperPanel); JLabel lblAnnotationFileLocation = new JLabel("Annotation File Location :"); GridBagConstraints gbc_lblAnnotationFileLocation = new GridBagConstraints(); gbc_lblAnnotationFileLocation.insets = new Insets(0, 0, 5, 5); gbc_lblAnnotationFileLocation.anchor = GridBagConstraints.EAST; gbc_lblAnnotationFileLocation.gridx = 0; gbc_lblAnnotationFileLocation.gridy = 0; upperPanel.add(lblAnnotationFileLocation, gbc_lblAnnotationFileLocation); tbannfile = new JTextField(); GridBagConstraints gbc_tbannfile = new GridBagConstraints(); gbc_tbannfile.insets = new Insets(0, 0, 5, 5); gbc_tbannfile.fill = GridBagConstraints.HORIZONTAL; gbc_tbannfile.gridx = 1; gbc_tbannfile.gridy = 0; upperPanel.add(tbannfile, gbc_tbannfile); tbannfile.setColumns(10); JButton btnBrowse = new JButton("Browse"); btnBrowse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { JFileChooser fc = new JFileChooser("."); fc.setFileSelectionMode(JFileChooser.FILES_ONLY); int returnVal = fc.showSaveDialog(XMLGenerateGui.this); if(returnVal == JFileChooser.APPROVE_OPTION){ inputFile = fc.getSelectedFile(); tbannfile.setText(inputFile.getPath()); } } }); GridBagConstraints gbc_btnBrowse = new GridBagConstraints(); gbc_btnBrowse.insets = new Insets(0, 0, 5, 0); gbc_btnBrowse.gridx = 2; gbc_btnBrowse.gridy = 0; upperPanel.add(btnBrowse, gbc_btnBrowse); JLabel lblTextFileLocation = new JLabel("Text File Location :"); GridBagConstraints gbc_lblTextFileLocation = new GridBagConstraints(); gbc_lblTextFileLocation.anchor = GridBagConstraints.EAST; gbc_lblTextFileLocation.insets = new Insets(0, 0, 5, 5); gbc_lblTextFileLocation.gridx = 0; gbc_lblTextFileLocation.gridy = 1; upperPanel.add(lblTextFileLocation, gbc_lblTextFileLocation); tbtextfile = new JTextField(); GridBagConstraints gbc_tbtextfile = new GridBagConstraints(); gbc_tbtextfile.insets = new Insets(0, 0, 5, 5); gbc_tbtextfile.fill = GridBagConstraints.HORIZONTAL; gbc_tbtextfile.gridx = 1; gbc_tbtextfile.gridy = 1; upperPanel.add(tbtextfile, gbc_tbtextfile); tbtextfile.setColumns(10); JButton btnBrowse_2 = new JButton("Browse"); btnBrowse_2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JFileChooser fc = new JFileChooser("."); fc.setFileSelectionMode(JFileChooser.FILES_ONLY); int returnVal = fc.showSaveDialog(XMLGenerateGui.this); if(returnVal == JFileChooser.APPROVE_OPTION){ inputTextFile = fc.getSelectedFile(); tbtextfile.setText(inputTextFile.getPath()); } } }); GridBagConstraints gbc_btnBrowse_2 = new GridBagConstraints(); gbc_btnBrowse_2.insets = new Insets(0, 0, 5, 0); gbc_btnBrowse_2.gridx = 2; gbc_btnBrowse_2.gridy = 1; upperPanel.add(btnBrowse_2, gbc_btnBrowse_2); JLabel lblTypeOfFile = new JLabel("Type of File :"); GridBagConstraints gbc_lblTypeOfFile = new GridBagConstraints(); gbc_lblTypeOfFile.anchor = GridBagConstraints.EAST; gbc_lblTypeOfFile.insets = new Insets(0, 0, 5, 5); gbc_lblTypeOfFile.gridx = 0; gbc_lblTypeOfFile.gridy = 2; upperPanel.add(lblTypeOfFile, gbc_lblTypeOfFile); comboBox = new JComboBox(); GridBagConstraints gbc_comboBox = new GridBagConstraints(); gbc_comboBox.insets = new Insets(0, 0, 5, 5); gbc_comboBox.fill = GridBagConstraints.HORIZONTAL; gbc_comboBox.gridx = 1; gbc_comboBox.gridy = 2; comboBox.addItem("Daily Strength File"); comboBox.addItem("Twitter File"); upperPanel.add(comboBox, gbc_comboBox); JLabel lblOutputFilesLocation = new JLabel("Output Files Location"); GridBagConstraints gbc_lblOutputFilesLocation = new GridBagConstraints(); gbc_lblOutputFilesLocation.anchor = GridBagConstraints.EAST; gbc_lblOutputFilesLocation.insets = new Insets(0, 0, 5, 5); gbc_lblOutputFilesLocation.gridx = 0; gbc_lblOutputFilesLocation.gridy = 3; upperPanel.add(lblOutputFilesLocation, gbc_lblOutputFilesLocation); tboutputfile = new JTextField(); GridBagConstraints gbc_tboutputfile = new GridBagConstraints(); gbc_tboutputfile.insets = new Insets(0, 0, 5, 5); gbc_tboutputfile.fill = GridBagConstraints.HORIZONTAL; gbc_tboutputfile.gridx = 1; gbc_tboutputfile.gridy = 3; upperPanel.add(tboutputfile, gbc_tboutputfile); tboutputfile.setColumns(10); JButton btnBrowse_1 = new JButton("Browse"); btnBrowse_1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { JFileChooser fc = new JFileChooser("."); fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int returnVal = fc.showSaveDialog(XMLGenerateGui.this); if(returnVal == JFileChooser.APPROVE_OPTION){ outputDir = fc.getSelectedFile(); tboutputfile.setText(outputDir.getPath()); } } }); GridBagConstraints gbc_btnBrowse_1 = new GridBagConstraints(); gbc_btnBrowse_1.insets = new Insets(0, 0, 5, 0); gbc_btnBrowse_1.gridx = 2; gbc_btnBrowse_1.gridy = 3; upperPanel.add(btnBrowse_1, gbc_btnBrowse_1); JButton btnGenerateXmlFiles = new JButton("Generate XML Files"); btnGenerateXmlFiles.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { // String str = comboBox.getSelectedItem().toString(); if(str.equals("Daily Strength File")) { filetype = "DS"; } else if(str.equals("Twitter File")) { filetype = "T"; } if(inputFile!=null && outputDir!=null && inputTextFile!=null) { if(filetype.equals("T")) { XMLGeneration obj = new XMLGeneration(); String result = obj.CreateXMLFilesforTwitter(inputFile, inputTextFile, outputDir); consolePane.setText(consolePane.getText() + "\n" + result); } else if(filetype.equals("DS")){ XMLGeneration obj = new XMLGeneration(); String result = obj.CreateXMLFilesforDS2(inputFile, inputTextFile, outputDir); consolePane.setText(consolePane.getText() + "\n" + result); } } } }); GridBagConstraints gbc_btnGenerateXmlFiles = new GridBagConstraints(); gbc_btnGenerateXmlFiles.gridx = 2; gbc_btnGenerateXmlFiles.gridy = 4; upperPanel.add(btnGenerateXmlFiles, gbc_btnGenerateXmlFiles); JPanel lowerPanel = new JPanel(); splitPane.setRightComponent(lowerPanel); GridBagLayout gbl_lowerPanel = new GridBagLayout(); gbl_lowerPanel.columnWidths = new int[]{0, 0}; gbl_lowerPanel.rowHeights = new int[]{0, 0, 0}; gbl_lowerPanel.columnWeights = new double[]{1.0, Double.MIN_VALUE}; gbl_lowerPanel.rowWeights = new double[]{1.0, 0.0, Double.MIN_VALUE}; lowerPanel.setLayout(gbl_lowerPanel); JScrollPane scrollPane = new JScrollPane(); GridBagConstraints gbc_scrollPane = new GridBagConstraints(); gbc_scrollPane.insets = new Insets(0, 0, 5, 0); gbc_scrollPane.fill = GridBagConstraints.BOTH; gbc_scrollPane.gridx = 0; gbc_scrollPane.gridy = 0; lowerPanel.add(scrollPane, gbc_scrollPane); consolePane = new JTextPane(); scrollPane.setViewportView(consolePane); JLabel lblNewLabel = new JLabel("Output Result:"); scrollPane.setColumnHeaderView(lblNewLabel); //lowerPanel.setFocusTraversalPolicy(new FocusTraversalOnArray(new Component[]{lblNewLabel, scrollPane, consolePane})); } }
Java
/* * Copyright 2011 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.apps.iosched.service; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.io.LocalBlocksHandler; import com.google.android.apps.iosched.io.LocalExecutor; import com.google.android.apps.iosched.io.LocalRoomsHandler; import com.google.android.apps.iosched.io.LocalSearchSuggestHandler; import com.google.android.apps.iosched.io.LocalSessionsHandler; import com.google.android.apps.iosched.io.LocalTracksHandler; import com.google.android.apps.iosched.io.RemoteExecutor; import com.google.android.apps.iosched.io.RemoteSessionsHandler; import com.google.android.apps.iosched.io.RemoteSpeakersHandler; import com.google.android.apps.iosched.io.RemoteVendorsHandler; import com.google.android.apps.iosched.io.RemoteWorksheetsHandler; import com.google.android.apps.iosched.provider.ScheduleProvider; import org.apache.http.Header; import org.apache.http.HeaderElement; import org.apache.http.HttpEntity; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseInterceptor; import org.apache.http.client.HttpClient; import org.apache.http.entity.HttpEntityWrapper; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams; import org.apache.http.protocol.HttpContext; import android.app.IntentService; import android.app.Service; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.Resources; import android.os.Bundle; import android.os.ResultReceiver; import android.text.format.DateUtils; import android.util.Log; import java.io.IOException; import java.io.InputStream; import java.util.zip.GZIPInputStream; /** * Background {@link Service} that synchronizes data living in * {@link ScheduleProvider}. Reads data from both local {@link Resources} and * from remote sources, such as a spreadsheet. */ public class SyncService extends IntentService { private static final String TAG = "SyncService"; public static final String EXTRA_STATUS_RECEIVER = "com.google.android.iosched.extra.STATUS_RECEIVER"; public static final int STATUS_RUNNING = 0x1; public static final int STATUS_ERROR = 0x2; public static final int STATUS_FINISHED = 0x3; private static final int SECOND_IN_MILLIS = (int) DateUtils.SECOND_IN_MILLIS; /** Root worksheet feed for online data source */ // TODO: insert your sessions/speakers/vendors spreadsheet doc URL here. private static final String WORKSHEETS_URL = "INSERT_SPREADSHEET_URL_HERE"; private static final String HEADER_ACCEPT_ENCODING = "Accept-Encoding"; private static final String ENCODING_GZIP = "gzip"; private static final int VERSION_NONE = 0; private static final int VERSION_CURRENT = 11; private LocalExecutor mLocalExecutor; private RemoteExecutor mRemoteExecutor; public SyncService() { super(TAG); } @Override public void onCreate() { super.onCreate(); final HttpClient httpClient = getHttpClient(this); final ContentResolver resolver = getContentResolver(); mLocalExecutor = new LocalExecutor(getResources(), resolver); mRemoteExecutor = new RemoteExecutor(httpClient, resolver); } @Override protected void onHandleIntent(Intent intent) { Log.d(TAG, "onHandleIntent(intent=" + intent.toString() + ")"); final ResultReceiver receiver = intent.getParcelableExtra(EXTRA_STATUS_RECEIVER); if (receiver != null) receiver.send(STATUS_RUNNING, Bundle.EMPTY); final Context context = this; final SharedPreferences prefs = getSharedPreferences(Prefs.IOSCHED_SYNC, Context.MODE_PRIVATE); final int localVersion = prefs.getInt(Prefs.LOCAL_VERSION, VERSION_NONE); try { // Bulk of sync work, performed by executing several fetches from // local and online sources. final long startLocal = System.currentTimeMillis(); final boolean localParse = localVersion < VERSION_CURRENT; Log.d(TAG, "found localVersion=" + localVersion + " and VERSION_CURRENT=" + VERSION_CURRENT); if (localParse) { // Load static local data mLocalExecutor.execute(R.xml.blocks, new LocalBlocksHandler()); mLocalExecutor.execute(R.xml.rooms, new LocalRoomsHandler()); mLocalExecutor.execute(R.xml.tracks, new LocalTracksHandler()); mLocalExecutor.execute(R.xml.search_suggest, new LocalSearchSuggestHandler()); mLocalExecutor.execute(R.xml.sessions, new LocalSessionsHandler()); // Parse values from local cache first, since spreadsheet copy // or network might be down. mLocalExecutor.execute(context, "cache-sessions.xml", new RemoteSessionsHandler()); mLocalExecutor.execute(context, "cache-speakers.xml", new RemoteSpeakersHandler()); mLocalExecutor.execute(context, "cache-vendors.xml", new RemoteVendorsHandler()); // Save local parsed version prefs.edit().putInt(Prefs.LOCAL_VERSION, VERSION_CURRENT).commit(); } Log.d(TAG, "local sync took " + (System.currentTimeMillis() - startLocal) + "ms"); // Always hit remote spreadsheet for any updates final long startRemote = System.currentTimeMillis(); mRemoteExecutor .executeGet(WORKSHEETS_URL, new RemoteWorksheetsHandler(mRemoteExecutor)); Log.d(TAG, "remote sync took " + (System.currentTimeMillis() - startRemote) + "ms"); } catch (Exception e) { Log.e(TAG, "Problem while syncing", e); if (receiver != null) { // Pass back error to surface listener final Bundle bundle = new Bundle(); bundle.putString(Intent.EXTRA_TEXT, e.toString()); receiver.send(STATUS_ERROR, bundle); } } // Announce success to any surface listener Log.d(TAG, "sync finished"); if (receiver != null) receiver.send(STATUS_FINISHED, Bundle.EMPTY); } /** * Generate and return a {@link HttpClient} configured for general use, * including setting an application-specific user-agent string. */ public static HttpClient getHttpClient(Context context) { final HttpParams params = new BasicHttpParams(); // Use generous timeouts for slow mobile networks HttpConnectionParams.setConnectionTimeout(params, 20 * SECOND_IN_MILLIS); HttpConnectionParams.setSoTimeout(params, 20 * SECOND_IN_MILLIS); HttpConnectionParams.setSocketBufferSize(params, 8192); HttpProtocolParams.setUserAgent(params, buildUserAgent(context)); final DefaultHttpClient client = new DefaultHttpClient(params); client.addRequestInterceptor(new HttpRequestInterceptor() { public void process(HttpRequest request, HttpContext context) { // Add header to accept gzip content if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) { request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP); } } }); client.addResponseInterceptor(new HttpResponseInterceptor() { public void process(HttpResponse response, HttpContext context) { // Inflate any responses compressed with gzip final HttpEntity entity = response.getEntity(); final Header encoding = entity.getContentEncoding(); if (encoding != null) { for (HeaderElement element : encoding.getElements()) { if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) { response.setEntity(new InflatingEntity(response.getEntity())); break; } } } } }); return client; } /** * Build and return a user-agent string that can identify this application * to remote servers. Contains the package name and version code. */ private static String buildUserAgent(Context context) { try { final PackageManager manager = context.getPackageManager(); final PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0); // Some APIs require "(gzip)" in the user-agent string. return info.packageName + "/" + info.versionName + " (" + info.versionCode + ") (gzip)"; } catch (NameNotFoundException e) { return null; } } /** * Simple {@link HttpEntityWrapper} that inflates the wrapped * {@link HttpEntity} by passing it through {@link GZIPInputStream}. */ private static class InflatingEntity extends HttpEntityWrapper { public InflatingEntity(HttpEntity wrapped) { super(wrapped); } @Override public InputStream getContent() throws IOException { return new GZIPInputStream(wrappedEntity.getContent()); } @Override public long getContentLength() { return -1; } } private interface Prefs { String IOSCHED_SYNC = "iosched_sync"; String LOCAL_VERSION = "local_version"; } }
Java
/* * Copyright 2011 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.apps.iosched.ui; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.widget.BlockView; import com.google.android.apps.iosched.ui.widget.BlocksLayout; import com.google.android.apps.iosched.ui.widget.ObservableScrollView; import com.google.android.apps.iosched.ui.widget.Workspace; import com.google.android.apps.iosched.util.AnalyticsUtils; import com.google.android.apps.iosched.util.Maps; import com.google.android.apps.iosched.util.MotionEventUtils; import com.google.android.apps.iosched.util.NotifyingAsyncQueryHandler; import com.google.android.apps.iosched.util.ParserUtils; import com.google.android.apps.iosched.util.UIUtils; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.database.ContentObserver; import android.database.Cursor; import android.graphics.Rect; import android.graphics.drawable.LayerDrawable; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.provider.BaseColumns; import android.support.v4.app.Fragment; import android.text.format.DateUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.TimeZone; /** * Shows a horizontally-pageable calendar of conference days. Horizontaly paging is achieved using * {@link Workspace}, and the primary UI classes for rendering the calendar are * {@link com.google.android.apps.iosched.ui.widget.TimeRulerView}, * {@link BlocksLayout}, and {@link BlockView}. */ public class ScheduleFragment extends Fragment implements NotifyingAsyncQueryHandler.AsyncQueryListener, ObservableScrollView.OnScrollListener, View.OnClickListener { private static final String TAG = "ScheduleFragment"; /** * Flags used with {@link android.text.format.DateUtils#formatDateRange}. */ private static final int TIME_FLAGS = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_ABBREV_WEEKDAY; private static final long TUE_START = ParserUtils.parseTime("2011-05-10T00:00:00.000-07:00"); private static final long WED_START = ParserUtils.parseTime("2011-05-11T00:00:00.000-07:00"); private static final int DISABLED_BLOCK_ALPHA = 100; private static final HashMap<String, Integer> sTypeColumnMap = buildTypeColumnMap(); // TODO: show blocks that don't fall into columns at the bottom public static final String EXTRA_TIME_START = "com.google.android.iosched.extra.TIME_START"; public static final String EXTRA_TIME_END = "com.google.android.iosched.extra.TIME_END"; private NotifyingAsyncQueryHandler mHandler; private Workspace mWorkspace; private TextView mTitle; private int mTitleCurrentDayIndex = -1; private View mLeftIndicator; private View mRightIndicator; /** * A helper class containing object references related to a particular day in the schedule. */ private class Day { private ViewGroup rootView; private ObservableScrollView scrollView; private View nowView; private BlocksLayout blocksView; private int index = -1; private String label = null; private Uri blocksUri = null; private long timeStart = -1; private long timeEnd = -1; } private List<Day> mDays = new ArrayList<Day>(); private static HashMap<String, Integer> buildTypeColumnMap() { final HashMap<String, Integer> map = Maps.newHashMap(); map.put(ParserUtils.BLOCK_TYPE_FOOD, 0); map.put(ParserUtils.BLOCK_TYPE_SESSION, 1); map.put(ParserUtils.BLOCK_TYPE_OFFICE_HOURS, 2); return map; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mHandler = new NotifyingAsyncQueryHandler(getActivity().getContentResolver(), this); setHasOptionsMenu(true); AnalyticsUtils.getInstance(getActivity()).trackPageView("/Schedule"); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_schedule, null); mWorkspace = (Workspace) root.findViewById(R.id.workspace); mTitle = (TextView) root.findViewById(R.id.block_title); mLeftIndicator = root.findViewById(R.id.indicator_left); mLeftIndicator.setOnTouchListener(new View.OnTouchListener() { public boolean onTouch(View view, MotionEvent motionEvent) { if ((motionEvent.getAction() & MotionEventUtils.ACTION_MASK) == MotionEvent.ACTION_DOWN) { mWorkspace.scrollLeft(); return true; } return false; } }); mLeftIndicator.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { mWorkspace.scrollLeft(); } }); mRightIndicator = root.findViewById(R.id.indicator_right); mRightIndicator.setOnTouchListener(new View.OnTouchListener() { public boolean onTouch(View view, MotionEvent motionEvent) { if ((motionEvent.getAction() & MotionEventUtils.ACTION_MASK) == MotionEvent.ACTION_DOWN) { mWorkspace.scrollRight(); return true; } return false; } }); mRightIndicator.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { mWorkspace.scrollRight(); } }); setupDay(inflater, TUE_START); setupDay(inflater, WED_START); updateWorkspaceHeader(0); mWorkspace.setOnScrollListener(new Workspace.OnScrollListener() { public void onScroll(float screenFraction) { updateWorkspaceHeader(Math.round(screenFraction)); } }, true); return root; } public void updateWorkspaceHeader(int dayIndex) { if (mTitleCurrentDayIndex == dayIndex) { return; } mTitleCurrentDayIndex = dayIndex; Day day = mDays.get(dayIndex); mTitle.setText(day.label); mLeftIndicator .setVisibility((dayIndex != 0) ? View.VISIBLE : View.INVISIBLE); mRightIndicator .setVisibility((dayIndex < mDays.size() - 1) ? View.VISIBLE : View.INVISIBLE); } private void setupDay(LayoutInflater inflater, long startMillis) { Day day = new Day(); // Setup data day.index = mDays.size(); day.timeStart = startMillis; day.timeEnd = startMillis + DateUtils.DAY_IN_MILLIS; day.blocksUri = ScheduleContract.Blocks.buildBlocksBetweenDirUri( day.timeStart, day.timeEnd); // Setup views day.rootView = (ViewGroup) inflater.inflate(R.layout.blocks_content, null); day.scrollView = (ObservableScrollView) day.rootView.findViewById(R.id.blocks_scroll); day.scrollView.setOnScrollListener(this); day.blocksView = (BlocksLayout) day.rootView.findViewById(R.id.blocks); day.nowView = day.rootView.findViewById(R.id.blocks_now); day.blocksView.setDrawingCacheEnabled(true); day.blocksView.setAlwaysDrawnWithCacheEnabled(true); TimeZone.setDefault(UIUtils.CONFERENCE_TIME_ZONE); day.label = DateUtils.formatDateTime(getActivity(), startMillis, TIME_FLAGS); mWorkspace.addView(day.rootView); mDays.add(day); } @Override public void onResume() { super.onResume(); // Since we build our views manually instead of using an adapter, we // need to manually requery every time launched. requery(); getActivity().getContentResolver().registerContentObserver( ScheduleContract.Sessions.CONTENT_URI, true, mSessionChangesObserver); // Start listening for time updates to adjust "now" bar. TIME_TICK is // triggered once per minute, which is how we move the bar over time. final IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_TIME_TICK); filter.addAction(Intent.ACTION_TIME_CHANGED); filter.addAction(Intent.ACTION_TIMEZONE_CHANGED); getActivity().registerReceiver(mReceiver, filter, null, new Handler()); } private void requery() { for (Day day : mDays) { mHandler.startQuery(0, day, day.blocksUri, BlocksQuery.PROJECTION, null, null, ScheduleContract.Blocks.DEFAULT_SORT); } } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); getActivity().runOnUiThread(new Runnable() { public void run() { updateNowView(true); } }); } @Override public void onPause() { super.onPause(); getActivity().unregisterReceiver(mReceiver); getActivity().getContentResolver().unregisterContentObserver(mSessionChangesObserver); } /** * {@inheritDoc} */ public void onQueryComplete(int token, Object cookie, Cursor cursor) { if (getActivity() == null) { return; } Day day = (Day) cookie; // Clear out any existing sessions before inserting again day.blocksView.removeAllBlocks(); try { while (cursor.moveToNext()) { final String type = cursor.getString(BlocksQuery.BLOCK_TYPE); final Integer column = sTypeColumnMap.get(type); // TODO: place random blocks at bottom of entire layout if (column == null) { continue; } final String blockId = cursor.getString(BlocksQuery.BLOCK_ID); final String title = cursor.getString(BlocksQuery.BLOCK_TITLE); final long start = cursor.getLong(BlocksQuery.BLOCK_START); final long end = cursor.getLong(BlocksQuery.BLOCK_END); final boolean containsStarred = cursor.getInt(BlocksQuery.CONTAINS_STARRED) != 0; final BlockView blockView = new BlockView(getActivity(), blockId, title, start, end, containsStarred, column); final int sessionsCount = cursor.getInt(BlocksQuery.SESSIONS_COUNT); if (sessionsCount > 0) { blockView.setOnClickListener(this); } else { blockView.setFocusable(false); blockView.setEnabled(false); LayerDrawable buttonDrawable = (LayerDrawable) blockView.getBackground(); buttonDrawable.getDrawable(0).setAlpha(DISABLED_BLOCK_ALPHA); buttonDrawable.getDrawable(2).setAlpha(DISABLED_BLOCK_ALPHA); } day.blocksView.addBlock(blockView); } } finally { cursor.close(); } } /** {@inheritDoc} */ public void onClick(View view) { if (view instanceof BlockView) { String title = ((BlockView)view).getText().toString(); AnalyticsUtils.getInstance(getActivity()).trackEvent( "Schedule", "Session Click", title, 0); final String blockId = ((BlockView) view).getBlockId(); final Uri sessionsUri = ScheduleContract.Blocks.buildSessionsUri(blockId); final Intent intent = new Intent(Intent.ACTION_VIEW, sessionsUri); intent.putExtra(SessionsFragment.EXTRA_SCHEDULE_TIME_STRING, ((BlockView) view).getBlockTimeString()); ((BaseActivity) getActivity()).openActivityOrFragment(intent); } } /** * Update position and visibility of "now" view. */ private boolean updateNowView(boolean forceScroll) { final long now = UIUtils.getCurrentTime(getActivity()); Day nowDay = null; // effectively Day corresponding to today for (Day day : mDays) { if (now >= day.timeStart && now <= day.timeEnd) { nowDay = day; day.nowView.setVisibility(View.VISIBLE); } else { day.nowView.setVisibility(View.GONE); } } if (nowDay != null && forceScroll) { // Scroll to show "now" in center mWorkspace.setCurrentScreen(nowDay.index); final int offset = nowDay.scrollView.getHeight() / 2; nowDay.nowView.requestRectangleOnScreen(new Rect(0, offset, 0, offset), true); nowDay.blocksView.requestLayout(); return true; } return false; } public void onScrollChanged(ObservableScrollView view) { // Keep each day view at the same vertical scroll offset. final int scrollY = view.getScrollY(); for (Day day : mDays) { if (day.scrollView != view) { day.scrollView.scrollTo(0, scrollY); } } } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.schedule_menu_items, menu); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.menu_now) { if (!updateNowView(true)) { Toast.makeText(getActivity(), R.string.toast_now_not_visible, Toast.LENGTH_SHORT).show(); } return true; } return super.onOptionsItemSelected(item); } private ContentObserver mSessionChangesObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfChange) { requery(); } }; private BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Log.d(TAG, "onReceive time update"); updateNowView(false); } }; private interface BlocksQuery { String[] PROJECTION = { BaseColumns._ID, ScheduleContract.Blocks.BLOCK_ID, ScheduleContract.Blocks.BLOCK_TITLE, ScheduleContract.Blocks.BLOCK_START, ScheduleContract.Blocks.BLOCK_END, ScheduleContract.Blocks.BLOCK_TYPE, ScheduleContract.Blocks.SESSIONS_COUNT, ScheduleContract.Blocks.CONTAINS_STARRED, }; int _ID = 0; int BLOCK_ID = 1; int BLOCK_TITLE = 2; int BLOCK_START = 3; int BLOCK_END = 4; int BLOCK_TYPE = 5; int SESSIONS_COUNT = 6; int CONTAINS_STARRED = 7; } }
Java
/* * Copyright 2011 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.apps.iosched.ui; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.AnalyticsUtils; import com.google.android.apps.iosched.util.NotifyingAsyncQueryHandler; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; /** * A simple {@link ListFragment} that renders a list of tracks with available sessions or vendors * (depending on {@link TracksFragment#EXTRA_NEXT_TYPE}) using a {@link TracksAdapter}. */ public class TracksFragment extends ListFragment implements NotifyingAsyncQueryHandler.AsyncQueryListener { public static final String EXTRA_NEXT_TYPE = "com.google.android.iosched.extra.NEXT_TYPE"; public static final String NEXT_TYPE_SESSIONS = "sessions"; public static final String NEXT_TYPE_VENDORS = "vendors"; private TracksAdapter mAdapter; private NotifyingAsyncQueryHandler mHandler; private String mNextType; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Intent intent = BaseActivity.fragmentArgumentsToIntent(getArguments()); final Uri tracksUri = intent.getData(); mNextType = intent.getStringExtra(EXTRA_NEXT_TYPE); mAdapter = new TracksAdapter(getActivity()); setListAdapter(mAdapter); // Filter our tracks query to only include those with valid results String[] projection = TracksAdapter.TracksQuery.PROJECTION; String selection = null; if (NEXT_TYPE_SESSIONS.equals(mNextType)) { // Only show tracks with at least one session projection = TracksAdapter.TracksQuery.PROJECTION_WITH_SESSIONS_COUNT; selection = ScheduleContract.Tracks.SESSIONS_COUNT + ">0"; AnalyticsUtils.getInstance(getActivity()).trackPageView("/Tracks"); } else if (NEXT_TYPE_VENDORS.equals(mNextType)) { // Only show tracks with at least one vendor projection = TracksAdapter.TracksQuery.PROJECTION_WITH_VENDORS_COUNT; selection = ScheduleContract.Tracks.VENDORS_COUNT + ">0"; AnalyticsUtils.getInstance(getActivity()).trackPageView("/Sandbox"); } // Start background query to load tracks mHandler = new NotifyingAsyncQueryHandler(getActivity().getContentResolver(), this); mHandler.startQuery(tracksUri, projection, selection, null, ScheduleContract.Tracks.DEFAULT_SORT); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_list_with_spinner, null); // For some reason, if we omit this, NoSaveStateFrameLayout thinks we are // FILL_PARENT / WRAP_CONTENT, making the progress bar stick to the top of the activity. root.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT)); return root; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE); } /** {@inheritDoc} */ public void onQueryComplete(int token, Object cookie, Cursor cursor) { if (getActivity() == null) { return; } getActivity().startManagingCursor(cursor); mAdapter.setHasAllItem(true); mAdapter.setIsSessions(TracksFragment.NEXT_TYPE_SESSIONS.equals(mNextType)); mAdapter.changeCursor(cursor); } /** {@inheritDoc} */ @Override public void onListItemClick(ListView l, View v, int position, long id) { final Cursor cursor = (Cursor) mAdapter.getItem(position); final String trackId; if (cursor != null) { trackId = cursor.getString(TracksAdapter.TracksQuery.TRACK_ID); } else { trackId = ScheduleContract.Tracks.ALL_TRACK_ID; } final Intent intent = new Intent(Intent.ACTION_VIEW); final Uri trackUri = ScheduleContract.Tracks.buildTrackUri(trackId); intent.putExtra(SessionDetailFragment.EXTRA_TRACK, trackUri); if (NEXT_TYPE_SESSIONS.equals(mNextType)) { if (cursor == null) { intent.setData(ScheduleContract.Sessions.CONTENT_URI); } else { intent.setData(ScheduleContract.Tracks.buildSessionsUri(trackId)); } } else if (NEXT_TYPE_VENDORS.equals(mNextType)) { if (cursor == null) { intent.setData(ScheduleContract.Vendors.CONTENT_URI); } else { intent.setData(ScheduleContract.Tracks.buildVendorsUri(trackId)); } } ((BaseActivity) getActivity()).openActivityOrFragment(intent); getListView().setItemChecked(position, true); } }
Java
/* * Copyright 2011 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.apps.iosched.ui; import com.google.android.apps.iosched.util.ActivityHelper; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; /** * A base activity that defers common functionality across app activities to an * {@link ActivityHelper}. This class shouldn't be used directly; instead, activities should * inherit from {@link BaseSinglePaneActivity} or {@link BaseMultiPaneActivity}. */ public abstract class BaseActivity extends FragmentActivity { final ActivityHelper mActivityHelper = ActivityHelper.createInstance(this); @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); mActivityHelper.onPostCreate(savedInstanceState); } @Override public boolean onKeyLongPress(int keyCode, KeyEvent event) { return mActivityHelper.onKeyLongPress(keyCode, event) || super.onKeyLongPress(keyCode, event); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { return mActivityHelper.onKeyDown(keyCode, event) || super.onKeyDown(keyCode, event); } @Override public boolean onCreateOptionsMenu(Menu menu) { return mActivityHelper.onCreateOptionsMenu(menu) || super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { return mActivityHelper.onOptionsItemSelected(item) || super.onOptionsItemSelected(item); } /** * Returns the {@link ActivityHelper} object associated with this activity. */ protected ActivityHelper getActivityHelper() { return mActivityHelper; } /** * Takes a given intent and either starts a new activity to handle it (the default behavior), * or creates/updates a fragment (in the case of a multi-pane activity) that can handle the * intent. * * Must be called from the main (UI) thread. */ public void openActivityOrFragment(Intent intent) { // Default implementation simply calls startActivity startActivity(intent); } /** * Converts an intent into a {@link Bundle} suitable for use as fragment arguments. */ public static Bundle intentToFragmentArguments(Intent intent) { Bundle arguments = new Bundle(); if (intent == null) { return arguments; } final Uri data = intent.getData(); if (data != null) { arguments.putParcelable("_uri", data); } final Bundle extras = intent.getExtras(); if (extras != null) { arguments.putAll(intent.getExtras()); } return arguments; } /** * Converts a fragment arguments bundle into an intent. */ public static Intent fragmentArgumentsToIntent(Bundle arguments) { Intent intent = new Intent(); if (arguments == null) { return intent; } final Uri data = arguments.getParcelable("_uri"); if (data != null) { intent.setData(data); } intent.putExtras(arguments); intent.removeExtra("_uri"); return intent; } }
Java
/* * Copyright 2011 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.apps.iosched.ui; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.tablet.NowPlayingMultiPaneActivity; import com.google.android.apps.iosched.util.AnalyticsUtils; import com.google.android.apps.iosched.util.UIUtils; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.support.v4.app.Fragment; import android.text.format.DateUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; /** * A fragment used in {@link HomeActivity} that shows either a countdown, 'now playing' link to * current sessions, or 'thank you' text, at different times (before/during/after the conference). * It also shows a 'Realtime Search' button on phones, as a replacement for the * {@link TagStreamFragment} that is visible on tablets on the home screen. */ public class WhatsOnFragment extends Fragment { private Handler mMessageHandler = new Handler(); private TextView mCountdownTextView; private ViewGroup mRootView; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = (ViewGroup) inflater.inflate(R.layout.fragment_whats_on, container); refresh(); return mRootView; } @Override public void onAttach(Activity activity) { super.onAttach(activity); } @Override public void onDetach() { super.onDetach(); mMessageHandler.removeCallbacks(mCountdownRunnable); } private void refresh() { mMessageHandler.removeCallbacks(mCountdownRunnable); mRootView.removeAllViews(); final long currentTimeMillis = UIUtils.getCurrentTime(getActivity()); // Show Loading... and load the view corresponding to the current state if (currentTimeMillis < UIUtils.CONFERENCE_START_MILLIS) { setupBefore(); } else if (currentTimeMillis > UIUtils.CONFERENCE_END_MILLIS) { setupAfter(); } else { setupDuring(); } if (!UIUtils.isHoneycombTablet(getActivity())) { View separator = new View(getActivity()); separator.setLayoutParams( new ViewGroup.LayoutParams(1, ViewGroup.LayoutParams.FILL_PARENT)); separator.setBackgroundResource(R.drawable.whats_on_separator); mRootView.addView(separator); View view = getActivity().getLayoutInflater().inflate( R.layout.whats_on_stream, mRootView, false); view.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { AnalyticsUtils.getInstance(getActivity()).trackEvent( "Home Screen Dashboard", "Click", "Realtime Stream", 0); Intent intent = new Intent(getActivity(), TagStreamActivity.class); startActivity(intent); } }); mRootView.addView(view); } } private void setupBefore() { // Before conference, show countdown. mCountdownTextView = (TextView) getActivity().getLayoutInflater().inflate( R.layout.whats_on_countdown, mRootView, false); mRootView.addView(mCountdownTextView); mMessageHandler.post(mCountdownRunnable); } private void setupAfter() { // After conference, show canned text. getActivity().getLayoutInflater().inflate( R.layout.whats_on_thank_you, mRootView, true); } private void setupDuring() { // Conference in progress, show "Now Playing" link. View view = getActivity().getLayoutInflater().inflate( R.layout.whats_on_now_playing, mRootView, false); view.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { if (UIUtils.isHoneycombTablet(getActivity())) { startActivity(new Intent(getActivity(), NowPlayingMultiPaneActivity.class)); } else { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(ScheduleContract.Sessions .buildSessionsAtDirUri(System.currentTimeMillis())); intent.putExtra(Intent.EXTRA_TITLE, getString(R.string.title_now_playing)); startActivity(intent); } } }); mRootView.addView(view); } /** * Event that updates countdown timer. Posts itself again to {@link #mMessageHandler} to * continue updating time. */ private Runnable mCountdownRunnable = new Runnable() { public void run() { int remainingSec = (int) Math.max(0, (UIUtils.CONFERENCE_START_MILLIS - System.currentTimeMillis()) / 1000); final boolean conferenceStarted = remainingSec == 0; if (conferenceStarted) { // Conference started while in countdown mode, switch modes and // bail on future countdown updates. mMessageHandler.postDelayed(new Runnable() { public void run() { refresh(); } }, 100); return; } final int secs = remainingSec % 86400; final int days = remainingSec / 86400; final String str = getResources().getQuantityString( R.plurals.whats_on_countdown_title, days, days, DateUtils.formatElapsedTime(secs)); mCountdownTextView.setText(str); // Repost ourselves to keep updating countdown mMessageHandler.postDelayed(mCountdownRunnable, 1000); } }; }
Java
/* * Copyright 2011 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.apps.iosched.ui.phone; import com.google.android.apps.iosched.ui.BaseSinglePaneActivity; import com.google.android.apps.iosched.ui.SessionsFragment; import android.os.Bundle; import android.support.v4.app.Fragment; public class SessionsActivity extends BaseSinglePaneActivity { @Override protected Fragment onCreatePane() { return new SessionsFragment(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getActivityHelper().setupSubActivity(); } }
Java
/* * Copyright 2011 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.apps.iosched.ui.phone; import com.google.android.apps.iosched.ui.BaseSinglePaneActivity; import com.google.android.apps.iosched.ui.MapFragment; import android.os.Bundle; import android.support.v4.app.Fragment; public class MapActivity extends BaseSinglePaneActivity { @Override protected Fragment onCreatePane() { return new MapFragment(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getActivityHelper().setupSubActivity(); } }
Java
/* * Copyright 2011 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.apps.iosched.ui.phone; import com.google.android.apps.iosched.ui.BaseSinglePaneActivity; import com.google.android.apps.iosched.ui.VendorDetailFragment; import android.os.Bundle; import android.support.v4.app.Fragment; public class VendorDetailActivity extends BaseSinglePaneActivity { @Override protected Fragment onCreatePane() { return new VendorDetailFragment(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getActivityHelper().setupSubActivity(); } }
Java
/* * Copyright 2011 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.apps.iosched.ui.phone; import com.google.android.apps.iosched.ui.BaseSinglePaneActivity; import com.google.android.apps.iosched.ui.SessionDetailFragment; import android.os.Bundle; import android.support.v4.app.Fragment; public class SessionDetailActivity extends BaseSinglePaneActivity { @Override protected Fragment onCreatePane() { return new SessionDetailFragment(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getActivityHelper().setupSubActivity(); } }
Java
/* * Copyright 2011 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.apps.iosched.ui.phone; import com.google.android.apps.iosched.ui.BaseSinglePaneActivity; import com.google.android.apps.iosched.ui.TracksFragment; import android.os.Bundle; import android.support.v4.app.Fragment; public class TracksActivity extends BaseSinglePaneActivity { @Override protected Fragment onCreatePane() { return new TracksFragment(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getActivityHelper().setupSubActivity(); } }
Java
/* * Copyright 2011 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.apps.iosched.ui.phone; import com.google.android.apps.iosched.ui.BaseSinglePaneActivity; import com.google.android.apps.iosched.ui.VendorsFragment; import android.os.Bundle; import android.support.v4.app.Fragment; public class VendorsActivity extends BaseSinglePaneActivity { @Override protected Fragment onCreatePane() { return new VendorsFragment(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getActivityHelper().setupSubActivity(); } }
Java
/* * Copyright 2011 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.apps.iosched.ui.phone; import com.google.android.apps.iosched.ui.BaseSinglePaneActivity; import com.google.android.apps.iosched.ui.ScheduleFragment; import android.os.Bundle; import android.support.v4.app.Fragment; public class ScheduleActivity extends BaseSinglePaneActivity { @Override protected Fragment onCreatePane() { return new ScheduleFragment(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getActivityHelper().setupSubActivity(); } }
Java
/* * Copyright 2011 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.apps.iosched.ui.tablet; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.ui.BaseMultiPaneActivity; import com.google.android.apps.iosched.ui.SessionDetailFragment; import com.google.android.apps.iosched.ui.SessionsFragment; import com.google.android.apps.iosched.ui.phone.SessionDetailActivity; import com.google.android.apps.iosched.ui.phone.SessionsActivity; import android.app.FragmentBreadCrumbs; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.view.View; import android.view.ViewGroup; /** * A multi-pane activity, where the primary navigation pane is a * {@link com.google.android.apps.iosched.ui.ScheduleFragment}, that * shows {@link SessionsFragment} and {@link SessionDetailFragment} as popups. * * This activity requires API level 11 or greater because of its use of {@link FragmentBreadCrumbs}. */ public class ScheduleMultiPaneActivity extends BaseMultiPaneActivity implements View.OnClickListener, FragmentManager.OnBackStackChangedListener { private FragmentManager mFragmentManager; private FragmentBreadCrumbs mFragmentBreadCrumbs; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_schedule); mFragmentManager = getSupportFragmentManager(); mFragmentBreadCrumbs = (FragmentBreadCrumbs) findViewById(R.id.breadcrumbs); mFragmentBreadCrumbs.setActivity(this); mFragmentManager.addOnBackStackChangedListener(this); updateBreadCrumb(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getActivityHelper().setupSubActivity(); ViewGroup detailContainer = (ViewGroup) findViewById(R.id.fragment_container_schedule_detail); if (detailContainer != null && detailContainer.getChildCount() > 0) { findViewById(R.id.fragment_container_schedule_detail).setBackgroundColor(0); } } @Override public FragmentReplaceInfo onSubstituteFragmentForActivityLaunch(String activityClassName) { if (SessionsActivity.class.getName().equals(activityClassName)) { getSupportFragmentManager().popBackStack(); findViewById(R.id.fragment_container_schedule_detail).setBackgroundColor(0); return new FragmentReplaceInfo( SessionsFragment.class, "sessions", R.id.fragment_container_schedule_detail); } else if (SessionDetailActivity.class.getName().equals(activityClassName)) { findViewById(R.id.fragment_container_schedule_detail).setBackgroundColor(0); return new FragmentReplaceInfo( SessionDetailFragment.class, "session_detail", R.id.fragment_container_schedule_detail); } return null; } @Override protected void onBeforeCommitReplaceFragment(FragmentManager fm, FragmentTransaction ft, Fragment fragment) { super.onBeforeCommitReplaceFragment(fm, ft, fragment); if (fragment instanceof SessionDetailFragment) { ft.addToBackStack(null); } else if (fragment instanceof SessionsFragment) { fm.popBackStack(); } updateBreadCrumb(); } /** * Handler for the breadcrumb parent. */ public void onClick(View view) { mFragmentManager.popBackStack(); } public void onBackStackChanged() { updateBreadCrumb(); } public void updateBreadCrumb() { final String title = getString(R.string.title_sessions); final String detailTitle = getString(R.string.title_session_detail); if (mFragmentManager.getBackStackEntryCount() >= 1) { mFragmentBreadCrumbs.setParentTitle(title, title, this); mFragmentBreadCrumbs.setTitle(detailTitle, detailTitle); } else { mFragmentBreadCrumbs.setParentTitle(null, null, null); mFragmentBreadCrumbs.setTitle(title, title); } } }
Java
/* * Copyright 2011 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.apps.iosched.ui.tablet; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.BaseMultiPaneActivity; import com.google.android.apps.iosched.ui.TracksFragment; import com.google.android.apps.iosched.ui.VendorDetailFragment; import com.google.android.apps.iosched.ui.VendorsFragment; import com.google.android.apps.iosched.ui.phone.VendorDetailActivity; import com.google.android.apps.iosched.ui.phone.VendorsActivity; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.view.ViewGroup; /** * A multi-pane activity, consisting of a {@link TracksDropdownFragment}, a * {@link VendorsFragment}, and {@link VendorDetailFragment}. This activity is very similar in * function to {@link SessionsMultiPaneActivity}. * * This activity requires API level 11 or greater because {@link TracksDropdownFragment} requires * API level 11. */ public class VendorsMultiPaneActivity extends BaseMultiPaneActivity { private TracksDropdownFragment mTracksDropdownFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView( R.layout.activity_vendors); Intent intent = new Intent(); intent.setData(ScheduleContract.Tracks.CONTENT_URI); intent.putExtra(TracksFragment.EXTRA_NEXT_TYPE, TracksFragment.NEXT_TYPE_VENDORS); final FragmentManager fm = getSupportFragmentManager(); mTracksDropdownFragment = (TracksDropdownFragment) fm.findFragmentById( R.id.fragment_tracks_dropdown); mTracksDropdownFragment.reloadFromArguments(intentToFragmentArguments(intent)); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getActivityHelper().setupSubActivity(); ViewGroup detailContainer = (ViewGroup) findViewById(R.id.fragment_container_vendor_detail); if (detailContainer != null && detailContainer.getChildCount() > 0) { findViewById(R.id.fragment_container_vendor_detail).setBackgroundColor(0xffffffff); } } @Override public FragmentReplaceInfo onSubstituteFragmentForActivityLaunch(String activityClassName) { if (VendorsActivity.class.getName().equals(activityClassName)) { return new FragmentReplaceInfo( VendorsFragment.class, "vendors", R.id.fragment_container_vendors); } else if (VendorDetailActivity.class.getName().equals(activityClassName)) { findViewById(R.id.fragment_container_vendor_detail).setBackgroundColor( 0xffffffff); return new FragmentReplaceInfo( VendorDetailFragment.class, "vendor_detail", R.id.fragment_container_vendor_detail); } return null; } }
Java
/* * Copyright 2011 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.apps.iosched.ui.tablet; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.BaseActivity; import com.google.android.apps.iosched.ui.SessionDetailFragment; import com.google.android.apps.iosched.ui.TracksAdapter; import com.google.android.apps.iosched.ui.TracksFragment; import com.google.android.apps.iosched.util.NotifyingAsyncQueryHandler; import com.google.android.apps.iosched.util.UIUtils; import android.content.Intent; import android.content.res.Resources; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListPopupWindow; import android.widget.PopupWindow; import android.widget.TextView; /** * A tablet-specific fragment that is a giant {@link android.widget.Spinner}-like widget. It shows * a {@link ListPopupWindow} containing a list of tracks, using {@link TracksAdapter}. * * Requires API level 11 or later since {@link ListPopupWindow} is API level 11+. */ public class TracksDropdownFragment extends Fragment implements NotifyingAsyncQueryHandler.AsyncQueryListener, AdapterView.OnItemClickListener, PopupWindow.OnDismissListener { public static final String EXTRA_NEXT_TYPE = "com.google.android.iosched.extra.NEXT_TYPE"; public static final String NEXT_TYPE_SESSIONS = "sessions"; public static final String NEXT_TYPE_VENDORS = "vendors"; private boolean mAutoloadTarget = true; private Cursor mCursor; private TracksAdapter mAdapter; private String mNextType; private ListPopupWindow mListPopupWindow; private ViewGroup mRootView; private TextView mTitle; private TextView mAbstract; private NotifyingAsyncQueryHandler mHandler; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mHandler = new NotifyingAsyncQueryHandler(getActivity().getContentResolver(), this); mAdapter = new TracksAdapter(getActivity()); if (savedInstanceState != null) { // Prevent auto-load behavior on orientation change. mAutoloadTarget = false; } reloadFromArguments(getArguments()); } public void reloadFromArguments(Bundle arguments) { // Teardown from previous arguments if (mListPopupWindow != null) { mListPopupWindow.setAdapter(null); } if (mCursor != null) { getActivity().stopManagingCursor(mCursor); mCursor = null; } mHandler.cancelOperation(TracksAdapter.TracksQuery._TOKEN); // Load new arguments final Intent intent = BaseActivity.fragmentArgumentsToIntent(arguments); final Uri tracksUri = intent.getData(); if (tracksUri == null) { return; } mNextType = intent.getStringExtra(EXTRA_NEXT_TYPE); // Filter our tracks query to only include those with valid results String[] projection = TracksAdapter.TracksQuery.PROJECTION; String selection = null; if (TracksFragment.NEXT_TYPE_SESSIONS.equals(mNextType)) { // Only show tracks with at least one session projection = TracksAdapter.TracksQuery.PROJECTION_WITH_SESSIONS_COUNT; selection = ScheduleContract.Tracks.SESSIONS_COUNT + ">0"; } else if (TracksFragment.NEXT_TYPE_VENDORS.equals(mNextType)) { // Only show tracks with at least one vendor projection = TracksAdapter.TracksQuery.PROJECTION_WITH_VENDORS_COUNT; selection = ScheduleContract.Tracks.VENDORS_COUNT + ">0"; } // Start background query to load tracks mHandler.startQuery(TracksAdapter.TracksQuery._TOKEN, null, tracksUri, projection, selection, null, ScheduleContract.Tracks.DEFAULT_SORT); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = (ViewGroup) inflater.inflate(R.layout.fragment_tracks_dropdown, null); mTitle = (TextView) mRootView.findViewById(R.id.track_title); mAbstract = (TextView) mRootView.findViewById(R.id.track_abstract); mRootView.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { mListPopupWindow = new ListPopupWindow(getActivity()); mListPopupWindow.setAdapter(mAdapter); mListPopupWindow.setModal(true); mListPopupWindow.setContentWidth(400); mListPopupWindow.setAnchorView(mRootView); mListPopupWindow.setOnItemClickListener(TracksDropdownFragment.this); mListPopupWindow.show(); mListPopupWindow.setOnDismissListener(TracksDropdownFragment.this); } }); return mRootView; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } /** {@inheritDoc} */ public void onQueryComplete(int token, Object cookie, Cursor cursor) { if (getActivity() == null || cursor == null) { return; } mCursor = cursor; getActivity().startManagingCursor(mCursor); // If there was a last-opened track, load it. Otherwise load the first track. cursor.moveToFirst(); String lastTrackID = UIUtils.getLastUsedTrackID(getActivity()); if (lastTrackID != null) { while (!cursor.isAfterLast()) { if (lastTrackID.equals(cursor.getString(TracksAdapter.TracksQuery.TRACK_ID))) { break; } cursor.moveToNext(); } if (cursor.isAfterLast()) { loadTrack(null, mAutoloadTarget); } else { loadTrack(cursor, mAutoloadTarget); } } else { loadTrack(null, mAutoloadTarget); } mAdapter.setHasAllItem(true); mAdapter.setIsSessions(TracksFragment.NEXT_TYPE_SESSIONS.equals(mNextType)); mAdapter.changeCursor(mCursor); } /** {@inheritDoc} */ public void onItemClick(AdapterView<?> parent, View view, int position, long id) { final Cursor cursor = (Cursor) mAdapter.getItem(position); loadTrack(cursor, true); if (cursor != null) { UIUtils.setLastUsedTrackID(getActivity(), cursor.getString( TracksAdapter.TracksQuery.TRACK_ID)); } else { UIUtils.setLastUsedTrackID(getActivity(), ScheduleContract.Tracks.ALL_TRACK_ID); } if (mListPopupWindow != null) { mListPopupWindow.dismiss(); } } public void loadTrack(Cursor cursor, boolean loadTargetFragment) { final String trackId; final int trackColor; final Resources res = getResources(); if (cursor != null) { trackColor = cursor.getInt(TracksAdapter.TracksQuery.TRACK_COLOR); trackId = cursor.getString(TracksAdapter.TracksQuery.TRACK_ID); mTitle.setText(cursor.getString(TracksAdapter.TracksQuery.TRACK_NAME)); mAbstract.setText(cursor.getString(TracksAdapter.TracksQuery.TRACK_ABSTRACT)); } else { trackColor = res.getColor(R.color.all_track_color); trackId = ScheduleContract.Tracks.ALL_TRACK_ID; mTitle.setText(TracksFragment.NEXT_TYPE_SESSIONS.equals(mNextType) ? R.string.all_sessions_title : R.string.all_sandbox_title); mAbstract.setText(TracksFragment.NEXT_TYPE_SESSIONS.equals(mNextType) ? R.string.all_sessions_subtitle : R.string.all_sandbox_subtitle); } boolean isDark = UIUtils.isColorDark(trackColor); mRootView.setBackgroundColor(trackColor); if (isDark) { mTitle.setTextColor(res.getColor(R.color.body_text_1_inverse)); mAbstract.setTextColor(res.getColor(R.color.body_text_2_inverse)); mRootView.findViewById(R.id.track_dropdown_arrow).setBackgroundResource( R.drawable.track_dropdown_arrow_light); } else { mTitle.setTextColor(res.getColor(R.color.body_text_1)); mAbstract.setTextColor(res.getColor(R.color.body_text_2)); mRootView.findViewById(R.id.track_dropdown_arrow).setBackgroundResource( R.drawable.track_dropdown_arrow_dark); } if (loadTargetFragment) { final Intent intent = new Intent(Intent.ACTION_VIEW); final Uri trackUri = ScheduleContract.Tracks.buildTrackUri(trackId); intent.putExtra(SessionDetailFragment.EXTRA_TRACK, trackUri); if (NEXT_TYPE_SESSIONS.equals(mNextType)) { if (cursor == null) { intent.setData(ScheduleContract.Sessions.CONTENT_URI); } else { intent.setData(ScheduleContract.Tracks.buildSessionsUri(trackId)); } } else if (NEXT_TYPE_VENDORS.equals(mNextType)) { if (cursor == null) { intent.setData(ScheduleContract.Vendors.CONTENT_URI); } else { intent.setData(ScheduleContract.Tracks.buildVendorsUri(trackId)); } } ((BaseActivity) getActivity()).openActivityOrFragment(intent); } } public void onDismiss() { mListPopupWindow = null; } }
Java
/* * Copyright 2011 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.apps.iosched.ui.tablet; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.BaseMultiPaneActivity; import com.google.android.apps.iosched.ui.SessionDetailFragment; import com.google.android.apps.iosched.ui.SessionsFragment; import com.google.android.apps.iosched.ui.TracksFragment; import com.google.android.apps.iosched.ui.phone.SessionDetailActivity; import com.google.android.apps.iosched.ui.phone.SessionsActivity; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.view.ViewGroup; /** * A multi-pane activity, consisting of a {@link TracksDropdownFragment}, a * {@link SessionsFragment}, and {@link SessionDetailFragment}. * * This activity requires API level 11 or greater because {@link TracksDropdownFragment} requires * API level 11. */ public class SessionsMultiPaneActivity extends BaseMultiPaneActivity { private TracksDropdownFragment mTracksDropdownFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sessions); Intent intent = new Intent(); intent.setData(ScheduleContract.Tracks.CONTENT_URI); intent.putExtra(TracksFragment.EXTRA_NEXT_TYPE, TracksFragment.NEXT_TYPE_SESSIONS); final FragmentManager fm = getSupportFragmentManager(); mTracksDropdownFragment = (TracksDropdownFragment) fm.findFragmentById( R.id.fragment_tracks_dropdown); mTracksDropdownFragment.reloadFromArguments(intentToFragmentArguments(intent)); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getActivityHelper().setupSubActivity(); ViewGroup detailContainer = (ViewGroup) findViewById(R.id.fragment_container_session_detail); if (detailContainer != null && detailContainer.getChildCount() > 0) { findViewById(R.id.fragment_container_session_detail).setBackgroundColor(0xffffffff); } } @Override public FragmentReplaceInfo onSubstituteFragmentForActivityLaunch(String activityClassName) { if (SessionsActivity.class.getName().equals(activityClassName)) { return new FragmentReplaceInfo( SessionsFragment.class, "sessions", R.id.fragment_container_sessions); } else if (SessionDetailActivity.class.getName().equals(activityClassName)) { findViewById(R.id.fragment_container_session_detail).setBackgroundColor( 0xffffffff); return new FragmentReplaceInfo( SessionDetailFragment.class, "session_detail", R.id.fragment_container_session_detail); } return null; } }
Java
/* * Copyright 2011 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.apps.iosched.ui.tablet; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.ui.BaseMultiPaneActivity; import com.google.android.apps.iosched.ui.MapFragment; import com.google.android.apps.iosched.ui.SessionDetailFragment; import com.google.android.apps.iosched.ui.SessionsFragment; import com.google.android.apps.iosched.ui.VendorDetailFragment; import com.google.android.apps.iosched.ui.VendorsFragment; import com.google.android.apps.iosched.ui.phone.SessionDetailActivity; import com.google.android.apps.iosched.ui.phone.SessionsActivity; import com.google.android.apps.iosched.ui.phone.VendorDetailActivity; import com.google.android.apps.iosched.ui.phone.VendorsActivity; import android.app.FragmentBreadCrumbs; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.view.View; /** * A multi-pane activity, where the primary navigation pane is a {@link MapFragment}, that shows * {@link SessionsFragment}, {@link SessionDetailFragment}, {@link VendorsFragment}, and * {@link VendorDetailFragment} as popups. * * This activity requires API level 11 or greater because of its use of {@link FragmentBreadCrumbs}. */ public class MapMultiPaneActivity extends BaseMultiPaneActivity implements View.OnClickListener, FragmentManager.OnBackStackChangedListener { private static final int POPUP_TYPE_SESSIONS = 1; private static final int POPUP_TYPE_VENDORS = 2; private int mPopupType = -1; private boolean mPauseBackStackWatcher = false; private FragmentManager mFragmentManager; private FragmentBreadCrumbs mFragmentBreadCrumbs; private MapFragment mMapFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_map); mFragmentManager = getSupportFragmentManager(); mFragmentManager.addOnBackStackChangedListener(this); mFragmentBreadCrumbs = (FragmentBreadCrumbs) findViewById(R.id.breadcrumbs); mFragmentBreadCrumbs.setActivity(this); mMapFragment = (MapFragment) mFragmentManager.findFragmentByTag("map"); if (mMapFragment == null) { mMapFragment = new MapFragment(); mMapFragment.setArguments(intentToFragmentArguments(getIntent())); mFragmentManager.beginTransaction() .add(R.id.fragment_container_map, mMapFragment, "map") .commit(); } findViewById(R.id.close_button).setOnClickListener(new View.OnClickListener() { public void onClick(View view) { clearBackStack(getSupportFragmentManager()); } }); updateBreadCrumb(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getActivityHelper().setupSubActivity(); } @Override public FragmentReplaceInfo onSubstituteFragmentForActivityLaunch(String activityClassName) { if (SessionsActivity.class.getName().equals(activityClassName)) { clearBackStack(getSupportFragmentManager()); mPopupType = POPUP_TYPE_SESSIONS; showHideDetailAndPan(true); return new FragmentReplaceInfo( SessionsFragment.class, "sessions", R.id.fragment_container_map_detail); } else if (SessionDetailActivity.class.getName().equals(activityClassName)) { mPopupType = POPUP_TYPE_SESSIONS; showHideDetailAndPan(true); return new FragmentReplaceInfo( SessionDetailFragment.class, "session_detail", R.id.fragment_container_map_detail); } else if (VendorsActivity.class.getName().equals(activityClassName)) { clearBackStack(getSupportFragmentManager()); mPopupType = POPUP_TYPE_VENDORS; showHideDetailAndPan(true); return new FragmentReplaceInfo( VendorsFragment.class, "vendors", R.id.fragment_container_map_detail); } else if (VendorDetailActivity.class.getName().equals(activityClassName)) { mPopupType = POPUP_TYPE_VENDORS; showHideDetailAndPan(true); return new FragmentReplaceInfo( VendorDetailFragment.class, "vendor_detail", R.id.fragment_container_map_detail); } return null; } @Override protected void onBeforeCommitReplaceFragment(FragmentManager fm, FragmentTransaction ft, Fragment fragment) { super.onBeforeCommitReplaceFragment(fm, ft, fragment); if (fragment instanceof SessionsFragment || fragment instanceof VendorsFragment) { mPauseBackStackWatcher = true; clearBackStack(fm); mPauseBackStackWatcher = false; } ft.addToBackStack(null); updateBreadCrumb(); } /** * Handler for the breadcrumb parent. */ public void onClick(View view) { mFragmentManager.popBackStack(); } private void clearBackStack(FragmentManager fm) { while (fm.getBackStackEntryCount() > 0) { fm.popBackStackImmediate(); } } public void onBackStackChanged() { if (mPauseBackStackWatcher) { return; } if (mFragmentManager.getBackStackEntryCount() == 0) { showHideDetailAndPan(false); } updateBreadCrumb(); } private void showHideDetailAndPan(boolean show) { View detailPopup = findViewById(R.id.map_detail_popup); if (show != (detailPopup.getVisibility() == View.VISIBLE)) { detailPopup.setVisibility(show ? View.VISIBLE : View.GONE); mMapFragment.panLeft(show ? 0.25f : -0.25f); } } public void updateBreadCrumb() { final String title = (mPopupType == POPUP_TYPE_SESSIONS) ? getString(R.string.title_sessions) : getString(R.string.title_vendors); final String detailTitle = (mPopupType == POPUP_TYPE_SESSIONS) ? getString(R.string.title_session_detail) : getString(R.string.title_vendor_detail); if (mFragmentManager.getBackStackEntryCount() >= 2) { mFragmentBreadCrumbs.setParentTitle(title, title, this); mFragmentBreadCrumbs.setTitle(detailTitle, detailTitle); } else { mFragmentBreadCrumbs.setParentTitle(null, null, null); mFragmentBreadCrumbs.setTitle(title, title); } } }
Java
/* * Copyright 2011 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.apps.iosched.ui.tablet; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract.Sessions; import com.google.android.apps.iosched.ui.BaseMultiPaneActivity; import com.google.android.apps.iosched.ui.SessionDetailFragment; import com.google.android.apps.iosched.ui.SessionsFragment; import com.google.android.apps.iosched.ui.phone.SessionDetailActivity; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.view.View; import android.view.ViewGroup; /** * An activity that shows currently playing sessions in a two-pane view. */ public class NowPlayingMultiPaneActivity extends BaseMultiPaneActivity { private SessionsFragment mSessionsFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = new Intent(); intent.setData(Sessions.buildSessionsAtDirUri(System.currentTimeMillis())); setContentView(R.layout.activity_now_playing); final FragmentManager fm = getSupportFragmentManager(); mSessionsFragment = (SessionsFragment) fm.findFragmentByTag("sessions"); if (mSessionsFragment == null) { mSessionsFragment = new SessionsFragment(); mSessionsFragment.setArguments(intentToFragmentArguments(intent)); fm.beginTransaction() .add(R.id.fragment_container_sessions, mSessionsFragment, "sessions") .commit(); } } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getActivityHelper().setupSubActivity(); ViewGroup detailContainer = (ViewGroup) findViewById( R.id.fragment_container_now_playing_detail); if (detailContainer != null && detailContainer.getChildCount() > 1) { findViewById(android.R.id.empty).setVisibility(View.GONE); } } @Override public FragmentReplaceInfo onSubstituteFragmentForActivityLaunch( String activityClassName) { findViewById(android.R.id.empty).setVisibility(View.GONE); if (SessionDetailActivity.class.getName().equals(activityClassName)) { clearSelectedItems(); return new FragmentReplaceInfo( SessionDetailFragment.class, "session_detail", R.id.fragment_container_now_playing_detail); } return null; } private void clearSelectedItems() { if (mSessionsFragment != null) { mSessionsFragment.clearCheckedPosition(); } } }
Java
/* * Copyright 2011 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.apps.iosched.ui; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.ActivityHelper; import com.google.android.apps.iosched.util.AnalyticsUtils; import com.google.android.apps.iosched.util.BitmapUtils; import com.google.android.apps.iosched.util.FractionalTouchDelegate; import com.google.android.apps.iosched.util.NotifyingAsyncQueryHandler; import com.google.android.apps.iosched.util.ParserUtils; import com.google.android.apps.iosched.util.UIUtils; import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.RectF; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.CompoundButton; import android.widget.ImageView; import android.widget.TextView; /** * A fragment that shows detail information for a sandbox company, including company name, * description, product description, logo, etc. */ public class VendorDetailFragment extends Fragment implements NotifyingAsyncQueryHandler.AsyncQueryListener, CompoundButton.OnCheckedChangeListener { private static final String TAG = "VendorDetailFragment"; private Uri mVendorUri; private String mTrackId; private ViewGroup mRootView; private TextView mName; private CompoundButton mStarred; private ImageView mLogo; private TextView mUrl; private TextView mDesc; private TextView mProductDesc; private String mNameString; private NotifyingAsyncQueryHandler mHandler; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Intent intent = BaseActivity.fragmentArgumentsToIntent(getArguments()); mVendorUri = intent.getData(); if (mVendorUri== null) { return; } setHasOptionsMenu(true); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (mVendorUri == null) { return; } // Start background query to load vendor details mHandler = new NotifyingAsyncQueryHandler(getActivity().getContentResolver(), this); mHandler.startQuery(mVendorUri, VendorsQuery.PROJECTION); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = (ViewGroup) inflater.inflate(R.layout.fragment_vendor_detail, null); mName = (TextView) mRootView.findViewById(R.id.vendor_name); mStarred = (CompoundButton) mRootView.findViewById(R.id.star_button); mStarred.setFocusable(true); mStarred.setClickable(true); // Larger target triggers star toggle final View starParent = mRootView.findViewById(R.id.header_vendor); FractionalTouchDelegate.setupDelegate(starParent, mStarred, new RectF(0.6f, 0f, 1f, 0.8f)); mLogo = (ImageView) mRootView.findViewById(R.id.vendor_logo); mUrl = (TextView) mRootView.findViewById(R.id.vendor_url); mDesc = (TextView) mRootView.findViewById(R.id.vendor_desc); mProductDesc = (TextView) mRootView.findViewById(R.id.vendor_product_desc); return mRootView; } /** * Build a {@link android.view.View} to be used as a tab indicator, setting the requested string resource as * its label. * * @return View */ private View buildIndicator(int textRes) { final TextView indicator = (TextView) getActivity().getLayoutInflater() .inflate(R.layout.tab_indicator, (ViewGroup) mRootView.findViewById(android.R.id.tabs), false); indicator.setText(textRes); return indicator; } /** * {@inheritDoc} */ public void onQueryComplete(int token, Object cookie, Cursor cursor) { if (getActivity() == null) { return; } try { if (!cursor.moveToFirst()) { return; } mNameString = cursor.getString(VendorsQuery.NAME); mName.setText(mNameString); // Unregister around setting checked state to avoid triggering // listener since change isn't user generated. mStarred.setOnCheckedChangeListener(null); mStarred.setChecked(cursor.getInt(VendorsQuery.STARRED) != 0); mStarred.setOnCheckedChangeListener(this); // Start background fetch to load vendor logo final String logoUrl = cursor.getString(VendorsQuery.LOGO_URL); if (!TextUtils.isEmpty(logoUrl)) { BitmapUtils.fetchImage(getActivity(), logoUrl, null, null, new BitmapUtils.OnFetchCompleteListener() { public void onFetchComplete(Object cookie, Bitmap result) { if (result == null) { mLogo.setVisibility(View.GONE); } else { mLogo.setVisibility(View.VISIBLE); mLogo.setImageBitmap(result); } } }); } mUrl.setText(cursor.getString(VendorsQuery.URL)); mDesc.setText(cursor.getString(VendorsQuery.DESC)); mProductDesc.setText(cursor.getString(VendorsQuery.PRODUCT_DESC)); mTrackId = cursor.getString(VendorsQuery.TRACK_ID); // Assign track details when found // TODO: handle vendors not attached to track ActivityHelper activityHelper = ((BaseActivity) getActivity()).getActivityHelper(); activityHelper.setActionBarTitle(cursor.getString(VendorsQuery.TRACK_NAME)); activityHelper.setActionBarColor(cursor.getInt(VendorsQuery.TRACK_COLOR)); AnalyticsUtils.getInstance(getActivity()).trackPageView( "/Sandbox/Vendors/" + mNameString); } finally { cursor.close(); } } /** * Handle toggling of starred checkbox. */ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { final ContentValues values = new ContentValues(); values.put(ScheduleContract.Vendors.VENDOR_STARRED, isChecked ? 1 : 0); mHandler.startUpdate(mVendorUri, values); AnalyticsUtils.getInstance(getActivity()).trackEvent( "Sandbox", isChecked ? "Starred" : "Unstarred", mNameString, 0); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.map_menu_items, menu); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.menu_map) { // The room ID for the sandbox, in the map, is just the track ID final Intent intent = new Intent(getActivity().getApplicationContext(), UIUtils.getMapActivityClass(getActivity())); intent.putExtra(MapFragment.EXTRA_ROOM, ParserUtils.translateTrackIdAliasInverse(mTrackId)); startActivity(intent); return true; } return super.onOptionsItemSelected(item); } /** * {@link com.google.android.apps.iosched.provider.ScheduleContract.Vendors} query parameters. */ private interface VendorsQuery { String[] PROJECTION = { ScheduleContract.Vendors.VENDOR_NAME, ScheduleContract.Vendors.VENDOR_LOCATION, ScheduleContract.Vendors.VENDOR_DESC, ScheduleContract.Vendors.VENDOR_URL, ScheduleContract.Vendors.VENDOR_PRODUCT_DESC, ScheduleContract.Vendors.VENDOR_LOGO_URL, ScheduleContract.Vendors.VENDOR_STARRED, ScheduleContract.Vendors.TRACK_ID, ScheduleContract.Tracks.TRACK_NAME, ScheduleContract.Tracks.TRACK_COLOR, }; int NAME = 0; int LOCATION = 1; int DESC = 2; int URL = 3; int PRODUCT_DESC = 4; int LOGO_URL = 5; int STARRED = 6; int TRACK_ID = 7; int TRACK_NAME = 8; int TRACK_COLOR = 9; } }
Java
/* * Copyright 2011 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.apps.iosched.ui; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.ui.phone.ScheduleActivity; import com.google.android.apps.iosched.ui.tablet.ScheduleMultiPaneActivity; import com.google.android.apps.iosched.ui.tablet.SessionsMultiPaneActivity; import com.google.android.apps.iosched.ui.tablet.VendorsMultiPaneActivity; import com.google.android.apps.iosched.util.AnalyticsUtils; import com.google.android.apps.iosched.util.UIUtils; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; public class DashboardFragment extends Fragment { public void fireTrackerEvent(String label) { AnalyticsUtils.getInstance(getActivity()).trackEvent( "Home Screen Dashboard", "Click", label, 0); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View root = inflater.inflate(R.layout.fragment_dashboard, container); // Attach event handlers root.findViewById(R.id.home_btn_schedule).setOnClickListener(new View.OnClickListener() { public void onClick(View view) { fireTrackerEvent("Schedule"); if (UIUtils.isHoneycombTablet(getActivity())) { startActivity(new Intent(getActivity(), ScheduleMultiPaneActivity.class)); } else { startActivity(new Intent(getActivity(), ScheduleActivity.class)); } } }); root.findViewById(R.id.home_btn_sessions).setOnClickListener(new View.OnClickListener() { public void onClick(View view) { fireTrackerEvent("Sessions"); // Launch sessions list if (UIUtils.isHoneycombTablet(getActivity())) { startActivity(new Intent(getActivity(), SessionsMultiPaneActivity.class)); } else { final Intent intent = new Intent(Intent.ACTION_VIEW, ScheduleContract.Tracks.CONTENT_URI); intent.putExtra(Intent.EXTRA_TITLE, getString(R.string.title_session_tracks)); intent.putExtra(TracksFragment.EXTRA_NEXT_TYPE, TracksFragment.NEXT_TYPE_SESSIONS); startActivity(intent); } } }); root.findViewById(R.id.home_btn_starred).setOnClickListener(new View.OnClickListener() { public void onClick(View view) { fireTrackerEvent("Starred"); // Launch list of sessions and vendors the user has starred startActivity(new Intent(getActivity(), StarredActivity.class)); } }); root.findViewById(R.id.home_btn_vendors).setOnClickListener(new View.OnClickListener() { public void onClick(View view) { fireTrackerEvent("Sandbox"); // Launch vendors list if (UIUtils.isHoneycombTablet(getActivity())) { startActivity(new Intent(getActivity(), VendorsMultiPaneActivity.class)); } else { final Intent intent = new Intent(Intent.ACTION_VIEW, ScheduleContract.Tracks.CONTENT_URI); intent.putExtra(Intent.EXTRA_TITLE, getString(R.string.title_vendor_tracks)); intent.putExtra(TracksFragment.EXTRA_NEXT_TYPE, TracksFragment.NEXT_TYPE_VENDORS); startActivity(intent); } } }); root.findViewById(R.id.home_btn_map).setOnClickListener(new View.OnClickListener() { public void onClick(View view) { // Launch map of conference venue fireTrackerEvent("Map"); startActivity(new Intent(getActivity(), UIUtils.getMapActivityClass(getActivity()))); } }); root.findViewById(R.id.home_btn_announcements).setOnClickListener( new View.OnClickListener() { public void onClick(View view) { // splicing in tag streamer fireTrackerEvent("Bulletin"); Intent intent = new Intent(getActivity(), BulletinActivity.class); startActivity(intent); } }); return root; } }
Java
/* * Copyright 2011 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.apps.iosched.ui; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.ActivityHelper; import com.google.android.apps.iosched.util.AnalyticsUtils; import com.google.android.apps.iosched.util.NotifyingAsyncQueryHandler; import com.google.android.apps.iosched.util.UIUtils; import android.content.Context; import android.content.Intent; import android.database.ContentObserver; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.SystemClock; import android.provider.BaseColumns; import android.support.v4.app.ListFragment; import android.text.Spannable; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.ListView; import android.widget.TextView; import static com.google.android.apps.iosched.util.UIUtils.buildStyledSnippet; import static com.google.android.apps.iosched.util.UIUtils.formatSessionSubtitle; /** * A {@link ListFragment} showing a list of sessions. */ public class SessionsFragment extends ListFragment implements NotifyingAsyncQueryHandler.AsyncQueryListener { public static final String EXTRA_SCHEDULE_TIME_STRING = "com.google.android.iosched.extra.SCHEDULE_TIME_STRING"; private static final String STATE_CHECKED_POSITION = "checkedPosition"; private Uri mTrackUri; private Cursor mCursor; private CursorAdapter mAdapter; private int mCheckedPosition = -1; private boolean mHasSetEmptyText = false; private NotifyingAsyncQueryHandler mHandler; private Handler mMessageQueueHandler = new Handler(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mHandler = new NotifyingAsyncQueryHandler(getActivity().getContentResolver(), this); reloadFromArguments(getArguments()); } public void reloadFromArguments(Bundle arguments) { // Teardown from previous arguments if (mCursor != null) { getActivity().stopManagingCursor(mCursor); mCursor = null; } mCheckedPosition = -1; setListAdapter(null); mHandler.cancelOperation(SearchQuery._TOKEN); mHandler.cancelOperation(SessionsQuery._TOKEN); mHandler.cancelOperation(TracksQuery._TOKEN); // Load new arguments final Intent intent = BaseActivity.fragmentArgumentsToIntent(arguments); final Uri sessionsUri = intent.getData(); final int sessionQueryToken; if (sessionsUri == null) { return; } String[] projection; if (!ScheduleContract.Sessions.isSearchUri(sessionsUri)) { mAdapter = new SessionsAdapter(getActivity()); projection = SessionsQuery.PROJECTION; sessionQueryToken = SessionsQuery._TOKEN; } else { mAdapter = new SearchAdapter(getActivity()); projection = SearchQuery.PROJECTION; sessionQueryToken = SearchQuery._TOKEN; } setListAdapter(mAdapter); // Start background query to load sessions mHandler.startQuery(sessionQueryToken, null, sessionsUri, projection, null, null, ScheduleContract.Sessions.DEFAULT_SORT); // If caller launched us with specific track hint, pass it along when // launching session details. Also start a query to load the track info. mTrackUri = intent.getParcelableExtra(SessionDetailFragment.EXTRA_TRACK); if (mTrackUri != null) { mHandler.startQuery(TracksQuery._TOKEN, mTrackUri, TracksQuery.PROJECTION); } } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE); if (savedInstanceState != null) { mCheckedPosition = savedInstanceState.getInt(STATE_CHECKED_POSITION, -1); } if (!mHasSetEmptyText) { // Could be a bug, but calling this twice makes it become visible when it shouldn't // be visible. setEmptyText(getString(R.string.empty_sessions)); mHasSetEmptyText = true; } } /** {@inheritDoc} */ public void onQueryComplete(int token, Object cookie, Cursor cursor) { if (getActivity() == null) { return; } if (token == SessionsQuery._TOKEN || token == SearchQuery._TOKEN) { onSessionOrSearchQueryComplete(cursor); } else if (token == TracksQuery._TOKEN) { onTrackQueryComplete(cursor); } else { Log.d("SessionsFragment/onQueryComplete", "Query complete, Not Actionable: " + token); cursor.close(); } } /** * Handle {@link SessionsQuery} {@link Cursor}. */ private void onSessionOrSearchQueryComplete(Cursor cursor) { if (mCursor != null) { // In case cancelOperation() doesn't work and we end up with consecutive calls to this // callback. getActivity().stopManagingCursor(mCursor); mCursor = null; } mCursor = cursor; getActivity().startManagingCursor(mCursor); mAdapter.changeCursor(mCursor); if (mCheckedPosition >= 0 && getView() != null) { getListView().setItemChecked(mCheckedPosition, true); } } /** * Handle {@link TracksQuery} {@link Cursor}. */ private void onTrackQueryComplete(Cursor cursor) { try { if (!cursor.moveToFirst()) { return; } // Use found track to build title-bar ActivityHelper activityHelper = ((BaseActivity) getActivity()).getActivityHelper(); String trackName = cursor.getString(TracksQuery.TRACK_NAME); activityHelper.setActionBarTitle(trackName); activityHelper.setActionBarColor(cursor.getInt(TracksQuery.TRACK_COLOR)); AnalyticsUtils.getInstance(getActivity()).trackPageView("/Tracks/" + trackName); } finally { cursor.close(); } } @Override public void onResume() { super.onResume(); mMessageQueueHandler.post(mRefreshSessionsRunnable); getActivity().getContentResolver().registerContentObserver( ScheduleContract.Sessions.CONTENT_URI, true, mSessionChangesObserver); if (mCursor != null) { mCursor.requery(); } } @Override public void onPause() { super.onPause(); mMessageQueueHandler.removeCallbacks(mRefreshSessionsRunnable); getActivity().getContentResolver().unregisterContentObserver(mSessionChangesObserver); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt(STATE_CHECKED_POSITION, mCheckedPosition); } /** {@inheritDoc} */ @Override public void onListItemClick(ListView l, View v, int position, long id) { // Launch viewer for specific session, passing along any track knowledge // that should influence the title-bar. final Cursor cursor = (Cursor)mAdapter.getItem(position); final String sessionId = cursor.getString(cursor.getColumnIndex( ScheduleContract.Sessions.SESSION_ID)); final Uri sessionUri = ScheduleContract.Sessions.buildSessionUri(sessionId); final Intent intent = new Intent(Intent.ACTION_VIEW, sessionUri); intent.putExtra(SessionDetailFragment.EXTRA_TRACK, mTrackUri); ((BaseActivity) getActivity()).openActivityOrFragment(intent); getListView().setItemChecked(position, true); mCheckedPosition = position; } public void clearCheckedPosition() { if (mCheckedPosition >= 0) { getListView().setItemChecked(mCheckedPosition, false); mCheckedPosition = -1; } } /** * {@link CursorAdapter} that renders a {@link SessionsQuery}. */ private class SessionsAdapter extends CursorAdapter { public SessionsAdapter(Context context) { super(context, null); } /** {@inheritDoc} */ @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return getActivity().getLayoutInflater().inflate(R.layout.list_item_session, parent, false); } /** {@inheritDoc} */ @Override public void bindView(View view, Context context, Cursor cursor) { final TextView titleView = (TextView) view.findViewById(R.id.session_title); final TextView subtitleView = (TextView) view.findViewById(R.id.session_subtitle); titleView.setText(cursor.getString(SessionsQuery.TITLE)); // Format time block this session occupies final long blockStart = cursor.getLong(SessionsQuery.BLOCK_START); final long blockEnd = cursor.getLong(SessionsQuery.BLOCK_END); final String roomName = cursor.getString(SessionsQuery.ROOM_NAME); final String subtitle = formatSessionSubtitle(blockStart, blockEnd, roomName, context); subtitleView.setText(subtitle); final boolean starred = cursor.getInt(SessionsQuery.STARRED) != 0; view.findViewById(R.id.star_button).setVisibility( starred ? View.VISIBLE : View.INVISIBLE); // Possibly indicate that the session has occurred in the past. UIUtils.setSessionTitleColor(blockStart, blockEnd, titleView, subtitleView); } } /** * {@link CursorAdapter} that renders a {@link SearchQuery}. */ private class SearchAdapter extends CursorAdapter { public SearchAdapter(Context context) { super(context, null); } /** {@inheritDoc} */ @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return getActivity().getLayoutInflater().inflate(R.layout.list_item_session, parent, false); } /** {@inheritDoc} */ @Override public void bindView(View view, Context context, Cursor cursor) { ((TextView) view.findViewById(R.id.session_title)).setText(cursor .getString(SearchQuery.TITLE)); final String snippet = cursor.getString(SearchQuery.SEARCH_SNIPPET); final Spannable styledSnippet = buildStyledSnippet(snippet); ((TextView) view.findViewById(R.id.session_subtitle)).setText(styledSnippet); final boolean starred = cursor.getInt(SearchQuery.STARRED) != 0; view.findViewById(R.id.star_button).setVisibility( starred ? View.VISIBLE : View.INVISIBLE); } } private ContentObserver mSessionChangesObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfChange) { if (mCursor != null) { mCursor.requery(); } } }; private Runnable mRefreshSessionsRunnable = new Runnable() { public void run() { if (mAdapter != null) { // This is used to refresh session title colors. mAdapter.notifyDataSetChanged(); } // Check again on the next quarter hour, with some padding to account for network // time differences. long nextQuarterHour = (SystemClock.uptimeMillis() / 900000 + 1) * 900000 + 5000; mMessageQueueHandler.postAtTime(mRefreshSessionsRunnable, nextQuarterHour); } }; /** * {@link com.google.android.apps.iosched.provider.ScheduleContract.Sessions} query parameters. */ private interface SessionsQuery { int _TOKEN = 0x1; String[] PROJECTION = { BaseColumns._ID, ScheduleContract.Sessions.SESSION_ID, ScheduleContract.Sessions.SESSION_TITLE, ScheduleContract.Sessions.SESSION_STARRED, ScheduleContract.Blocks.BLOCK_START, ScheduleContract.Blocks.BLOCK_END, ScheduleContract.Rooms.ROOM_NAME, }; int _ID = 0; int SESSION_ID = 1; int TITLE = 2; int STARRED = 3; int BLOCK_START = 4; int BLOCK_END = 5; int ROOM_NAME = 6; } /** * {@link com.google.android.apps.iosched.provider.ScheduleContract.Tracks} query parameters. */ private interface TracksQuery { int _TOKEN = 0x2; String[] PROJECTION = { ScheduleContract.Tracks.TRACK_NAME, ScheduleContract.Tracks.TRACK_COLOR, }; int TRACK_NAME = 0; int TRACK_COLOR = 1; } /** {@link com.google.android.apps.iosched.provider.ScheduleContract.Sessions} search query * parameters. */ private interface SearchQuery { int _TOKEN = 0x3; String[] PROJECTION = { BaseColumns._ID, ScheduleContract.Sessions.SESSION_ID, ScheduleContract.Sessions.SESSION_TITLE, ScheduleContract.Sessions.SEARCH_SNIPPET, ScheduleContract.Sessions.SESSION_STARRED, }; int _ID = 0; int SESSION_ID = 1; int TITLE = 2; int SEARCH_SNIPPET = 3; int STARRED = 4; } }
Java
/* * Copyright 2011 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.apps.iosched.ui; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.ActivityHelper; import com.google.android.apps.iosched.util.AnalyticsUtils; import com.google.android.apps.iosched.util.BitmapUtils; import com.google.android.apps.iosched.util.CatchNotesHelper; import com.google.android.apps.iosched.util.FractionalTouchDelegate; import com.google.android.apps.iosched.util.NotifyingAsyncQueryHandler; import com.google.android.apps.iosched.util.UIUtils; import android.content.BroadcastReceiver; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.RectF; import android.graphics.Typeface; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.TextUtils; import android.text.method.LinkMovementMethod; import android.text.style.StyleSpan; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.CompoundButton; import android.widget.ImageView; import android.widget.TabHost; import android.widget.TextView; /** * A fragment that shows detail information for a session, including session title, abstract, * time information, speaker photos and bios, etc. */ public class SessionDetailFragment extends Fragment implements NotifyingAsyncQueryHandler.AsyncQueryListener, CompoundButton.OnCheckedChangeListener { private static final String TAG = "SessionDetailFragment"; /** * Since sessions can belong tracks, the parent activity can send this extra specifying a * track URI that should be used for coloring the title-bar. */ public static final String EXTRA_TRACK = "com.google.android.iosched.extra.TRACK"; private static final String TAG_SUMMARY = "summary"; private static final String TAG_NOTES = "notes"; private static final String TAG_LINKS = "links"; private static StyleSpan sBoldSpan = new StyleSpan(Typeface.BOLD); private String mSessionId; private Uri mSessionUri; private Uri mTrackUri; private String mTitleString; private String mHashtag; private String mUrl; private TextView mTagDisplay; private String mRoomId; private ViewGroup mRootView; private TabHost mTabHost; private TextView mTitle; private TextView mSubtitle; private CompoundButton mStarred; private TextView mAbstract; private TextView mRequirements; private NotifyingAsyncQueryHandler mHandler; private boolean mSessionCursor = false; private boolean mSpeakersCursor = false; private boolean mHasSummaryContent = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Intent intent = BaseActivity.fragmentArgumentsToIntent(getArguments()); mSessionUri = intent.getData(); mTrackUri = resolveTrackUri(intent); if (mSessionUri == null) { return; } mSessionId = ScheduleContract.Sessions.getSessionId(mSessionUri); setHasOptionsMenu(true); } @Override public void onResume() { super.onResume(); updateNotesTab(); // Start listening for time updates to adjust "now" bar. TIME_TICK is // triggered once per minute, which is how we move the bar over time. final IntentFilter filter = new IntentFilter(); filter.addAction(Intent.ACTION_PACKAGE_ADDED); filter.addAction(Intent.ACTION_PACKAGE_REMOVED); filter.addAction(Intent.ACTION_PACKAGE_REPLACED); filter.addDataScheme("package"); getActivity().registerReceiver(mPackageChangesReceiver, filter); } @Override public void onPause() { super.onPause(); getActivity().unregisterReceiver(mPackageChangesReceiver); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (mSessionUri == null) { return; } // Start background queries to load session and track details final Uri speakersUri = ScheduleContract.Sessions.buildSpeakersDirUri(mSessionId); mHandler = new NotifyingAsyncQueryHandler(getActivity().getContentResolver(), this); mHandler.startQuery(SessionsQuery._TOKEN, mSessionUri, SessionsQuery.PROJECTION); mHandler.startQuery(TracksQuery._TOKEN, mTrackUri, TracksQuery.PROJECTION); mHandler.startQuery(SpeakersQuery._TOKEN, speakersUri, SpeakersQuery.PROJECTION); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mRootView = (ViewGroup) inflater.inflate(R.layout.fragment_session_detail, null); mTabHost = (TabHost) mRootView.findViewById(android.R.id.tabhost); mTabHost.setup(); mTitle = (TextView) mRootView.findViewById(R.id.session_title); mSubtitle = (TextView) mRootView.findViewById(R.id.session_subtitle); mStarred = (CompoundButton) mRootView.findViewById(R.id.star_button); mStarred.setFocusable(true); mStarred.setClickable(true); // Larger target triggers star toggle final View starParent = mRootView.findViewById(R.id.header_session); FractionalTouchDelegate.setupDelegate(starParent, mStarred, new RectF(0.6f, 0f, 1f, 0.8f)); mAbstract = (TextView) mRootView.findViewById(R.id.session_abstract); mRequirements = (TextView) mRootView.findViewById(R.id.session_requirements); setupSummaryTab(); setupNotesTab(); setupLinksTab(); return mRootView; } /** * Build and add "summary" tab. */ private void setupSummaryTab() { // Summary content comes from existing layout mTabHost.addTab(mTabHost.newTabSpec(TAG_SUMMARY) .setIndicator(buildIndicator(R.string.session_summary)) .setContent(R.id.tab_session_summary)); } /** * Build a {@link View} to be used as a tab indicator, setting the requested string resource as * its label. * * @param textRes * @return View */ private View buildIndicator(int textRes) { final TextView indicator = (TextView) getActivity().getLayoutInflater() .inflate(R.layout.tab_indicator, (ViewGroup) mRootView.findViewById(android.R.id.tabs), false); indicator.setText(textRes); return indicator; } /** * Derive {@link com.google.android.apps.iosched.provider.ScheduleContract.Tracks#CONTENT_ITEM_TYPE} * {@link Uri} based on incoming {@link Intent}, using * {@link #EXTRA_TRACK} when set. * @param intent * @return Uri */ private Uri resolveTrackUri(Intent intent) { final Uri trackUri = intent.getParcelableExtra(EXTRA_TRACK); if (trackUri != null) { return trackUri; } else { return ScheduleContract.Sessions.buildTracksDirUri(mSessionId); } } /** * {@inheritDoc} */ public void onQueryComplete(int token, Object cookie, Cursor cursor) { if (getActivity() == null) { return; } if (token == SessionsQuery._TOKEN) { onSessionQueryComplete(cursor); } else if (token == TracksQuery._TOKEN) { onTrackQueryComplete(cursor); } else if (token == SpeakersQuery._TOKEN) { onSpeakersQueryComplete(cursor); } else { cursor.close(); } } /** * Handle {@link SessionsQuery} {@link Cursor}. */ private void onSessionQueryComplete(Cursor cursor) { try { mSessionCursor = true; if (!cursor.moveToFirst()) { return; } // Format time block this session occupies final long blockStart = cursor.getLong(SessionsQuery.BLOCK_START); final long blockEnd = cursor.getLong(SessionsQuery.BLOCK_END); final String roomName = cursor.getString(SessionsQuery.ROOM_NAME); final String subtitle = UIUtils.formatSessionSubtitle(blockStart, blockEnd, roomName, getActivity()); mTitleString = cursor.getString(SessionsQuery.TITLE); mTitle.setText(mTitleString); mSubtitle.setText(subtitle); mUrl = cursor.getString(SessionsQuery.URL); if (TextUtils.isEmpty(mUrl)) { mUrl = ""; } mHashtag = cursor.getString(SessionsQuery.HASHTAG); mTagDisplay = (TextView) mRootView.findViewById(R.id.session_tags_button); if (!TextUtils.isEmpty(mHashtag)) { // Create the button text SpannableStringBuilder sb = new SpannableStringBuilder(); sb.append(getString(R.string.tag_stream) + " "); int boldStart = sb.length(); sb.append(getHashtagsString()); sb.setSpan(sBoldSpan, boldStart, sb.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); mTagDisplay.setText(sb); mTagDisplay.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent intent = new Intent(getActivity(), TagStreamActivity.class); intent.putExtra(TagStreamFragment.EXTRA_QUERY, getHashtagsString()); startActivity(intent); } }); } else { mTagDisplay.setVisibility(View.GONE); } mRoomId = cursor.getString(SessionsQuery.ROOM_ID); // Unregister around setting checked state to avoid triggering // listener since change isn't user generated. mStarred.setOnCheckedChangeListener(null); mStarred.setChecked(cursor.getInt(SessionsQuery.STARRED) != 0); mStarred.setOnCheckedChangeListener(this); final String sessionAbstract = cursor.getString(SessionsQuery.ABSTRACT); if (!TextUtils.isEmpty(sessionAbstract)) { UIUtils.setTextMaybeHtml(mAbstract, sessionAbstract); mAbstract.setVisibility(View.VISIBLE); mHasSummaryContent = true; } else { mAbstract.setVisibility(View.GONE); } final View requirementsBlock = mRootView.findViewById(R.id.session_requirements_block); final String sessionRequirements = cursor.getString(SessionsQuery.REQUIREMENTS); if (!TextUtils.isEmpty(sessionRequirements)) { UIUtils.setTextMaybeHtml(mRequirements, sessionRequirements); requirementsBlock.setVisibility(View.VISIBLE); mHasSummaryContent = true; } else { requirementsBlock.setVisibility(View.GONE); } // Show empty message when all data is loaded, and nothing to show if (mSpeakersCursor && !mHasSummaryContent) { mRootView.findViewById(android.R.id.empty).setVisibility(View.VISIBLE); } AnalyticsUtils.getInstance(getActivity()).trackPageView("/Sessions/" + mTitleString); updateLinksTab(cursor); updateNotesTab(); } finally { cursor.close(); } } /** * Handle {@link TracksQuery} {@link Cursor}. */ private void onTrackQueryComplete(Cursor cursor) { try { if (!cursor.moveToFirst()) { return; } // Use found track to build title-bar ActivityHelper activityHelper = ((BaseActivity) getActivity()).getActivityHelper(); activityHelper.setActionBarTitle(cursor.getString(TracksQuery.TRACK_NAME)); activityHelper.setActionBarColor(cursor.getInt(TracksQuery.TRACK_COLOR)); } finally { cursor.close(); } } private void onSpeakersQueryComplete(Cursor cursor) { try { mSpeakersCursor = true; // TODO: remove any existing speakers from layout, since this cursor // might be from a data change notification. final ViewGroup speakersGroup = (ViewGroup) mRootView.findViewById(R.id.session_speakers_block); final LayoutInflater inflater = getActivity().getLayoutInflater(); boolean hasSpeakers = false; while (cursor.moveToNext()) { final String speakerName = cursor.getString(SpeakersQuery.SPEAKER_NAME); if (TextUtils.isEmpty(speakerName)) { continue; } final String speakerImageUrl = cursor.getString(SpeakersQuery.SPEAKER_IMAGE_URL); final String speakerCompany = cursor.getString(SpeakersQuery.SPEAKER_COMPANY); final String speakerUrl = cursor.getString(SpeakersQuery.SPEAKER_URL); final String speakerAbstract = cursor.getString(SpeakersQuery.SPEAKER_ABSTRACT); String speakerHeader = speakerName; if (!TextUtils.isEmpty(speakerCompany)) { speakerHeader += ", " + speakerCompany; } final View speakerView = inflater .inflate(R.layout.speaker_detail, speakersGroup, false); final TextView speakerHeaderView = (TextView) speakerView .findViewById(R.id.speaker_header); final ImageView speakerImgView = (ImageView) speakerView .findViewById(R.id.speaker_image); final TextView speakerUrlView = (TextView) speakerView .findViewById(R.id.speaker_url); final TextView speakerAbstractView = (TextView) speakerView .findViewById(R.id.speaker_abstract); if (!TextUtils.isEmpty(speakerImageUrl)) { BitmapUtils.fetchImage(getActivity(), speakerImageUrl, null, null, new BitmapUtils.OnFetchCompleteListener() { public void onFetchComplete(Object cookie, Bitmap result) { if (result != null) { speakerImgView.setImageBitmap(result); } } }); } speakerHeaderView.setText(speakerHeader); UIUtils.setTextMaybeHtml(speakerAbstractView, speakerAbstract); if (!TextUtils.isEmpty(speakerUrl)) { UIUtils.setTextMaybeHtml(speakerUrlView, speakerUrl); speakerUrlView.setVisibility(View.VISIBLE); } else { speakerUrlView.setVisibility(View.GONE); } speakersGroup.addView(speakerView); hasSpeakers = true; mHasSummaryContent = true; } speakersGroup.setVisibility(hasSpeakers ? View.VISIBLE : View.GONE); // Show empty message when all data is loaded, and nothing to show if (mSessionCursor && !mHasSummaryContent) { mRootView.findViewById(android.R.id.empty).setVisibility(View.VISIBLE); } } finally { if (null != cursor) { cursor.close(); } } } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.session_detail_menu_items, menu); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { final String shareString; final Intent intent; switch (item.getItemId()) { case R.id.menu_map: intent = new Intent(getActivity().getApplicationContext(), UIUtils.getMapActivityClass(getActivity())); intent.putExtra(MapFragment.EXTRA_ROOM, mRoomId); startActivity(intent); return true; case R.id.menu_share: // TODO: consider bringing in shortlink to session shareString = getString(R.string.share_template, mTitleString, getHashtagsString(), mUrl); intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_TEXT, shareString); startActivity(Intent.createChooser(intent, getText(R.string.title_share))); return true; } return super.onOptionsItemSelected(item); } /** * Handle toggling of starred checkbox. */ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { final ContentValues values = new ContentValues(); values.put(ScheduleContract.Sessions.SESSION_STARRED, isChecked ? 1 : 0); mHandler.startUpdate(mSessionUri, values); // Because change listener is set to null during initialization, these won't fire on // pageview. AnalyticsUtils.getInstance(getActivity()).trackEvent( "Sandbox", isChecked ? "Starred" : "Unstarred", mTitleString, 0); } /** * Build and add "notes" tab. */ private void setupNotesTab() { // Make powered-by clickable ((TextView) mRootView.findViewById(R.id.notes_powered_by)).setMovementMethod( LinkMovementMethod.getInstance()); // Setup tab mTabHost.addTab(mTabHost.newTabSpec(TAG_NOTES) .setIndicator(buildIndicator(R.string.session_notes)) .setContent(R.id.tab_session_notes)); } /* * Event structure: * Category -> "Session Details" * Action -> "Create Note", "View Note", etc * Label -> Session's Title * Value -> 0. */ public void fireNotesEvent(int actionId) { AnalyticsUtils.getInstance(getActivity()).trackEvent( "Session Details", getActivity().getString(actionId), mTitleString, 0); } /* * Event structure: * Category -> "Session Details" * Action -> Link Text * Label -> Session's Title * Value -> 0. */ public void fireLinkEvent(int actionId) { AnalyticsUtils.getInstance(getActivity()).trackEvent( "Link Details", getActivity().getString(actionId), mTitleString, 0); } private void updateNotesTab() { final CatchNotesHelper helper = new CatchNotesHelper(getActivity()); final boolean notesInstalled = helper.isNotesInstalledAndMinimumVersion(); final Intent marketIntent = helper.notesMarketIntent(); final Intent newIntent = helper.createNoteIntent( getString(R.string.note_template, mTitleString, getHashtagsString())); final Intent viewIntent = helper.viewNotesIntent(getHashtagsString()); // Set icons and click listeners ((ImageView) mRootView.findViewById(R.id.notes_catch_market_icon)).setImageDrawable( UIUtils.getIconForIntent(getActivity(), marketIntent)); ((ImageView) mRootView.findViewById(R.id.notes_catch_new_icon)).setImageDrawable( UIUtils.getIconForIntent(getActivity(), newIntent)); ((ImageView) mRootView.findViewById(R.id.notes_catch_view_icon)).setImageDrawable( UIUtils.getIconForIntent(getActivity(), viewIntent)); // Set click listeners mRootView.findViewById(R.id.notes_catch_market_link).setOnClickListener( new View.OnClickListener() { public void onClick(View view) { startActivity(marketIntent); fireNotesEvent(R.string.notes_catch_market_title); } }); mRootView.findViewById(R.id.notes_catch_new_link).setOnClickListener( new View.OnClickListener() { public void onClick(View view) { startActivity(newIntent); fireNotesEvent(R.string.notes_catch_new_title); } }); mRootView.findViewById(R.id.notes_catch_view_link).setOnClickListener( new View.OnClickListener() { public void onClick(View view) { startActivity(viewIntent); fireNotesEvent(R.string.notes_catch_view_title); } }); // Show/hide elements mRootView.findViewById(R.id.notes_catch_market_link).setVisibility( notesInstalled ? View.GONE : View.VISIBLE); mRootView.findViewById(R.id.notes_catch_market_separator).setVisibility( notesInstalled ? View.GONE : View.VISIBLE); mRootView.findViewById(R.id.notes_catch_new_link).setVisibility( !notesInstalled ? View.GONE : View.VISIBLE); mRootView.findViewById(R.id.notes_catch_new_separator).setVisibility( !notesInstalled ? View.GONE : View.VISIBLE); mRootView.findViewById(R.id.notes_catch_view_link).setVisibility( !notesInstalled ? View.GONE : View.VISIBLE); mRootView.findViewById(R.id.notes_catch_view_separator).setVisibility( !notesInstalled ? View.GONE : View.VISIBLE); } /** * Build and add "summary" tab. */ private void setupLinksTab() { // Summary content comes from existing layout mTabHost.addTab(mTabHost.newTabSpec(TAG_LINKS) .setIndicator(buildIndicator(R.string.session_links)) .setContent(R.id.tab_session_links)); } private void updateLinksTab(Cursor cursor) { ViewGroup container = (ViewGroup) mRootView.findViewById(R.id.links_container); // Remove all views but the 'empty' view int childCount = container.getChildCount(); if (childCount > 1) { container.removeViews(1, childCount - 1); } LayoutInflater inflater = getLayoutInflater(null); boolean hasLinks = false; for (int i = 0; i < SessionsQuery.LINKS_INDICES.length; i++) { final String url = cursor.getString(SessionsQuery.LINKS_INDICES[i]); if (!TextUtils.isEmpty(url)) { hasLinks = true; ViewGroup linkContainer = (ViewGroup) inflater.inflate(R.layout.list_item_session_link, container, false); ((TextView) linkContainer.findViewById(R.id.link_text)).setText( SessionsQuery.LINKS_TITLES[i]); final int linkTitleIndex = i; linkContainer.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { fireLinkEvent(SessionsQuery.LINKS_TITLES[linkTitleIndex]); Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); startActivity(intent); } }); container.addView(linkContainer); // Create separator View separatorView = new ImageView(getActivity()); separatorView.setLayoutParams( new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); separatorView.setBackgroundResource(android.R.drawable.divider_horizontal_bright); container.addView(separatorView); } } container.findViewById(R.id.empty_links).setVisibility(hasLinks ? View.GONE : View.VISIBLE); } private String getHashtagsString() { if (!TextUtils.isEmpty(mHashtag)) { return TagStreamFragment.CONFERENCE_HASHTAG + " #" + mHashtag; } else { return TagStreamFragment.CONFERENCE_HASHTAG; } } private BroadcastReceiver mPackageChangesReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { updateNotesTab(); } }; /** * {@link com.google.android.apps.iosched.provider.ScheduleContract.Sessions} query parameters. */ private interface SessionsQuery { int _TOKEN = 0x1; String[] PROJECTION = { ScheduleContract.Blocks.BLOCK_START, ScheduleContract.Blocks.BLOCK_END, ScheduleContract.Sessions.SESSION_LEVEL, ScheduleContract.Sessions.SESSION_TITLE, ScheduleContract.Sessions.SESSION_ABSTRACT, ScheduleContract.Sessions.SESSION_REQUIREMENTS, ScheduleContract.Sessions.SESSION_STARRED, ScheduleContract.Sessions.SESSION_HASHTAG, ScheduleContract.Sessions.SESSION_SLUG, ScheduleContract.Sessions.SESSION_URL, ScheduleContract.Sessions.SESSION_MODERATOR_URL, ScheduleContract.Sessions.SESSION_YOUTUBE_URL, ScheduleContract.Sessions.SESSION_PDF_URL, ScheduleContract.Sessions.SESSION_FEEDBACK_URL, ScheduleContract.Sessions.SESSION_NOTES_URL, ScheduleContract.Sessions.ROOM_ID, ScheduleContract.Rooms.ROOM_NAME, }; int BLOCK_START = 0; int BLOCK_END = 1; int LEVEL = 2; int TITLE = 3; int ABSTRACT = 4; int REQUIREMENTS = 5; int STARRED = 6; int HASHTAG = 7; int SLUG = 8; int URL = 9; int MODERATOR_URL = 10; int YOUTUBE_URL = 11; int PDF_URL = 12; int FEEDBACK_URL = 13; int NOTES_URL = 14; int ROOM_ID = 15; int ROOM_NAME = 16; int[] LINKS_INDICES = { URL, MODERATOR_URL, YOUTUBE_URL, PDF_URL, FEEDBACK_URL, NOTES_URL, }; int[] LINKS_TITLES = { R.string.session_link_main, R.string.session_link_moderator, R.string.session_link_youtube, R.string.session_link_pdf, R.string.session_link_feedback, R.string.session_link_notes, }; } /** * {@link com.google.android.apps.iosched.provider.ScheduleContract.Tracks} query parameters. */ private interface TracksQuery { int _TOKEN = 0x2; String[] PROJECTION = { ScheduleContract.Tracks.TRACK_NAME, ScheduleContract.Tracks.TRACK_COLOR, }; int TRACK_NAME = 0; int TRACK_COLOR = 1; } private interface SpeakersQuery { int _TOKEN = 0x3; String[] PROJECTION = { ScheduleContract.Speakers.SPEAKER_NAME, ScheduleContract.Speakers.SPEAKER_IMAGE_URL, ScheduleContract.Speakers.SPEAKER_COMPANY, ScheduleContract.Speakers.SPEAKER_ABSTRACT, ScheduleContract.Speakers.SPEAKER_URL, }; int SPEAKER_NAME = 0; int SPEAKER_IMAGE_URL = 1; int SPEAKER_COMPANY = 2; int SPEAKER_ABSTRACT = 3; int SPEAKER_URL = 4; } }
Java
/* * Copyright 2011 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.apps.iosched.ui; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.util.AnalyticsUtils; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import android.webkit.WebViewClient; import java.util.regex.Pattern; /** * A fragment containing a {@link WebView} pointing to the I/O announcements URL. */ public class BulletinFragment extends Fragment { private static final Pattern sSiteUrlPattern = Pattern.compile("google\\.com\\/events\\/io"); private static final String BULLETIN_URL = "http://www.google.com/events/io/2011/mobile_announcements.html"; private WebView mWebView; private View mLoadingSpinner; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); AnalyticsUtils.getInstance(getActivity()).trackPageView("/Bulletin"); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_webview_with_spinner, null); // For some reason, if we omit this, NoSaveStateFrameLayout thinks we are // FILL_PARENT / WRAP_CONTENT, making the progress bar stick to the top of the activity. root.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT)); mLoadingSpinner = root.findViewById(R.id.loading_spinner); mWebView = (WebView) root.findViewById(R.id.webview); mWebView.setWebViewClient(mWebViewClient); mWebView.post(new Runnable() { public void run() { mWebView.getSettings().setJavaScriptEnabled(true); mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(false); mWebView.loadUrl(BULLETIN_URL); } }); return root; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.refresh_menu_items, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.menu_refresh) { mWebView.reload(); return true; } return super.onOptionsItemSelected(item); } private WebViewClient mWebViewClient = new WebViewClient() { @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); mLoadingSpinner.setVisibility(View.VISIBLE); mWebView.setVisibility(View.INVISIBLE); } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); mLoadingSpinner.setVisibility(View.GONE); mWebView.setVisibility(View.VISIBLE); } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (sSiteUrlPattern.matcher(url).find()) { return false; } Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(intent); return true; } }; }
Java
/* * Copyright 2011 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.apps.iosched.ui; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract; import com.google.android.apps.iosched.util.ActivityHelper; import com.google.android.apps.iosched.util.AnalyticsUtils; import com.google.android.apps.iosched.util.NotifyingAsyncQueryHandler; import android.content.Context; import android.content.Intent; import android.database.ContentObserver; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.provider.BaseColumns; import android.support.v4.app.ListFragment; import android.text.Spannable; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.ListView; import android.widget.TextView; import static com.google.android.apps.iosched.util.UIUtils.buildStyledSnippet; /** * A {@link ListFragment} showing a list of sandbox comapnies. */ public class VendorsFragment extends ListFragment implements NotifyingAsyncQueryHandler.AsyncQueryListener { private static final String STATE_CHECKED_POSITION = "checkedPosition"; private Uri mTrackUri; private Cursor mCursor; private CursorAdapter mAdapter; private int mCheckedPosition = -1; private boolean mHasSetEmptyText = false; private NotifyingAsyncQueryHandler mHandler; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mHandler = new NotifyingAsyncQueryHandler(getActivity().getContentResolver(), this); reloadFromArguments(getArguments()); } public void reloadFromArguments(Bundle arguments) { // Teardown from previous arguments if (mCursor != null) { getActivity().stopManagingCursor(mCursor); mCursor = null; } mCheckedPosition = -1; setListAdapter(null); mHandler.cancelOperation(SearchQuery._TOKEN); mHandler.cancelOperation(VendorsQuery._TOKEN); // Load new arguments final Intent intent = BaseActivity.fragmentArgumentsToIntent(arguments); final Uri vendorsUri = intent.getData(); final int vendorQueryToken; if (vendorsUri == null) { return; } String[] projection; if (!ScheduleContract.Vendors.isSearchUri(vendorsUri)) { mAdapter = new VendorsAdapter(getActivity()); projection = VendorsQuery.PROJECTION; vendorQueryToken = VendorsQuery._TOKEN; } else { Log.d("VendorsFragment/reloadFromArguments", "A search URL definitely gets passed in."); mAdapter = new SearchAdapter(getActivity()); projection = SearchQuery.PROJECTION; vendorQueryToken = SearchQuery._TOKEN; } setListAdapter(mAdapter); // Start background query to load vendors mHandler.startQuery(vendorQueryToken, null, vendorsUri, projection, null, null, ScheduleContract.Vendors.DEFAULT_SORT); // If caller launched us with specific track hint, pass it along when // launching vendor details. Also start a query to load the track info. mTrackUri = intent.getParcelableExtra(SessionDetailFragment.EXTRA_TRACK); if (mTrackUri != null) { mHandler.startQuery(TracksQuery._TOKEN, mTrackUri, TracksQuery.PROJECTION); } } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE); if (savedInstanceState != null) { mCheckedPosition = savedInstanceState.getInt(STATE_CHECKED_POSITION, -1); } if (!mHasSetEmptyText) { // Could be a bug, but calling this twice makes it become visible when it shouldn't // be visible. setEmptyText(getString(R.string.empty_vendors)); mHasSetEmptyText = true; } } /** {@inheritDoc} */ public void onQueryComplete(int token, Object cookie, Cursor cursor) { if (getActivity() == null) { return; } if (token == VendorsQuery._TOKEN || token == SearchQuery._TOKEN) { onVendorsOrSearchQueryComplete(cursor); } else if (token == TracksQuery._TOKEN) { onTrackQueryComplete(cursor); } else { cursor.close(); } } /** * Handle {@link VendorsQuery} {@link Cursor}. */ private void onVendorsOrSearchQueryComplete(Cursor cursor) { if (mCursor != null) { // In case cancelOperation() doesn't work and we end up with consecutive calls to this // callback. getActivity().stopManagingCursor(mCursor); mCursor = null; } // TODO(romannurik): stopManagingCursor on detach (throughout app) mCursor = cursor; getActivity().startManagingCursor(mCursor); mAdapter.changeCursor(mCursor); if (mCheckedPosition >= 0 && getView() != null) { getListView().setItemChecked(mCheckedPosition, true); } } /** * Handle {@link TracksQuery} {@link Cursor}. */ private void onTrackQueryComplete(Cursor cursor) { try { if (!cursor.moveToFirst()) { return; } // Use found track to build title-bar ActivityHelper activityHelper = ((BaseActivity) getActivity()).getActivityHelper(); String trackName = cursor.getString(TracksQuery.TRACK_NAME); activityHelper.setActionBarTitle(trackName); activityHelper.setActionBarColor(cursor.getInt(TracksQuery.TRACK_COLOR)); AnalyticsUtils.getInstance(getActivity()).trackPageView("/Sandbox/Track/" + trackName); } finally { cursor.close(); } } @Override public void onResume() { super.onResume(); getActivity().getContentResolver().registerContentObserver( ScheduleContract.Vendors.CONTENT_URI, true, mVendorChangesObserver); if (mCursor != null) { mCursor.requery(); } } @Override public void onPause() { super.onPause(); getActivity().getContentResolver().unregisterContentObserver(mVendorChangesObserver); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt(STATE_CHECKED_POSITION, mCheckedPosition); } /** {@inheritDoc} */ @Override public void onListItemClick(ListView l, View v, int position, long id) { // Launch viewer for specific vendor. final Cursor cursor = (Cursor)mAdapter.getItem(position); final String vendorId = cursor.getString(VendorsQuery.VENDOR_ID); final Uri vendorUri = ScheduleContract.Vendors.buildVendorUri(vendorId); ((BaseActivity) getActivity()).openActivityOrFragment(new Intent(Intent.ACTION_VIEW, vendorUri)); getListView().setItemChecked(position, true); mCheckedPosition = position; } public void clearCheckedPosition() { if (mCheckedPosition >= 0) { getListView().setItemChecked(mCheckedPosition, false); mCheckedPosition = -1; } } /** * {@link CursorAdapter} that renders a {@link VendorsQuery}. */ private class VendorsAdapter extends CursorAdapter { public VendorsAdapter(Context context) { super(context, null); } /** {@inheritDoc} */ @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return getActivity().getLayoutInflater().inflate(R.layout.list_item_vendor_oneline, parent, false); } /** {@inheritDoc} */ @Override public void bindView(View view, Context context, Cursor cursor) { ((TextView) view.findViewById(R.id.vendor_name)).setText( cursor.getString(VendorsQuery.NAME)); final boolean starred = cursor.getInt(VendorsQuery.STARRED) != 0; view.findViewById(R.id.star_button).setVisibility( starred ? View.VISIBLE : View.INVISIBLE); } } /** * {@link CursorAdapter} that renders a {@link SearchQuery}. */ private class SearchAdapter extends CursorAdapter { public SearchAdapter(Context context) { super(context, null); } /** {@inheritDoc} */ @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { return getActivity().getLayoutInflater().inflate(R.layout.list_item_vendor, parent, false); } /** {@inheritDoc} */ @Override public void bindView(View view, Context context, Cursor cursor) { ((TextView) view.findViewById(R.id.vendor_name)).setText(cursor .getString(SearchQuery.NAME)); final String snippet = cursor.getString(SearchQuery.SEARCH_SNIPPET); final Spannable styledSnippet = buildStyledSnippet(snippet); ((TextView) view.findViewById(R.id.vendor_location)).setText(styledSnippet); final boolean starred = cursor.getInt(VendorsQuery.STARRED) != 0; view.findViewById(R.id.star_button).setVisibility( starred ? View.VISIBLE : View.INVISIBLE); } } private ContentObserver mVendorChangesObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfChange) { if (mCursor != null) { mCursor.requery(); } } }; /** * {@link com.google.android.apps.iosched.provider.ScheduleContract.Vendors} query parameters. */ private interface VendorsQuery { int _TOKEN = 0x1; String[] PROJECTION = { BaseColumns._ID, ScheduleContract.Vendors.VENDOR_ID, ScheduleContract.Vendors.VENDOR_NAME, ScheduleContract.Vendors.VENDOR_LOCATION, ScheduleContract.Vendors.VENDOR_STARRED, }; int _ID = 0; int VENDOR_ID = 1; int NAME = 2; int LOCATION = 3; int STARRED = 4; } /** * {@link com.google.android.apps.iosched.provider.ScheduleContract.Tracks} query parameters. */ private interface TracksQuery { int _TOKEN = 0x2; String[] PROJECTION = { ScheduleContract.Tracks.TRACK_NAME, ScheduleContract.Tracks.TRACK_COLOR, }; int TRACK_NAME = 0; int TRACK_COLOR = 1; } /** {@link com.google.android.apps.iosched.provider.ScheduleContract.Vendors} search query * parameters. */ private interface SearchQuery { int _TOKEN = 0x3; String[] PROJECTION = { BaseColumns._ID, ScheduleContract.Vendors.VENDOR_ID, ScheduleContract.Vendors.VENDOR_NAME, ScheduleContract.Vendors.SEARCH_SNIPPET, ScheduleContract.Vendors.VENDOR_STARRED, }; int _ID = 0; int VENDOR_ID = 1; int NAME = 2; int SEARCH_SNIPPET = 3; int STARRED = 4; } }
Java
/* * Copyright 2011 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.apps.iosched.ui; import com.google.android.apps.iosched.R; import com.google.android.apps.iosched.provider.ScheduleContract.Sessions; import com.google.android.apps.iosched.provider.ScheduleContract.Vendors; import com.google.android.apps.iosched.ui.phone.SessionDetailActivity; import com.google.android.apps.iosched.ui.phone.VendorDetailActivity; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.TabHost; import android.widget.TabWidget; import android.widget.TextView; /** * An activity that shows the user's starred sessions and sandbox companies. This activity can be * either single or multi-pane, depending on the device configuration. We want the multi-pane * support that {@link BaseMultiPaneActivity} offers, so we inherit from it instead of * {@link BaseSinglePaneActivity}. */ public class StarredActivity extends BaseMultiPaneActivity { public static final String TAG_SESSIONS = "sessions"; public static final String TAG_VENDORS = "vendors"; private TabHost mTabHost; private TabWidget mTabWidget; private SessionsFragment mSessionsFragment; private VendorsFragment mVendorsFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_starred); getActivityHelper().setupActionBar(getTitle(), 0); mTabHost = (TabHost) findViewById(android.R.id.tabhost); mTabWidget = (TabWidget) findViewById(android.R.id.tabs); mTabHost.setup(); setupSessionsTab(); setupVendorsTab(); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); getActivityHelper().setupSubActivity(); ViewGroup detailContainer = (ViewGroup) findViewById(R.id.fragment_container_starred_detail); if (detailContainer != null && detailContainer.getChildCount() > 1) { findViewById(android.R.id.empty).setVisibility(View.GONE); } } /** * Build and add "sessions" tab. */ private void setupSessionsTab() { // TODO: this is very inefficient and messy, clean it up FrameLayout fragmentContainer = new FrameLayout(this); fragmentContainer.setId(R.id.fragment_sessions); fragmentContainer.setLayoutParams( new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT)); ((ViewGroup) findViewById(android.R.id.tabcontent)).addView(fragmentContainer); final Intent intent = new Intent(Intent.ACTION_VIEW, Sessions.CONTENT_STARRED_URI); final FragmentManager fm = getSupportFragmentManager(); mSessionsFragment = (SessionsFragment) fm.findFragmentByTag("sessions"); if (mSessionsFragment == null) { mSessionsFragment = new SessionsFragment(); mSessionsFragment.setArguments(intentToFragmentArguments(intent)); fm.beginTransaction() .add(R.id.fragment_sessions, mSessionsFragment, "sessions") .commit(); } // Sessions content comes from reused activity mTabHost.addTab(mTabHost.newTabSpec(TAG_SESSIONS) .setIndicator(buildIndicator(R.string.starred_sessions)) .setContent(R.id.fragment_sessions)); } /** * Build and add "vendors" tab. */ private void setupVendorsTab() { // TODO: this is very inefficient and messy, clean it up FrameLayout fragmentContainer = new FrameLayout(this); fragmentContainer.setId(R.id.fragment_vendors); fragmentContainer.setLayoutParams( new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT)); ((ViewGroup) findViewById(android.R.id.tabcontent)).addView(fragmentContainer); final Intent intent = new Intent(Intent.ACTION_VIEW, Vendors.CONTENT_STARRED_URI); final FragmentManager fm = getSupportFragmentManager(); mVendorsFragment = (VendorsFragment) fm.findFragmentByTag("vendors"); if (mVendorsFragment == null) { mVendorsFragment = new VendorsFragment(); mVendorsFragment.setArguments(intentToFragmentArguments(intent)); fm.beginTransaction() .add(R.id.fragment_vendors, mVendorsFragment, "vendors") .commit(); } // Vendors content comes from reused activity mTabHost.addTab(mTabHost.newTabSpec(TAG_VENDORS) .setIndicator(buildIndicator(R.string.starred_vendors)) .setContent(R.id.fragment_vendors)); } /** * Build a {@link View} to be used as a tab indicator, setting the requested string resource as * its label. */ private View buildIndicator(int textRes) { final TextView indicator = (TextView) getLayoutInflater().inflate(R.layout.tab_indicator, mTabWidget, false); indicator.setText(textRes); return indicator; } @Override public FragmentReplaceInfo onSubstituteFragmentForActivityLaunch(String activityClassName) { if (findViewById(R.id.fragment_container_starred_detail) != null) { // The layout we currently have has a detail container, we can add fragments there. findViewById(android.R.id.empty).setVisibility(View.GONE); if (SessionDetailActivity.class.getName().equals(activityClassName)) { clearSelectedItems(); return new FragmentReplaceInfo( SessionDetailFragment.class, "session_detail", R.id.fragment_container_starred_detail); } else if (VendorDetailActivity.class.getName().equals(activityClassName)) { clearSelectedItems(); return new FragmentReplaceInfo( VendorDetailFragment.class, "vendor_detail", R.id.fragment_container_starred_detail); } } return null; } private void clearSelectedItems() { if (mSessionsFragment != null) { mSessionsFragment.clearCheckedPosition(); } if (mVendorsFragment != null) { mVendorsFragment.clearCheckedPosition(); } } }
Java
/* * Copyright 2011 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.apps.iosched.ui; import com.google.android.apps.iosched.R; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import android.webkit.WebViewClient; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; /** * A {@link WebView}-based fragment that shows Google Realtime Search results for a given query, * provided as the {@link TagStreamFragment#EXTRA_QUERY} extra in the fragment arguments. If no * search query is provided, the conference hashtag is used as the default query. */ public class TagStreamFragment extends Fragment { private static final String TAG = "TagStreamFragment"; public static final String EXTRA_QUERY = "com.google.android.iosched.extra.QUERY"; public static final String CONFERENCE_HASHTAG = "#io2011"; private String mSearchString; private WebView mWebView; private View mLoadingSpinner; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); final Intent intent = BaseActivity.fragmentArgumentsToIntent(getArguments()); mSearchString = intent.getStringExtra(EXTRA_QUERY); if (TextUtils.isEmpty(mSearchString)) { mSearchString = CONFERENCE_HASHTAG; } if (!mSearchString.startsWith("#")) { mSearchString = "#" + mSearchString; } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ViewGroup root = (ViewGroup) inflater.inflate(R.layout.fragment_webview_with_spinner, null); // For some reason, if we omit this, NoSaveStateFrameLayout thinks we are // FILL_PARENT / WRAP_CONTENT, making the progress bar stick to the top of the activity. root.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT)); mLoadingSpinner = root.findViewById(R.id.loading_spinner); mWebView = (WebView) root.findViewById(R.id.webview); mWebView.setWebViewClient(mWebViewClient); mWebView.post(new Runnable() { public void run() { mWebView.getSettings().setJavaScriptEnabled(true); mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(false); try { mWebView.loadUrl( "http://www.google.com/search?tbs=" + "mbl%3A1&hl=en&source=hp&biw=1170&bih=668&q=" + URLEncoder.encode(mSearchString, "UTF-8") + "&btnG=Search"); } catch (UnsupportedEncodingException e) { Log.e(TAG, "Could not construct the realtime search URL", e); } } }); return root; } public void refresh() { mWebView.reload(); } private WebViewClient mWebViewClient = new WebViewClient() { @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); mLoadingSpinner.setVisibility(View.VISIBLE); mWebView.setVisibility(View.INVISIBLE); } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); mLoadingSpinner.setVisibility(View.GONE); mWebView.setVisibility(View.VISIBLE); } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url.startsWith("javascript")) { return false; } Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(intent); return true; } }; }
Java