repo_name
stringlengths 7
104
| file_path
stringlengths 11
238
| context
list | import_statement
stringlengths 103
6.85k
| code
stringlengths 60
38.4k
| next_line
stringlengths 10
824
| gold_snippet_index
int32 0
8
|
---|---|---|---|---|---|---|
wangchongjie/multi-engine | src/main/java/com/baidu/unbiz/multiengine/codec/bytebuf/ByteEncoder.java | [
"public interface ByteBufCodec {\n\n /**\n * 将对象编码成ByteBuf\n * \n * @param object 编码对象\n * @return byte数组\n * @throws CodecException\n */\n byte[] encode(Object object) throws CodecException;\n\n /**\n * 将ByteBuf解码成对象\n * \n * @param byteBuf 字节缓冲区 @see ByteBuf\n * @param length 字节长度\n * @param clazz 对象类型\n * @return 解码对象\n * @throws CodecException\n */\n <T> T decode(ByteBuf byteBuf, int length, Class<T> clazz) throws CodecException;\n\n}",
"public interface HeadCodec extends MsgCodec {\n /**\n * 反序列化\n *\n * @param clazz 反序列化后的类定义\n * @param bytes 字节码\n *\n * @return 反序列化后的对象\n *\n * @throws CodecException\n */\n <T> T decode(Class<T> clazz, byte[] bytes) throws CodecException;\n\n /**\n * 序列化\n *\n * @param object 待序列化的对象\n *\n * @return 字节码\n *\n * @throws CodecException\n */\n <T> byte[] encode(T object) throws CodecException;\n\n /**\n * head的类型\n *\n * @return\n */\n Class getHeadClass();\n}",
"public interface MsgCodec {\n /**\n * 反序列化\n *\n * @param clazz 反序列化后的类定义\n * @param bytes 字节码\n * @return 反序列化后的对象\n * @throws CodecException\n */\n <T> T decode(Class<T> clazz, byte[] bytes) throws CodecException;\n\n /**\n * 序列化\n *\n * @param object 待序列化的对象\n * @return 字节码\n * @throws CodecException\n */\n <T> byte[] encode(T object) throws CodecException;\n}",
"public class MsgHeadCodec implements HeadCodec {\n\n @Override\n public <T> T decode(final Class<T> clazz, byte[] data) throws CodecException {\n return (T) MsgHead.fromBytes(data);\n }\n\n @Override\n public <T> byte[] encode(T object) throws CodecException {\n if (object instanceof MsgHead) {\n return ((MsgHead) object).toBytes();\n }\n throw new CodecException(\"not support non-msghead\");\n }\n\n @Override\n public Class getHeadClass() {\n return MsgHead.class;\n }\n\n}",
"public class ProtostuffCodec implements MsgCodec {\n\n /**\n * 设置编码规则\n */\n static {\n System.setProperty(\"protostuff.runtime.collection_schema_on_repeated_fields\", \"true\");\n System.setProperty(\"protostuff.runtime.morph_collection_interfaces\", \"true\");\n System.setProperty(\"protostuff.runtime.morph_map_interfaces\", \"true\");\n }\n\n /**\n * 缓冲区\n */\n private ThreadLocal<LinkedBuffer> linkedBuffer = new ThreadLocal<LinkedBuffer>() {\n @Override\n protected LinkedBuffer initialValue() {\n return LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);\n }\n };\n\n @Override\n public <T> T decode(final Class<T> clazz, byte[] data) throws CodecException {\n Schema<T> schema = RuntimeSchema.getSchema(clazz);\n\n T content = ReflectionUtil.newInstance(clazz);\n ProtobufIOUtil.mergeFrom(data, content, schema);\n return content;\n }\n\n @Override\n public <T> byte[] encode(T object) throws CodecException {\n try {\n @SuppressWarnings(\"unchecked\")\n com.dyuproject.protostuff.Schema<T> schema =\n (com.dyuproject.protostuff.Schema<T>) RuntimeSchema.getSchema(object.getClass());\n byte[] protostuff = ProtobufIOUtil.toByteArray(object, schema, linkedBuffer.get());\n return protostuff;\n } finally {\n linkedBuffer.get().clear();\n }\n }\n\n}",
"public class CodecException extends RuntimeException {\n\n /**\n * serialVersionUID\n */\n private static final long serialVersionUID = 5196421433506179782L;\n\n /**\n * Creates a new instance of CodecException.\n */\n public CodecException() {\n super();\n }\n\n /**\n * Creates a new instance of CodecException.\n * \n * @param arg0\n * @param arg1\n */\n public CodecException(String arg0, Throwable arg1) {\n super(arg0, arg1);\n }\n\n /**\n * Creates a new instance of CodecException.\n * \n * @param arg0\n */\n public CodecException(String arg0) {\n super(arg0);\n }\n\n /**\n * Creates a new instance of CodecException.\n * \n * @param arg0\n */\n public CodecException(Throwable arg0) {\n super(arg0);\n }\n\n}",
"public class Signal<T> {\n\n protected long seqId;\n protected T message;\n protected SignalType type = SignalType.TASK_COMMOND;\n\n public Signal() {\n }\n\n public Signal(T message) {\n this.message = message;\n }\n\n public T getMessage() {\n return message;\n }\n\n public void setMessage(T message) {\n this.message = message;\n }\n\n public long getSeqId() {\n return seqId;\n }\n\n public void setSeqId(long seqId) {\n this.seqId = seqId;\n }\n\n public String toString() {\n return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);\n }\n\n public SignalType getType() {\n return type;\n }\n\n public void setType(SignalType type) {\n this.type = type;\n }\n}",
"public final class MsgHead {\n\n /**\n * session内顺序Id\n */\n private long seqId;\n\n /**\n * int (4) 当前包的数据长度\n */\n private int bodyLen;\n\n public static final int SIZE = 12;\n\n private static String DEF_ENCODING = \"GBK\";\n\n private MsgHead() {\n\n }\n\n private MsgHead(long seqId, int bodyLen) {\n this.seqId = seqId;\n this.bodyLen = bodyLen;\n }\n\n public static MsgHead create() {\n return new MsgHead();\n }\n\n public static MsgHead create(long seqId) {\n MsgHead head = new MsgHead();\n head.setSeqId(seqId);\n return head;\n }\n\n /**\n * write pack_head to transport\n */\n public byte[] toBytes() {\n ByteBuffer bb = ByteBuffer.allocate(SIZE);\n bb.order(ByteOrder.LITTLE_ENDIAN);\n\n try {\n bb.putLong(seqId);\n bb.putInt(bodyLen);\n } catch (Exception e) {\n throw new RuntimeException(\"exception when putting bytes for nshead...\", e);\n }\n return bb.array();\n }\n\n /**\n * 由byte数组解析成PackHead对象\n */\n public static MsgHead fromBytes(byte[] headBytes) {\n MsgHead head = new MsgHead();\n if (headBytes.length < MsgHead.SIZE) {\n throw new RuntimeException(\"NSHead's size should equal 16.\");\n }\n ByteBuffer buffer = ByteBuffer.wrap(headBytes);\n buffer.order(ByteOrder.LITTLE_ENDIAN);\n head.seqId = buffer.getLong();\n head.bodyLen = buffer.getInt();\n return head;\n }\n\n public long getSeqId() {\n return seqId;\n }\n\n public void setSeqId(long seqId) {\n this.seqId = seqId;\n }\n\n public int getBodyLen() {\n return bodyLen;\n }\n\n public void setBodyLen(int bodyLen) {\n this.bodyLen = bodyLen;\n }\n\n @Override\n public String toString() {\n return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);\n }\n}",
"public final class NSHead {\n public static final int SIZE = 36;\n\n private static final int VERSION = 2;\n private static final int PROVIDER_LEN = 16;\n private static final long MAGIC_NUM = 0x012FAE3A;\n\n private static String DEF_ENCODING = \"GBK\";\n\n private int id = 0;\n private int version = 0;\n\n /**\n * unsigned int (4) 由 apache 产生的 logid,贯穿一次请求的所有网络交互。 要求前端产生的 logid 在短时间内 (例如 10 秒内) 在所有前端服务器范围内都不会重复出现 目的是用时间和\n * log_id 能够确定唯一一次 kr 会话\n */\n private long logId = 0;\n\n /**\n * char (16) 请求包为客户端标识,命名方式:产品名-模块名,比如 \"sf-web\\0\",\n * \"im-ext\\0\",”fc-web\\0”,凤巢客户端一定要填上”fc-web\\0”,否则得到的res中的竞价客户数是shifen的竞价客户数\n */\n private String provider;\n\n /**\n * unsigned int (4) 特殊标识:常数 0xfb709394,标识一个包的起始\n */\n private long magicNum = MAGIC_NUM;\n\n private long reserved;\n\n /**\n * unsigned int (4) head后数据的总长度\n */\n private long bodyLen;\n\n private NSHead() {\n\n }\n\n private NSHead(String provider) {\n this(0, VERSION, (long) 0, provider, MAGIC_NUM, 0x00, 0L);\n }\n\n private NSHead(int id, int version, long logId, String provider, long magicNum, int reserved, long bodyLen) {\n this.id = id;\n this.version = version;\n this.logId = logId;\n this.provider = provider;\n this.magicNum = magicNum;\n this.reserved = reserved;\n this.bodyLen = bodyLen;\n }\n\n public static NSHead factory(String provider) {\n return new NSHead(provider);\n }\n\n /**\n * write ns_head to transport\n */\n public byte[] toBytes() {\n ByteBuffer bb = ByteBuffer.allocate(SIZE);\n bb.order(ByteOrder.LITTLE_ENDIAN);\n\n try {\n bb.putShort((short) id);\n bb.putShort((short) version);\n bb.putInt((int) logId);\n byte[] prvd = provider.getBytes(DEF_ENCODING);\n byte[] pb = new byte[PROVIDER_LEN];\n System.arraycopy(prvd, 0, pb, 0, prvd.length);\n bb.put(pb);\n bb.putInt((int) magicNum);\n bb.putInt((int) reserved);\n bb.putInt((int) bodyLen);\n } catch (Exception e) {\n throw new RuntimeException(\"exception when putting bytes for nshead...\", e);\n }\n\n return bb.array();\n }\n\n /**\n * 由byte数组解析成NsHead对象\n *\n * @param headBytes 36-bytes\n *\n * @return 2012-9-21\n */\n public static NSHead fromBytes(byte[] headBytes) {\n NSHead head = new NSHead();\n if (headBytes.length < NSHead.SIZE) {\n throw new RuntimeException(\"NSHead's size should equal 16.\");\n }\n ByteBuffer buffer = ByteBuffer.wrap(headBytes);\n buffer.order(ByteOrder.LITTLE_ENDIAN);\n head.id = buffer.getShort();\n head.version = buffer.getShort();\n head.logId = buffer.getInt();\n\n byte[] hb = new byte[PROVIDER_LEN];\n buffer.get(hb, 0, PROVIDER_LEN);\n try {\n head.setProvider(new String(hb, DEF_ENCODING));\n } catch (UnsupportedEncodingException e) {\n // ignore\n throw new RuntimeException(e);\n }\n head.magicNum = buffer.getInt();\n head.reserved = buffer.getInt();\n head.bodyLen = buffer.getInt();\n\n return head;\n }\n\n @Override\n public String toString() {\n return \"[ version: \" + version + \", id:\" + id + \" logId:\" + logId + \" bodyLen:\" + bodyLen + \"]\";\n }\n\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public int getVersion() {\n return version;\n }\n\n public void setVersion(short version) {\n this.version = version;\n }\n\n public long getLogId() {\n return logId;\n }\n\n public void setLogId(long logId) {\n this.logId = logId;\n }\n\n public String getProvider(String charset) {\n return this.provider;\n }\n\n public void setProvider(String provider) {\n this.provider = provider;\n }\n\n public long getMagicNum() {\n return magicNum;\n }\n\n public void setMagicNum(long magicNum) {\n this.magicNum = magicNum;\n }\n\n public long getReserved() {\n return reserved;\n }\n\n public void setReserved(int reserved) {\n this.reserved = reserved;\n }\n\n public long getBodyLen() {\n return bodyLen;\n }\n\n public void setBodyLen(int bodyLen) {\n this.bodyLen = bodyLen;\n }\n}"
] | import org.slf4j.Logger;
import com.baidu.unbiz.multiengine.codec.ByteBufCodec;
import com.baidu.unbiz.multiengine.codec.HeadCodec;
import com.baidu.unbiz.multiengine.codec.MsgCodec;
import com.baidu.unbiz.multiengine.codec.common.MsgHeadCodec;
import com.baidu.unbiz.multiengine.codec.common.ProtostuffCodec;
import com.baidu.unbiz.multiengine.exception.CodecException;
import com.baidu.unbiz.multiengine.transport.dto.Signal;
import com.baidu.unbiz.multiengine.transport.protocol.MsgHead;
import com.baidu.unbiz.multiengine.transport.protocol.NSHead;
import com.baidu.unbiz.multitask.log.AopLogFactory;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder; | package com.baidu.unbiz.multiengine.codec.bytebuf;
/**
* 二进制编码器
*/
public class ByteEncoder extends MessageToByteEncoder<Object> {
protected static final Logger LOG = AopLogFactory.getLogger(ByteEncoder.class);
private Class<?> headerClass;
/**
* ByteBuf的编解码器
*/
protected ByteBufCodec byteBufCodec = new MsgCodecAdaptor(new ProtostuffCodec()); | protected ByteBufCodec headBufCodec = new MsgCodecAdaptor(new MsgHeadCodec()); | 3 |
JoostvDoorn/GlutenVrijApp | app/src/main/java/com/joostvdoorn/glutenvrij/scanner/core/oned/UPCAReader.java | [
"public final class BarcodeFormat {\n\n // No, we can't use an enum here. J2ME doesn't support it.\n\n private static final Hashtable VALUES = new Hashtable();\n\n /** Aztec 2D barcode format. */\n public static final BarcodeFormat AZTEC = new BarcodeFormat(\"AZTEC\");\n\n /** CODABAR 1D format. */\n public static final BarcodeFormat CODABAR = new BarcodeFormat(\"CODABAR\");\n\n /** Code 39 1D format. */\n public static final BarcodeFormat CODE_39 = new BarcodeFormat(\"CODE_39\");\n\n /** Code 93 1D format. */\n public static final BarcodeFormat CODE_93 = new BarcodeFormat(\"CODE_93\");\n\n /** Code 128 1D format. */\n public static final BarcodeFormat CODE_128 = new BarcodeFormat(\"CODE_128\");\n\n /** Data Matrix 2D barcode format. */\n public static final BarcodeFormat DATA_MATRIX = new BarcodeFormat(\"DATA_MATRIX\");\n\n /** EAN-8 1D format. */\n public static final BarcodeFormat EAN_8 = new BarcodeFormat(\"EAN_8\");\n\n /** EAN-13 1D format. */\n public static final BarcodeFormat EAN_13 = new BarcodeFormat(\"EAN_13\");\n\n /** ITF (Interleaved Two of Five) 1D format. */\n public static final BarcodeFormat ITF = new BarcodeFormat(\"ITF\");\n\n /** PDF417 format. */\n public static final BarcodeFormat PDF_417 = new BarcodeFormat(\"PDF_417\");\n\n /** QR Code 2D barcode format. */\n public static final BarcodeFormat QR_CODE = new BarcodeFormat(\"QR_CODE\");\n\n /** RSS 14 */\n public static final BarcodeFormat RSS_14 = new BarcodeFormat(\"RSS_14\");\n\n /** RSS EXPANDED */\n public static final BarcodeFormat RSS_EXPANDED = new BarcodeFormat(\"RSS_EXPANDED\");\n\n /** UPC-A 1D format. */\n public static final BarcodeFormat UPC_A = new BarcodeFormat(\"UPC_A\");\n\n /** UPC-E 1D format. */\n public static final BarcodeFormat UPC_E = new BarcodeFormat(\"UPC_E\");\n\n /** UPC/EAN extension format. Not a stand-alone format. */\n public static final BarcodeFormat UPC_EAN_EXTENSION = new BarcodeFormat(\"UPC_EAN_EXTENSION\");\n\n private final String name;\n\n private BarcodeFormat(String name) {\n this.name = name;\n VALUES.put(name, this);\n }\n\n public String getName() {\n return name;\n }\n\n public String toString() {\n return name;\n }\n\n public static BarcodeFormat valueOf(String name) {\n if (name == null || name.length() == 0) {\n throw new IllegalArgumentException();\n }\n BarcodeFormat format = (BarcodeFormat) VALUES.get(name);\n if (format == null) {\n throw new IllegalArgumentException();\n }\n return format;\n }\n\n}",
"public final class BinaryBitmap {\n\n private final Binarizer binarizer;\n private BitMatrix matrix;\n\n public BinaryBitmap(Binarizer binarizer) {\n if (binarizer == null) {\n throw new IllegalArgumentException(\"Binarizer must be non-null.\");\n }\n this.binarizer = binarizer;\n matrix = null;\n }\n\n /**\n * @return The width of the bitmap.\n */\n public int getWidth() {\n return binarizer.getLuminanceSource().getWidth();\n }\n\n /**\n * @return The height of the bitmap.\n */\n public int getHeight() {\n return binarizer.getLuminanceSource().getHeight();\n }\n\n /**\n * Converts one row of luminance data to 1 bit data. May actually do the conversion, or return\n * cached data. Callers should assume this method is expensive and call it as seldom as possible.\n * This method is intended for decoding 1D barcodes and may choose to apply sharpening.\n *\n * @param y The row to fetch, 0 <= y < bitmap height.\n * @param row An optional preallocated array. If null or too small, it will be ignored.\n * If used, the Binarizer will call BitArray.clear(). Always use the returned object.\n * @return The array of bits for this row (true means black).\n */\n public BitArray getBlackRow(int y, BitArray row) throws NotFoundException {\n return binarizer.getBlackRow(y, row);\n }\n\n /**\n * Converts a 2D array of luminance data to 1 bit. As above, assume this method is expensive\n * and do not call it repeatedly. This method is intended for decoding 2D barcodes and may or\n * may not apply sharpening. Therefore, a row from this matrix may not be identical to one\n * fetched using getBlackRow(), so don't mix and match between them.\n *\n * @return The 2D array of bits for the image (true means black).\n */\n public BitMatrix getBlackMatrix() throws NotFoundException {\n // The matrix is created on demand the first time it is requested, then cached. There are two\n // reasons for this:\n // 1. This work will never be done if the caller only installs 1D Reader objects, or if a\n // 1D Reader finds a barcode before the 2D Readers run.\n // 2. This work will only be done once even if the caller installs multiple 2D Readers.\n if (matrix == null) {\n matrix = binarizer.getBlackMatrix();\n }\n return matrix;\n }\n\n /**\n * @return Whether this bitmap can be cropped.\n */\n public boolean isCropSupported() {\n return binarizer.getLuminanceSource().isCropSupported();\n }\n\n /**\n * Returns a new object with cropped image data. Implementations may keep a reference to the\n * original data rather than a copy. Only callable if isCropSupported() is true.\n *\n * @param left The left coordinate, 0 <= left < getWidth().\n * @param top The top coordinate, 0 <= top <= getHeight().\n * @param width The width of the rectangle to crop.\n * @param height The height of the rectangle to crop.\n * @return A cropped version of this object.\n */\n public BinaryBitmap crop(int left, int top, int width, int height) {\n LuminanceSource newSource = binarizer.getLuminanceSource().crop(left, top, width, height);\n return new BinaryBitmap(binarizer.createBinarizer(newSource));\n }\n\n /**\n * @return Whether this bitmap supports counter-clockwise rotation.\n */\n public boolean isRotateSupported() {\n return binarizer.getLuminanceSource().isRotateSupported();\n }\n\n /**\n * Returns a new object with rotated image data. Only callable if isRotateSupported() is true.\n *\n * @return A rotated version of this object.\n */\n public BinaryBitmap rotateCounterClockwise() {\n LuminanceSource newSource = binarizer.getLuminanceSource().rotateCounterClockwise();\n return new BinaryBitmap(binarizer.createBinarizer(newSource));\n }\n\n}",
"public final class ChecksumException extends ReaderException {\n\n private static final ChecksumException instance = new ChecksumException();\n\n private ChecksumException() {\n // do nothing\n }\n\n public static ChecksumException getChecksumInstance() {\n return instance;\n }\n\n}",
"public final class FormatException extends ReaderException {\n\n private static final FormatException instance = new FormatException();\n\n private FormatException() {\n // do nothing\n }\n\n public static FormatException getFormatInstance() {\n return instance;\n }\n\n}",
"public final class NotFoundException extends ReaderException {\n\n private static final NotFoundException instance = new NotFoundException();\n\n private NotFoundException() {\n // do nothing\n }\n\n public static NotFoundException getNotFoundInstance() {\n return instance;\n }\n\n}",
"public final class Result {\n\n private final String text;\n private final byte[] rawBytes;\n private ResultPoint[] resultPoints;\n private final BarcodeFormat format;\n private Hashtable resultMetadata;\n private final long timestamp;\n\n public Result(String text,\n byte[] rawBytes,\n ResultPoint[] resultPoints,\n BarcodeFormat format) {\n this(text, rawBytes, resultPoints, format, System.currentTimeMillis());\n }\n\n public Result(String text,\n byte[] rawBytes,\n ResultPoint[] resultPoints,\n BarcodeFormat format,\n long timestamp) {\n if (text == null && rawBytes == null) {\n throw new IllegalArgumentException(\"Text and bytes are null\");\n }\n this.text = text;\n this.rawBytes = rawBytes;\n this.resultPoints = resultPoints;\n this.format = format;\n this.resultMetadata = null;\n this.timestamp = timestamp;\n }\n\n /**\n * @return raw text encoded by the barcode, if applicable, otherwise <code>null</code>\n */\n public String getText() {\n return text;\n }\n\n /**\n * @return raw bytes encoded by the barcode, if applicable, otherwise <code>null</code>\n */\n public byte[] getRawBytes() {\n return rawBytes;\n }\n\n /**\n * @return points related to the barcode in the image. These are typically points\n * identifying finder patterns or the corners of the barcode. The exact meaning is\n * specific to the type of barcode that was decoded.\n */\n public ResultPoint[] getResultPoints() {\n return resultPoints;\n }\n\n /**\n * @return {@link BarcodeFormat} representing the format of the barcode that was decoded\n */\n public BarcodeFormat getBarcodeFormat() {\n return format;\n }\n\n /**\n * @return {@link Hashtable} mapping {@link ResultMetadataType} keys to values. May be\n * <code>null</code>. This contains optional metadata about what was detected about the barcode,\n * like orientation.\n */\n public Hashtable getResultMetadata() {\n return resultMetadata;\n }\n\n public void putMetadata(ResultMetadataType type, Object value) {\n if (resultMetadata == null) {\n resultMetadata = new Hashtable(3);\n }\n resultMetadata.put(type, value);\n }\n\n public void putAllMetadata(Hashtable metadata) {\n if (metadata != null) {\n if (resultMetadata == null) {\n resultMetadata = metadata;\n } else {\n Enumeration e = metadata.keys();\n while (e.hasMoreElements()) {\n ResultMetadataType key = (ResultMetadataType) e.nextElement();\n Object value = metadata.get(key);\n resultMetadata.put(key, value);\n }\n }\n }\n }\n\n public void addResultPoints(ResultPoint[] newPoints) {\n if (resultPoints == null) {\n resultPoints = newPoints;\n } else if (newPoints != null && newPoints.length > 0) {\n ResultPoint[] allPoints = new ResultPoint[resultPoints.length + newPoints.length];\n System.arraycopy(resultPoints, 0, allPoints, 0, resultPoints.length);\n System.arraycopy(newPoints, 0, allPoints, resultPoints.length, newPoints.length);\n resultPoints = allPoints;\n }\n }\n\n public long getTimestamp() {\n return timestamp;\n }\n\n public String toString() {\n if (text == null) {\n return \"[\" + rawBytes.length + \" bytes]\";\n } else {\n return text;\n }\n }\n\n}",
"public final class BitArray {\n // I have changed these members to be public so ProGuard can inline get() and set(). Ideally\n // they'd be private and we'd use the -allowaccessmodification flag, but Dalvik rejects the\n // resulting binary at runtime on Android. If we find a solution to this, these should be changed\n // back to private.\n public int[] bits;\n public int size;\n\n public BitArray() {\n this.size = 0;\n this.bits = new int[1];\n }\n\n public BitArray(int size) {\n this.size = size;\n this.bits = makeArray(size);\n }\n\n public int getSize() {\n return size;\n }\n\n public int getSizeInBytes() {\n return (size + 7) >> 3;\n }\n\n private void ensureCapacity(int size) {\n if (size > bits.length << 5) {\n int[] newBits = makeArray(size);\n System.arraycopy(bits, 0, newBits, 0, bits.length);\n this.bits = newBits;\n }\n }\n\n /**\n * @param i bit to get\n * @return true iff bit i is set\n */\n public boolean get(int i) {\n return (bits[i >> 5] & (1 << (i & 0x1F))) != 0;\n }\n\n /**\n * Sets bit i.\n *\n * @param i bit to set\n */\n public void set(int i) {\n bits[i >> 5] |= 1 << (i & 0x1F);\n }\n\n /**\n * Flips bit i.\n *\n * @param i bit to set\n */\n public void flip(int i) {\n bits[i >> 5] ^= 1 << (i & 0x1F);\n }\n\n /**\n * Sets a block of 32 bits, starting at bit i.\n *\n * @param i first bit to set\n * @param newBits the new value of the next 32 bits. Note again that the least-significant bit\n * corresponds to bit i, the next-least-significant to i+1, and so on.\n */\n public void setBulk(int i, int newBits) {\n bits[i >> 5] = newBits;\n }\n\n /**\n * Clears all bits (sets to false).\n */\n public void clear() {\n int max = bits.length;\n for (int i = 0; i < max; i++) {\n bits[i] = 0;\n }\n }\n\n /**\n * Efficient method to check if a range of bits is set, or not set.\n *\n * @param start start of range, inclusive.\n * @param end end of range, exclusive\n * @param value if true, checks that bits in range are set, otherwise checks that they are not set\n * @return true iff all bits are set or not set in range, according to value argument\n * @throws IllegalArgumentException if end is less than or equal to start\n */\n public boolean isRange(int start, int end, boolean value) {\n if (end < start) {\n throw new IllegalArgumentException();\n }\n if (end == start) {\n return true; // empty range matches\n }\n end--; // will be easier to treat this as the last actually set bit -- inclusive\n int firstInt = start >> 5;\n int lastInt = end >> 5;\n for (int i = firstInt; i <= lastInt; i++) {\n int firstBit = i > firstInt ? 0 : start & 0x1F;\n int lastBit = i < lastInt ? 31 : end & 0x1F;\n int mask;\n if (firstBit == 0 && lastBit == 31) {\n mask = -1;\n } else {\n mask = 0;\n for (int j = firstBit; j <= lastBit; j++) {\n mask |= 1 << j;\n }\n }\n\n // Return false if we're looking for 1s and the masked bits[i] isn't all 1s (that is,\n // equals the mask, or we're looking for 0s and the masked portion is not all 0s\n if ((bits[i] & mask) != (value ? mask : 0)) {\n return false;\n }\n }\n return true;\n }\n\n public void appendBit(boolean bit) {\n ensureCapacity(size + 1);\n if (bit) {\n bits[size >> 5] |= (1 << (size & 0x1F));\n }\n size++;\n }\n\n /**\n * Appends the least-significant bits, from value, in order from most-significant to\n * least-significant. For example, appending 6 bits from 0x000001E will append the bits\n * 0, 1, 1, 1, 1, 0 in that order.\n */\n public void appendBits(int value, int numBits) {\n if (numBits < 0 || numBits > 32) {\n throw new IllegalArgumentException(\"Num bits must be between 0 and 32\");\n }\n ensureCapacity(size + numBits);\n for (int numBitsLeft = numBits; numBitsLeft > 0; numBitsLeft--) {\n appendBit(((value >> (numBitsLeft - 1)) & 0x01) == 1);\n }\n }\n\n public void appendBitArray(BitArray other) {\n int otherSize = other.getSize();\n ensureCapacity(size + otherSize);\n for (int i = 0; i < otherSize; i++) {\n appendBit(other.get(i));\n }\n }\n\n public void xor(BitArray other) {\n if (bits.length != other.bits.length) {\n throw new IllegalArgumentException(\"Sizes don't match\");\n }\n for (int i = 0; i < bits.length; i++) {\n // The last byte could be incomplete (i.e. not have 8 bits in\n // it) but there is no problem since 0 XOR 0 == 0.\n bits[i] ^= other.bits[i];\n }\n }\n\n /**\n *\n * @param bitOffset first bit to start writing\n * @param array array to write into. Bytes are written most-significant byte first. This is the opposite\n * of the internal representation, which is exposed by {@link #getBitArray()}\n * @param offset position in array to start writing\n * @param numBytes how many bytes to write\n */\n public void toBytes(int bitOffset, byte[] array, int offset, int numBytes) {\n for (int i = 0; i < numBytes; i++) {\n int theByte = 0;\n for (int j = 0; j < 8; j++) {\n if (get(bitOffset)) {\n theByte |= 1 << (7 - j);\n }\n bitOffset++;\n }\n array[offset + i] = (byte) theByte;\n }\n }\n\n /**\n * @return underlying array of ints. The first element holds the first 32 bits, and the least\n * significant bit is bit 0.\n */\n public int[] getBitArray() {\n return bits;\n }\n\n /**\n * Reverses all bits in the array.\n */\n public void reverse() {\n int[] newBits = new int[bits.length];\n int size = this.size;\n for (int i = 0; i < size; i++) {\n if (get(size - i - 1)) {\n newBits[i >> 5] |= 1 << (i & 0x1F);\n }\n }\n bits = newBits;\n }\n\n private static int[] makeArray(int size) {\n return new int[(size + 31) >> 5];\n }\n\n public String toString() {\n StringBuffer result = new StringBuffer(size);\n for (int i = 0; i < size; i++) {\n if ((i & 0x07) == 0) {\n result.append(' ');\n }\n result.append(get(i) ? 'X' : '.');\n }\n return result.toString();\n }\n\n}"
] | import com.joostvdoorn.glutenvrij.scanner.core.BarcodeFormat;
import com.joostvdoorn.glutenvrij.scanner.core.BinaryBitmap;
import com.joostvdoorn.glutenvrij.scanner.core.ChecksumException;
import com.joostvdoorn.glutenvrij.scanner.core.FormatException;
import com.joostvdoorn.glutenvrij.scanner.core.NotFoundException;
import com.joostvdoorn.glutenvrij.scanner.core.Result;
import com.joostvdoorn.glutenvrij.scanner.core.common.BitArray;
import java.util.Hashtable; | /*
* Copyright 2008 ZXing authors
*
* 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.joostvdoorn.glutenvrij.scanner.core.oned;
/**
* <p>Implements decoding of the UPC-A format.</p>
*
* @author [email protected] (Daniel Switkin)
* @author Sean Owen
*/
public final class UPCAReader extends UPCEANReader {
private final UPCEANReader ean13Reader = new EAN13Reader();
| public Result decodeRow(int rowNumber, BitArray row, int[] startGuardRange, Hashtable hints) | 6 |
leelit/STUer-client | app/src/main/java/com/leelit/stuer/module_treehole/presenter/CommentPresenter.java | [
"public class LoginActivity extends AppCompatActivity {\n\n\n public static final String[] INFOS = {\"SP_NAME\", \"SP_TEL\", \"SP_SHORT_TEL\", \"SP_WECHAT\"};\n public static final String IS_REGISTER = \"SP_IS_REGISTER\";\n\n @InjectView(R.id.et_name)\n EditText mEtName;\n @InjectView(R.id.et_tel)\n EditText mEtTel;\n @InjectView(R.id.et_shortTel)\n EditText mEtShortTel;\n @InjectView(R.id.et_wechat)\n EditText mEtWechat;\n @InjectView(R.id.toolbar)\n Toolbar mToolbar;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_login);\n ButterKnife.inject(this);\n UiUtils.setTranslucentStatusBar(this);\n initSP(); // 放在下面debug时虽然会执行到,但就是不显示...\n if (UiUtils.isNightMode(this)){\n return;\n }\n\n initToolbar(\"填写个人信息\");\n }\n\n private void initToolbar(String title) {\n mToolbar.setTitle(getString(R.string.post_title));\n setSupportActionBar(mToolbar);\n mToolbar.setTitle(title);\n mToolbar.setNavigationIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha);\n mToolbar.setNavigationOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n finish();\n }\n });\n }\n\n private void initSP() {\n EditText[] editText = {mEtName, mEtTel, mEtShortTel, mEtWechat};\n for (int i = 0; i < 4; i++) {\n String et_value = SPUtils.getString(INFOS[i]);\n if (!TextUtils.isEmpty(et_value)) {\n editText[i].setText(et_value);\n }\n }\n }\n\n private void saveSp() {\n if (isEmpty(mEtName) || isEmpty(mEtTel) || isEmpty(mEtShortTel) || isEmpty(mEtWechat)) {\n return;\n } else {\n boolean firstTime = !SPUtils.getBoolean(IS_REGISTER);\n String[] values = {mEtName.getText().toString(), mEtTel.getText().toString(), mEtShortTel.getText().toString(), mEtWechat.getText().toString()};\n SPUtils.save(INFOS, values);\n SPUtils.save(IS_REGISTER, true);\n Toast.makeText(LoginActivity.this, \"保存成功\", Toast.LENGTH_SHORT).show();\n if (firstTime) {\n startActivity(new Intent(this, MainActivity.class));\n finish();\n }\n }\n }\n\n private boolean isEmpty(EditText et) {\n if (TextUtils.isEmpty(et.getText())) {\n et.setError(\"不能为空\");\n return true;\n }\n return false;\n }\n\n\n @Override\n public boolean onCreateOptionsMenu(Menu menu) {\n // Inflate the menu; this adds items to the action bar if it is present.\n getMenuInflater().inflate(R.menu.menu_login, menu);\n return true;\n }\n\n @Override\n public boolean onOptionsItemSelected(MenuItem item) {\n // Handle action bar item clicks here. The action bar will\n // automatically handle clicks on the Home/Up button, so long\n // as you specify a parent activity in AndroidManifest.xml.\n int id = item.getItemId();\n\n //noinspection SimplifiableIfStatement\n if (id == R.id.action_save) {\n saveSp();\n return true;\n }\n\n return super.onOptionsItemSelected(item);\n }\n\n\n}",
"public interface IPresenter {\n void doClear();\n\n}",
"public class TreeholeComment {\n\n int likeCount;\n\n int unlikeCount;\n\n List<Comment> comments;\n\n public int getLikeCount() {\n return likeCount;\n }\n\n public void setLikeCount(int likeCount) {\n this.likeCount = likeCount;\n }\n\n public int getUnlikeCount() {\n return unlikeCount;\n }\n\n public void setUnlikeCount(int unlikeCount) {\n this.unlikeCount = unlikeCount;\n }\n\n public List<Comment> getComments() {\n return comments;\n }\n\n public void setComments(List<Comment> comments) {\n this.comments = comments;\n }\n\n @Override\n public String toString() {\n return \"TreeholeComment{\" +\n \"likeCount=\" + likeCount +\n \", unlikeCount=\" + unlikeCount +\n \", comments=\" + comments +\n '}';\n }\n\n public static class Comment {\n String uniquecode;\n String name;\n String dt;\n String comment;\n String imei;\n\n public String getUniquecode() {\n return uniquecode;\n }\n\n public void setUniquecode(String uniquecode) {\n this.uniquecode = uniquecode;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getDt() {\n return dt;\n }\n\n public void setDt(String dt) {\n this.dt = dt;\n }\n\n public String getComment() {\n return comment;\n }\n\n public void setComment(String comment) {\n this.comment = comment;\n }\n\n public String getImei() {\n return imei;\n }\n\n public void setImei(String imei) {\n this.imei = imei;\n }\n\n @Override\n public String toString() {\n return \"Comment{\" +\n \"uniquecode='\" + uniquecode + '\\'' +\n \", name='\" + name + '\\'' +\n \", dt='\" + dt + '\\'' +\n \", comment='\" + comment + '\\'' +\n \", imei='\" + imei + '\\'' +\n '}';\n }\n }\n}",
"public class TreeholeModel {\n\n private static final String BASE_URL = SupportModelUtils.HOST + \"treehole/\";\n\n\n private TreeholeService mService = new Retrofit.Builder()\n .baseUrl(BASE_URL)\n .addConverterFactory(GsonConverterFactory.create())\n .addCallAdapterFactory(RxJavaCallAdapterFactory.create())\n .build()\n .create(TreeholeService.class);\n\n\n public static final MediaType IMAGE\n = MediaType.parse(\"image/*\");\n\n public void addRecord(TreeholeInfo info, Subscriber<ResponseBody> subscriber) {\n SupportModelUtils.toSubscribe(mService.addRecord(info), subscriber);\n\n }\n\n public void addRecordWithPhoto(File file, TreeholeInfo info, Subscriber<ResponseBody> subscriber) {\n SupportModelUtils.toSubscribe(mService.addRecordWithPhoto(RequestBody.create(IMAGE, file), info), subscriber);\n }\n\n public void getNewerData(final Subscriber<List<TreeholeInfo>> subscriber) {\n Observable observable = Observable.create(new Observable.OnSubscribe<String>() {\n @Override\n public void call(Subscriber<? super String> subscriber) {\n subscriber.onNext(TreeholeDao.getLatestDatetime());\n }\n }).flatMap(new Func1<String, Observable<List<TreeholeInfo>>>() {\n @Override\n public Observable<List<TreeholeInfo>> call(String s) {\n return mService.getNewerData(s);\n }\n }).doOnNext(new Action1<List<TreeholeInfo>>() {\n @Override\n public void call(List<TreeholeInfo> treeholeInfos) {\n TreeholeDao.save(treeholeInfos);\n }\n });\n SupportModelUtils.toSubscribe(observable, subscriber);\n }\n\n public void loadFromDb(Subscriber<List<TreeholeLocalInfo>> subscriber) {\n Observable<List<TreeholeLocalInfo>> observable = Observable.create(new Observable.OnSubscribe<List<TreeholeLocalInfo>>() {\n @Override\n public void call(Subscriber<? super List<TreeholeLocalInfo>> subscriber) {\n List<TreeholeLocalInfo> list = TreeholeDao.getAll();\n subscriber.onNext(list);\n }\n\n });\n SupportModelUtils.toSubscribe(observable, subscriber);\n }\n\n public void doLikeJob(final String uniquecode, String imei, final boolean isLike) {\n String param;\n if (isLike) {\n param = \"true\";\n } else {\n param = \"false\";\n }\n mService.doLikeJob(uniquecode, imei, param)\n .subscribeOn(Schedulers.io())\n .subscribe(new Subscriber<ResponseBody>() {\n @Override\n public void onCompleted() {\n\n }\n\n @Override\n public void onError(Throwable e) {\n // 失败不进行任何操作,不会更新数据库,用户下次进来还是原来状态,\n // 不能使用Action1类型,否则Exception thrown on Scheduler.Worker thread. Add `onError` handling.\n }\n\n @Override\n public void onNext(ResponseBody responseBody) {\n if (isLike) {\n TreeholeDao.updateLikeOfComment(uniquecode, TreeholeDao.TRUE);\n } else {\n TreeholeDao.updateLikeOfComment(uniquecode, TreeholeDao.FALSE);\n }\n }\n });\n }\n\n public void doUnlikeJob(final String uniquecode, String imei, final boolean isUnlike) {\n String param;\n if (isUnlike) {\n param = \"true\";\n } else {\n param = \"false\";\n }\n mService.doUnlikeJob(uniquecode, imei, param)\n .subscribeOn(Schedulers.io())\n .subscribe(new Subscriber<ResponseBody>() {\n @Override\n public void onCompleted() {\n\n }\n\n @Override\n public void onError(Throwable e) {\n\n }\n\n @Override\n public void onNext(ResponseBody responseBody) {\n if (isUnlike) {\n TreeholeDao.updateUnlikeOfComment(uniquecode, TreeholeDao.TRUE);\n } else {\n TreeholeDao.updateUnlikeOfComment(uniquecode, TreeholeDao.FALSE);\n }\n }\n });\n }\n\n public void sendComment(TreeholeComment.Comment comment, Subscriber<ResponseBody> subscriber) {\n SupportModelUtils.toSubscribe(mService.sendComment(comment), subscriber);\n }\n\n public void doLoadingComments(String uniquecode, Subscriber<TreeholeComment> subscriber) {\n SupportModelUtils.toSubscribe(mService.loadComments(uniquecode), subscriber);\n }\n}",
"public interface ICommentView {\n void sendingCommentProgressDialog();\n\n void dismissProgressDialog();\n\n void netError();\n\n void loadingCommentProgressDialog();\n\n void refreshLikeAndUnlike(TreeholeComment comment);\n\n void succeededInSending();\n\n void noComment();\n\n void showComments(List<TreeholeComment.Comment> comment);\n}",
"public class AppInfoUtils {\n public static String getAppName() {\n return MyApplication.context.getString(R.string.app_name);\n }\n\n public static String getImei() {\n TelephonyManager tm = ((TelephonyManager) MyApplication.context.getSystemService(Activity.TELEPHONY_SERVICE));\n String imei = tm.getDeviceId();\n if (imei != null && !imei.isEmpty()) {\n return imei;\n }\n return \"\";\n }\n\n /**\n * 产生唯一订单号\n * @return\n */\n public static String getUniqueCode() {\n String imei = AppInfoUtils.getImei();\n Date date = new Date();\n String unique = imei + date.hashCode();\n return String.valueOf(unique.hashCode());\n }\n}",
"public class SPUtils {\n\n private static SharedPreferences sharedPreferences = MyApplication.context.getSharedPreferences(AppInfoUtils.getAppName(), Context.MODE_PRIVATE);\n private static SharedPreferences.Editor editor = sharedPreferences.edit();\n\n public static void save(String key, boolean value) {\n editor.putBoolean(key, value);\n editor.commit();\n }\n\n public static void save(String key, String value) {\n editor.putString(key, value);\n editor.commit();\n }\n\n public static void save(String[] keys, String[] values) {\n for (int i = 0; i < keys.length; i++) {\n editor.putString(keys[i], values[i]);\n }\n editor.commit();\n }\n\n public static String getString(String key) {\n return sharedPreferences.getString(key, \"\");\n }\n\n public static boolean getBoolean(String key) {\n return sharedPreferences.getBoolean(key, false);\n }\n}"
] | import com.leelit.stuer.LoginActivity;
import com.leelit.stuer.base_presenter.IPresenter;
import com.leelit.stuer.bean.TreeholeComment;
import com.leelit.stuer.module_treehole.model.TreeholeModel;
import com.leelit.stuer.module_treehole.viewinterface.ICommentView;
import com.leelit.stuer.utils.AppInfoUtils;
import com.leelit.stuer.utils.SPUtils;
import java.util.Collections;
import java.util.List;
import okhttp3.ResponseBody;
import rx.Subscriber; | package com.leelit.stuer.module_treehole.presenter;
/**
* Created by Leelit on 2016/3/27.
*/
public class CommentPresenter implements IPresenter{
private TreeholeModel mModel = new TreeholeModel();
private ICommentView mView;
private Subscriber<ResponseBody> mSubscriber1;
private Subscriber<TreeholeComment> mSubscriber2;
public CommentPresenter(ICommentView view) {
mView = view;
}
public void doLikeJob(String uniquecode, boolean isLike) {
mModel.doLikeJob(uniquecode, AppInfoUtils.getImei(), isLike);
}
public void doUnlikeJob(String uniquecode, boolean isUnlike) {
mModel.doUnlikeJob(uniquecode, AppInfoUtils.getImei(), isUnlike);
}
public void doSendComment(String uniquecode, String commentText) {
TreeholeComment.Comment comment = new TreeholeComment.Comment();
comment.setUniquecode(uniquecode); | comment.setName(SPUtils.getString(LoginActivity.INFOS[0])); | 6 |
kinnla/eniac | src/eniac/menu/action/ZoomFitWidth.java | [
"public enum EType {\n\n\t/**\n\t * A configuration of 3 units\n\t */\n\tCONFIGURATION_3,\n\n\t/**\n\t * A configuration of 4 units\n\t */\n\tCONFIGURATION_4,\n\n\t/**\n\t * A configuration of 8 units\n\t */\n\tCONFIGURATION_8,\n\n\t/**\n\t * A configuration of 12 units\n\t */\n\tCONFIGURATION_12,\n\n\t/**\n\t * A configuration of 16 units\n\t */\n\tCONFIGURATION_16,\n\n\t/**\n\t * A configuration of 20 units\n\t */\n\tCONFIGURATION_20,\n\n\t/**\n\t * the accumulator\n\t */\n\tACCUMULATOR_UNIT,\n\n\t/**\n\t * the cycling unit\n\t */\n\tCYCLING_UNIT,\n\n\t/**\n\t * the initiating unit\n\t */\n\tINITIATING_UNIT,\n\n\t/**\n\t * the 1st constant transmitter unit\n\t */\n\tCONSTANT_TRANSMITTER_1_UNIT,\n\n\t/**\n\t * the 2nd constant transmitter unit\n\t */\n\tCONSTANT_TRANSMITTER_2_UNIT,\n\n\t/**\n\t * an upper trunk which is 2 units width\n\t */\n\tUPPER_TRUNK_2,\n\n\t/**\n\t * an upper trunk which is 4 units width\n\t */\n\tUPPER_TRUNK_4,\n\n\t/**\n\t * a lower trunk which is 3 units width\n\t */\n\tLOWER_TRUNK_3,\n\n\t/**\n\t * a lower trunk which is 4 units width\n\t */\n\tLOWER_TRUNK_4,\n\n\t/**\n\t * a tray (part of a trunk) which is 2 units width\n\t */\n\tTRAY_2,\n\n\t/**\n\t * a tray (part of a trunk) which is 3 units width\n\t */\n\tTRAY_3,\n\n\t/**\n\t * a tray (part of a trunk) which is 4 units width\n\t */\n\tTRAY_4,\n\n\t/**\n\t * a blinken lights of an accumulator\n\t */\n\tBLINKEN_LIGHTS,\n\n\t/**\n\t * the heaters switch of an accumulator (may display the accumulator icon)\n\t */\n\tACCU_HEATERS,\n\n\t/**\n\t * a standard heaters switch\n\t */\n\tHEATERS,\n\n\t/**\n\t * a heaters switch that displays 0 - 1\n\t */\n\tHEATERS_01,\n\n\t/**\n\t * the step button of the cycling unit\n\t */\n\tSTEP_BUTTON,\n\n\t/**\n\t * the go button of the initiating unit\n\t */\n\tGO_BUTTON,\n\n\t/**\n\t * the clear button of the initiating unit\n\t */\n\tCLEAR_BUTTON,\n\n\t/**\n\t * the clear button for the cycle counter\n\t */\n\tCYCLE_COUNTER_CLEAR,\n\n\t/**\n\t * the iteration switch of the cycling unit\n\t */\n\tITERATION_SWITCH,\n\n\t/**\n\t * the significant figures switch of an accumulator\n\t */\n\tSIGNIFICIANT_FIGURES_SWITCH,\n\n\t/**\n\t * the operations switch of an accumulator\n\t */\n\tOPERATION_SWITCH,\n\n\t/**\n\t * the repeat switch of an accumulator\n\t */\n\tREPEAT_SWITCH,\n\n\t/**\n\t * a cipher of the cycle counter at the cycling unit\n\t */\n\tCIPHER,\n\n\t/**\n\t * a digit of the blinken lights\n\t */\n\tBLINKEN_NUMBER_SWITCH,\n\n\t/**\n\t * the sign of the blinken lights\n\t */\n\tBLINKEN_SIGN_SWITCH,\n\n\t/**\n\t * the cycling lights -- display the pulse\n\t */\n\tCYCLING_LIGHTS,\n\n\t/**\n\t * the go lights of the initiating unit\n\t */\n\tGO_LIGHTS,\n\n\t/**\n\t * a digit connector (10 digits + sign + carryover)\n\t */\n\tDIGIT_CONNECTOR,\n\n\t/**\n\t * a program connector (1 pulse)\n\t */\n\tPROGRAM_CONNECTOR,\n\n\t/**\n\t * an inter-connector (can connect 2 accumulator units)\n\t */\n\tINTER_CONNECTOR,\n\n\t/**\n\t * a digit connector in horizontal layout (e.g. at the edges of a tray)\n\t */\n\tDIGIT_CONNECTOR_CROSS,\n\n\t/**\n\t * a pair of program connectors (in + out)\n\t */\n\tPROGRAM_CONNECTOR_PAIR,\n\n\t/**\n\t * a cover, without functionality (accumulator, between heaters and\n\t * significant figures switch)\n\t */\n\tBLEND_8,\n\n\t/**\n\t * a cover, without functionality (accumulator, above the repeat switches)\n\t */\n\tBLEND_16,\n\n\t/**\n\t * a cover, without functionality (constant transmitter panel)\n\t */\n\tBLEND_A_10,\n\n\t/**\n\t * the symbol for the cycling unit\n\t */\n\tCYCLING_SYMBOL,\n\n\t/**\n\t * the symbol for the initiating unit\n\t */\n\tINITIATING_SYMBOL,\n\n\t/**\n\t * the symbol for the constant transmitter unit 1\n\t */\n\tCONSTANT_TRANSMITTER_1_SYMBOL,\n\n\t/**\n\t * the symbol for the constant transmitter unit 2\n\t */\n\tCONSTANT_TRANSMITTER_2_SYMBOL,\n\n\t/**\n\t * the constant selector switch for A+B\n\t */\n\tCONSTANT_SELECTOR_SWITCH_AB,\n\n\t/**\n\t * the constant selector switch for C+D\n\t */\n\tCONSTANT_SELECTOR_SWITCH_CD,\n\n\t/**\n\t * the constant selector switch for E+F\n\t */\n\tCONSTANT_SELECTOR_SWITCH_EF,\n\n\t/**\n\t * the constant selector switch for G+H\n\t */\n\tCONSTANT_SELECTOR_SWITCH_GH,\n\n\t/**\n\t * the constant selector switch for J+K\n\t */\n\tCONSTANT_SELECTOR_SWITCH_JK,\n\n\t/**\n\t * a number switch at the constant transmitter unit 2\n\t */\n\tCONSTANT_SWITCH,\n\n\t/**\n\t * the image displayed at the initiating unit\n\t */\n\tINITIATING_IMAGE,\n\n\t/**\n\t * the frequency slider (cycling unit)\n\t */\n\tFREQUENCY_SLIDER,\n\n\t/**\n\t * the benchmark, displaying the number of addition cycles per second\n\t */\n\tBENCHMARK,\n\n\t/**\n\t * the addition cycle counter\n\t */\n\tCYCLE_COUNTER,\n\n\t/**\n\t * image to be used in the overview panel, as marker for the currently\n\t * visible area\n\t */\n\tXOR_IMAGE,\n\n\t/**\n\t * toggle switch for the constant transmitter 2, row J, left\n\t */\n\tCONSTANT_SIGN_TOGGLE_JL,\n\n\t/**\n\t * toggle switch for the constant transmitter 2, row J, right\n\t */\n\tCONSTANT_SIGN_TOGGLE_JR,\n\n\t/**\n\t * toggle switch for the constant transmitter 2, row K, left\n\t */\n\tCONSTANT_SIGN_TOGGLE_KL,\n\n\t/**\n\t * toggle switch for the constant transmitter 2, row K, right\n\t */\n\tCONSTANT_SIGN_TOGGLE_KR,\n\n\t/**\n\t * the numbers display at the constant transmitter 2\n\t */\n\tCONSTANT_2_LIGHTS,\n\n\t/**\n\t * a decimal cipher of the constant transmitter 2 lights\n\t */\n\tCONSTANT_BLINKEN_CIPHER,\n\n\t/**\n\t * the +/- sign for a number at the constant transmitter 2 lights\n\t */\n\tCONSTANT_BLINKEN_SIGN,\n\n\t/**\n\t * a cipher displayed at constant transmitter 1, to be shown during a\n\t * transmission\n\t */\n\tCONSTANT_TRANSMITTION_CIPHER,\n\n\t/**\n\t * a =/- sign displayed at constant transmitter 1, to be shown during a\n\t * transmission\n\t */\n\tCONSTANT_TRANSMITTION_SIGN,\n\n\t/**\n\t * the lights at constant transmitter 1, will display number and sign during\n\t * a transmission\n\t */\n\tCONSTANT_TRANSMITTION_LIGHTS;\n\n\tpublic enum Tag {\n\t\tNAME, TYPE, MODEL, VIEW, CODE, CODES, VALUE;\n\t}\n\n\tprivate String _edataClass;\n\n\tprivate String _epanelClass;\n\n\tprivate EType.Tag _codeName;\n\n\tprivate String[] _codes;\n\n\tprivate Descriptor[] _descriptors;\n\n\tprivate Grid[] _gridCache;\n\n\tprivate EType() {\n\t\t_gridCache = new Grid[StringConverter.toInt(EProperties.getInstance().getProperty(\"GRID_CACHE_SIZE\"))];\n\t}\n\n\t// ========================== getters and setters\n\t// ===========================\n\n\tpublic void setCodes(String[] codes) {\n\t\t_codes = codes;\n\t}\n\n\tpublic String[] getCodes() {\n\t\treturn _codes;\n\t}\n\n\tpublic void setCodeName(EType.Tag codeName) {\n\t\t_codeName = codeName;\n\t}\n\n\tpublic EType.Tag getCodeName() {\n\t\treturn _codeName;\n\t}\n\n\tpublic void setEDataClass(String edataClass) {\n\t\t_edataClass = edataClass;\n\t}\n\n\tpublic void setEPanelClass(String epanelClass) {\n\t\t_epanelClass = epanelClass;\n\t}\n\n\tpublic void setDescriptors(Descriptor[] descriptors) {\n\t\t// empty grid cache\n\t\tArrays.fill(_gridCache, null);\n\t\t_descriptors = descriptors;\n\t}\n\n\t// ================================ methods\n\t// =================================\n\n\tpublic EData makeEData() throws InstantiationException, ClassNotFoundException, IllegalAccessException {\n\n\t\tEData edata = (EData) Class.forName(_edataClass).newInstance();\n\t\tedata.setType(this);\n\t\treturn edata;\n\t}\n\n\tpublic EPanel makeEPanel() {\n\t\ttry {\n\t\t\treturn (EPanel) Class.forName(_epanelClass).newInstance();\n\t\t} catch (Exception e) {\n\t\t\t// System.out.println(_epanelClass);\n\t\t\te.printStackTrace();\n\t\t}\n\t\treturn null;\n\t}\n\n\tpublic Descriptor getDescriptor(int lod) {\n\t\treturn _descriptors[lod];\n\t}\n\n\tpublic Grid getGrid(int width, int height, int lod) {\n\t\tint index = computeIndex(width, height);\n\t\tif (_gridCache[index] == null || _gridCache[index].width != width || _gridCache[index].height != height) {\n\n\t\t\t_gridCache[index] = getDescriptor(lod).makeGrid(width, height);\n\t\t}\n\t\treturn _gridCache[index];\n\t}\n\n\tprivate int computeIndex(int width, int height) {\n\t\treturn (width + height) % _gridCache.length;\n\t}\n}",
"public class ConfigPanel extends ParentPanel implements Scrollable, StatusListener {\n\n\t/*\n\t * ============================== fields ===================================\n\t */\n\n\t// cableManager tracking all cables\n\tprivate CableManager _cableManager = new CableManager();\n\n\t// current lod for detaied view\n\tprivate int _lod;\n\n\t// temporary Point for computation speed up\n\tprivate Point _p = new Point();\n\n\t/*\n\t * =============================== lifecycle ===============================\n\t */\n\n\tpublic void init() {\n\n\t\t// super call for initiating the guiGarten and adding children\n\t\tsuper.init();\n\n\t\t// init cables\n\t\t_cableManager.init();\n\n\t\t// add as propertychangelistener to status to receive simulation time\n\t\t// updates\n\t\tStatus.HIGHLIGHT_PULSE.addListener(this);\n\t\tStatus.ZOOMED_HEIGHT.addListener(this);\n\t}\n\n\tpublic void dispose() {\n\t\tsuper.dispose();\n\t\tStatus.HIGHLIGHT_PULSE.removeListener(this);\n\t\tStatus.ZOOMED_HEIGHT.removeListener(this);\n\t\tremoveAll();\n\t\t_cableManager = null;\n\t}\n\n\t/*\n\t * ============================== methods ==================================\n\t */\n\n\tpublic int getLod() {\n\t\treturn _lod;\n\t}\n\n\tpublic CableManager getCableManager() {\n\t\treturn _cableManager;\n\t}\n\n\t/*\n\t * =========================== gui methods =================================\n\t */\n\n\t/**\n\t * Computes the preferred size of this configPanel. The preferred width is\n\t * always a multiple of the numberOfUnits. So every unit will have the same\n\t * width.\n\t */\n\tpublic Dimension getPreferredSize() {\n\n\t\t// get current configuration height\n\t\tint height = (int) Status.ZOOMED_HEIGHT.getValue();\n\n\t\t// set lod\n\t\tSkin skin = (Skin) Status.SKIN.getValue();\n\t\t_lod = skin.getLodByHeight(height);\n\n\t\t// get descriptor for this configuration\n\t\tEType type = _data.getType();\n\t\tint lod = skin.getLodByHeight(height);\n\t\tDescriptor descriptor = type.getDescriptor(lod);\n\n\t\t// if no descriptor, return a default dimension\n\t\tif (descriptor == null) {\n\t\t\treturn new Dimension(0, 0);\n\t\t}\n\n\t\t// otherwise compute wanted width by the rule of three and return\n\t\tint width = height * descriptor.getWidth() / descriptor.getHeight();\n\t\treturn new Dimension(width, height);\n\t}\n\n\tpublic void doLayout() {\n\n\t\t// compute bounds for all children\n\t\tRectangle[] rectangles = getRectangles(_lod, getWidth(), getHeight());\n\n\t\t// set bounds for all of the children\n\t\tEPanel[] children = getChildren();\n\t\tfor (int i = 0; i < children.length; ++i) {\n\t\t\tRectangle r = rectangles[i];\n\t\t\tchildren[i].setBounds(r.x, r.y, r.width, r.height);\n\t\t}\n\t}\n\n\tpublic void paintAsIcon(Graphics g, int x, int y, int w, int h, int lod) {\n\n\t\t// paint background and children, then paint cables\n\t\tsuper.paintAsIcon(g, x, y, w, h, lod);\n\t\t_cableManager.paintOnBufferedImage(g, lod);\n\t}\n\n\tpublic void paintChildren(Graphics g) {\n\n\t\t// paint children by supercall, then paint cables\n\t\tsuper.paintChildren(g);\n\t\t_cableManager.paintOnConfigPanel(g, _lod);\n\t}\n\n\t/*\n\t * ========================== scrollable methods ===========================\n\t */\n\n\tpublic boolean getScrollableTracksViewportHeight() {\n\t\treturn false;\n\t}\n\n\tpublic boolean getScrollableTracksViewportWidth() {\n\t\treturn false;\n\t}\n\n\tpublic Dimension getPreferredScrollableViewportSize() {\n\t\treturn getPreferredSize();\n\t}\n\n\tpublic int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {\n\t\treturn 30;\n\t}\n\n\tpublic int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) {\n\t\treturn 30;\n\t}\n\n\t/*\n\t * ============================ event listening ============================\n\t */\n\n\t@Override\n\tpublic void statusChanged(Status status, Object newValue) {\n\t\tif (status == Status.HIGHLIGHT_PULSE) {\n\t\t\t// highlight mode changed by user action.\n\t\t\t// Because this won't happen too often don't be cheap:\n\t\t\t// just repaint.\n\t\t\tupdate(_data, EData.REPAINT);\n\t\t}\n\t\telse if (status == Status.ZOOMED_HEIGHT) {\n\n\t\t\t// zoom changed.\n\t\t\t// init with default values\n\t\t\tdouble scrollPercentageX = 0.5;\n\t\t\tdouble scrollPercentageY = 0.5;\n\n\t\t\t// get values\n\t\t\tDimension preferredSize = getPreferredSize();\n\t\t\tJViewport viewPort = ((JViewport) getParent());\n\t\t\tDimension viewPortSize = viewPort.getSize();\n\t\t\tPoint currentPosition = viewPort.getViewPosition();\n\n\t\t\t// check, if preferred width > viewport width\n\t\t\tint widthDiff = preferredSize.width - viewPortSize.width;\n\t\t\tif (widthDiff > 0) {\n\t\t\t\t// compute relative scroll position x\n\t\t\t\tscrollPercentageX = currentPosition.x / (double) (getSize().width - viewPortSize.width);\n\t\t\t}\n\n\t\t\t// check, if preferred height > viewport height\n\t\t\tint heightDiff = preferredSize.height - viewPortSize.height;\n\t\t\tif (heightDiff > 0) {\n\t\t\t\t// compute relative scroll position y\n\t\t\t\tscrollPercentageY = currentPosition.y / (double) (getSize().height - viewPortSize.height);\n\t\t\t}\n\n\t\t\t// default _p to current position\n\t\t\t_p = getLocation();\n\n\t\t\t// check, if need to update x location\n\t\t\tif (widthDiff > 0) {\n\t\t\t\t// we cannot see the complete configuration in x direction\n\t\t\t\t_p.x = (int) (widthDiff * scrollPercentageX);\n\t\t\t}\n\n\t\t\t// check, if need to update x location\n\t\t\tif (heightDiff > 0) {\n\t\t\t\t// we cannot see the complete configuration in x direction\n\t\t\t\t_p.y = (int) (heightDiff * scrollPercentageY);\n\t\t\t}\n\n\t\t\tsetSize(preferredSize);\n\t\t\tviewPort.setViewPosition(_p);\n\t\t\trevalidate();\n\t\t}\n\t}\n\n\t/*\n\t * ========================== static methods ===============================\n\t */\n\n\tpublic static float heightToPercentage() {\n\t\t// determine zoom and lod\n\t\tint basicHeight = StringConverter.toInt(EProperties.getInstance().getProperty(\"BASIC_CONFIGURATION_HEIGHT\"));\n\t\tint zoomedHeight = (int) Status.ZOOMED_HEIGHT.getValue();\n\t\treturn (float) zoomedHeight / (float) basicHeight;\n\t}\n}",
"public class Descriptor {\n\n\t/**\n\t * Enumeration of all keys that are available in a descriptor\n\t * \n\t * @author till\n\t * \n\t * TODO\n\t */\n\tpublic enum Key {\n\n\t\t/**\n\t\t * a background image\n\t\t */\n\t\tBACK_IMAGE,\n\n\t\t/**\n\t\t * an array of background images, as used by switches\n\t\t */\n\t\tBACK_IMAGE_ARRAY,\n\n\t\t/**\n\t\t * a foreground image\n\t\t */\n\t\tFORE_IMAGE,\n\n\t\t/**\n\t\t * an array of foreground images, as used by switchAndFlag\n\t\t */\n\t\tFORE_IMAGE_ARRAY,\n\n\t\t/**\n\t\t * The color, given as 6-digit rgb hex string\n\t\t */\n\t\tCOLOR,\n\n\t\t/**\n\t\t * A rectangle defining the bounds of the epanel\n\t\t */\n\t\tRECTANGLE,\n\n\t\t/**\n\t\t * An array of rectangles, as for the light bulbs in blinkenlights\n\t\t */\n\t\tRECTANGLE_ARRAY,\n\n\t\t/**\n\t\t * An array of polygons\n\t\t */\n\t\tAREAS,\n\n\t\t/**\n\t\t * The controller class, used by switch\n\t\t */\n\t\tACTIONATOR,\n\n\t\t/**\n\t\t * the color of the cable, as defined by the connectors\n\t\t */\n\t\tCABLE_COLOR,\n\n\t\t/**\n\t\t * the cable color in pulse highlighting mode\n\t\t */\n\t\tCABLE_COLOR_HIGHLIGHT,\n\n\t\t/**\n\t\t * the cable diameter in pixels\n\t\t */\n\t\tCABLE_PIXELS,\n\n\t\t/**\n\t\t * image for an unplugged connector\n\t\t */\n\t\tUNPLUGGED,\n\n\t\t/**\n\t\t * image for a plugged connector\n\t\t */\n\t\tPLUGGED,\n\n\t\t/**\n\t\t * image for a connector with a loadbox\n\t\t */\n\t\tLOADBOX,\n\n\t\t/**\n\t\t * the vertical lines of the grid\n\t\t */\n\t\tGRID_X,\n\n\t\t/**\n\t\t * the horizontal lines of the grid\n\t\t */\n\t\tGRID_Y,\n\n\t\t/**\n\t\t * the width of a slider (distance between min and max value)\n\t\t */\n\t\tX,\n\t}\n\n\tpublic enum Fill {\n\t\tNONE, BOTH, HORIZONTAL, VERTICAL;\n\t}\n\n\tprivate int _width;\n\n\tprivate int _height;\n\n\tprivate Fill _fill = Fill.NONE;\n\n\tprivate EnumMap<Key, Object> _map;\n\n\t// ============================= lifecycle\n\t// ==================================\n\n\tpublic Descriptor() {\n\t\t_map = new EnumMap<>(Key.class);\n\t}\n\n\t// ============================= getters and setters\n\t// ========================\n\n\tpublic void setWidth(int width) {\n\t\t_width = width;\n\t}\n\n\tpublic int getWidth() {\n\t\treturn _width;\n\t}\n\n\tpublic void setHeight(int height) {\n\t\t_height = height;\n\t}\n\n\tpublic int getHeight() {\n\t\treturn _height;\n\t}\n\n\tpublic void setFill(Fill fill) {\n\t\t_fill = fill;\n\t}\n\n\tpublic Fill getFill() {\n\t\treturn _fill;\n\t}\n\n\t// =============================== methods\n\t// ==================================\n\n\tpublic Object get(Descriptor.Key key) {\n\t\treturn _map.get(key);\n\t}\n\n\tpublic void put(Descriptor.Key key, Object value) {\n\t\t_map.put(key, value);\n\t}\n\n\tpublic Grid makeGrid(int width, int height) {\n\n\t\t// get gridx. if gridx is null, return a simple grid.\n\t\tint[] _gridX = (int[]) get(Key.GRID_X);\n\t\tif (_gridX == null) {\n\t\t\treturn new Grid(width, height);\n\t\t}\n\n\t\t// otherwise get gridy, too. Create ParentGrid\n\t\tint[] _gridY = (int[]) get(Key.GRID_Y);\n\t\tParentGrid grid = new ParentGrid(width, height);\n\n\t\t// compute zoom\n\t\tgrid.zoomX = (float) width / (float) _width;\n\t\tgrid.zoomY = (float) height / (float) _height;\n\n\t\t// create arrays\n\t\tgrid.xValues = new int[_gridX.length];\n\t\tgrid.yValues = new int[_gridY.length];\n\n\t\t// copy grid numbers\n\t\tfor (int i = 0; i < grid.xValues.length; ++i) {\n\t\t\tgrid.xValues[i] = _gridX[i] * width / _width;\n\t\t}\n\t\tfor (int i = 0; i < grid.yValues.length; ++i) {\n\t\t\tgrid.yValues[i] = _gridY[i] * height / _height;\n\t\t}\n\n\t\t// return grid.\n\t\treturn grid;\n\t}\n}",
"public class Skin {\n\n\t/**\n\t * enumeration of all tags in the skin xml.\n\t */\n\tpublic enum Tag {\n\n\t\t/**\n\t\t * the root element\n\t\t */\n\t\tSKIN,\n\n\t\t/**\n\t\t * the level of detail (should be 2 elements in a skin)\n\t\t */\n\t\tLOD,\n\n\t\t/**\n\t\t * a descriptor, containing all attributes for an edata\n\t\t */\n\t\tDESCRIPTOR,\n\n\t\t/**\n\t\t * a single element in a descriptor\n\t\t */\n\t\tSINGLE,\n\n\t\t/**\n\t\t * an array of elements in a descriptor\n\t\t */\n\t\tARRAY,\n\n\t\t/**\n\t\t * an entry in an array of elements\n\t\t */\n\t\tENTRY,\n\n\t\t/**\n\t\t * a point of a polygon entry\n\t\t */\n\t\tPOINT,\n\t}\n\n\t/**\n\t * enumeration of all attributes in the skin xml\n\t */\n\tpublic enum Attribute {\n\n\t\t/**\n\t\t * the minimum height for an lod in pixel\n\t\t */\n\t\tMIN_HEIGHT,\n\n\t\t/**\n\t\t * the maximum height for an lod in pixel\n\t\t */\n\t\tMAX_HEIGHT,\n\n\t\t/**\n\t\t * the type of a descriptor (reference to etype)\n\t\t */\n\t\tTYPE,\n\n\t\t/**\n\t\t * the width of a descriptor (default width of the epanel)\n\t\t */\n\t\tWIDTH,\n\n\t\t/**\n\t\t * the height of a descriptor (default height of the epanel)\n\t\t */\n\t\tHEIGHT,\n\n\t\t/**\n\t\t * the fill mode of a descriptor\n\t\t */\n\t\tFILL,\n\n\t\t/**\n\t\t * the creator class name of an element in a descriptor\n\t\t */\n\t\tCLASS,\n\n\t\t/**\n\t\t * the descriptor key for this element\n\t\t */\n\t\tNAME,\n\n\t\t/**\n\t\t * the x coordinate of a polygon point\n\t\t */\n\t\tX,\n\n\t\t/**\n\t\t * the y coordinate of a polygon point\n\t\t */\n\t\tY,\n\t}\n\n\t// default image and its static initialization\n\tpublic static final Image DEFAULT_IMAGE;\n\tstatic {\n\t\tDEFAULT_IMAGE = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);\n\t\tGraphics g = DEFAULT_IMAGE.getGraphics();\n\t\tg.setColor(StringConverter.toColor(EProperties.getInstance().getProperty(\"DEFAULT_COLOR\")));\n\t\tg.drawLine(0, 0, 0, 0);\n\t}\n\n\t// ============================== fields\n\t// ====================================\n\n\t// array of lods\n\tprivate int[] _minHeight;\n\n\tprivate int[] _maxHeight;\n\n\t// array od zoom steps\n\tint[] _zoomSteps;\n\n\t// proxy to the current skin\n\tprivate Proxy _proxy;\n\n\t// ============================== lifecycle\n\t// =================================\n\n\t// private constructor for instantiating singleton object\n\tpublic Skin(Proxy proxy) {\n\t\t_proxy = proxy;\n\n\t\t// init lods\n\t\tString s = _proxy.get(Proxy.Tag.NUMBER_OF_LODS);\n\t\tint numberOfLods = StringConverter.toInt(s);\n\t\t_minHeight = new int[numberOfLods];\n\t\t_maxHeight = new int[numberOfLods];\n\n\t\t// init zoom steps\n\t\ts = _proxy.get(Proxy.Tag.ZOOM_STEPS);\n\t\t_zoomSteps = StringConverter.toIntArray(s);\n\t}\n\n\t// ============================ methods\n\t// =====================================\n\n\tpublic Proxy getProxy() {\n\t\treturn _proxy;\n\t}\n\n\tpublic int getLodByHeight(int height) {\n\t\t// recurse on all levels of detail and return fitting zoom\n\t\tfor (int i = 0; i < _minHeight.length; ++i) {\n\t\t\tif (_minHeight[i] <= height && height <= _maxHeight[i]) {\n\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\t\t// no appropriate lod found.\n\t\treturn -1;\n\t}\n\n\tpublic void setLod(int lod, int minHeight, int maxHeight) {\n\t\t_minHeight[lod] = minHeight;\n\t\t_maxHeight[lod] = maxHeight;\n\t}\n\n\tpublic int[] getZoomSteps() {\n\t\treturn _zoomSteps;\n\t}\n}",
"public enum Status {\n\n\t/**\n\t * the current lifecycle state\n\t */\n\tLIFECYCLE,\n\n\t/**\n\t * the active configuration or null\n\t */\n\tCONFIGURATION,\n\n\t/**\n\t * flag indicating, whether the overview window is shown or not\n\t */\n\tSHOW_OVERVIEW,\n\n\t/**\n\t * the default height of the configuration panel\n\t */\n\tBASIC_CONFIGURATION_HEIGHT,\n\n\t/**\n\t * the height of the configuration panel\n\t */\n\tZOOMED_HEIGHT,\n\n\t/**\n\t * flag indicating, whether the overview window is shown or not\n\t */\n\tSHOW_LOG,\n\n\t/**\n\t * the currently loaded skin (currently only buttercream) or null\n\t */\n\tSKIN,\n\n\t/**\n\t * the currently loaded language\n\t */\n\tLANGUAGE,\n\n\t/**\n\t * flag indicating, whether the pulses shall be highlighted or not\n\t */\n\tHIGHLIGHT_PULSE,\n\n\t/**\n\t * the current simulation time\n\t */\n\tSIMULATION_TIME;\n\n\t/*\n\t * ============================= fields ==================================\n\t */\n\n\t// the value for this status key\n\tprivate Object _value;\n\n\tprivate LinkedList<StatusListener> _listeners = new LinkedList<>();\n\n\t/*\n\t * ========================= singleton stuff =======================\n\t */\n\n\tpublic static void initValues() {\n\t\tCONFIGURATION._value = null;\n\t\tSHOW_OVERVIEW._value = StringConverter.toBoolean(EProperties.getInstance().getProperty(SHOW_OVERVIEW));\n\t\tZOOMED_HEIGHT._value = StringConverter.toInt(EProperties.getInstance().getProperty(BASIC_CONFIGURATION_HEIGHT));\n\t\tSHOW_LOG._value = StringConverter.toBoolean(EProperties.getInstance().getProperty(SHOW_LOG));\n\t\tSKIN._value = null;\n\t\tLANGUAGE._value = null;\n\t\tHIGHLIGHT_PULSE._value = StringConverter.toBoolean(EProperties.getInstance().getProperty(HIGHLIGHT_PULSE));\n\t\tSIMULATION_TIME._value = -1L;\n\t}\n\n\t// =========================== getter and setter\n\t// ============================\n\n\tpublic void setValue(Object newValue) {\n\t\tObject oldValue = _value;\n\t\tif (oldValue == null) {\n\t\t\tif (newValue != null) {\n\t\t\t\t_value = newValue;\n\t\t\t\tinformListeners();\n\t\t\t}\n\t\t}\n\t\telse if (!oldValue.equals(newValue)) {\n\t\t\t_value = newValue;\n\t\t\tinformListeners();\n\t\t}\n\t}\n\n\tpublic boolean toggle() {\n\t\treturn (boolean) (_value = !((boolean) _value));\n\t}\n\n\tpublic Object getValue() {\n\t\treturn _value;\n\t}\n\n\t/*\n\t * ========================= listener stuff =======================\n\t */\n\n\tpublic void addListener(StatusListener listener) {\n\t\t_listeners.add(listener);\n\t}\n\n\tpublic void removeListener(StatusListener listener) {\n\t\t_listeners.remove(listener);\n\t}\n\n\tprivate void informListeners() {\n\t\tfor (StatusListener listener : _listeners) {\n\t\t\tlistener.statusChanged(this, _value);\n\t\t}\n\t}\n}",
"public class EFrame extends JFrame implements StatusListener {\n\n\t/*\n\t * ========================== private fields ===============================\n\t */\n\n\t// scrollPane as south component of the contentPane (North component is\n\t// the actionBar).\n\tprivate JScrollPane _scrollPane;\n\n\t// configuration panel for display the current configuration of the eniac.\n\t// This component is child to the scrollPane.\n\t// If no current configuration, this is null.\n\tprivate ConfigPanel _configPanel = null;\n\n\tprivate MediaTracker _mediaTracker;\n\n\t/*\n\t * ============================ singleton stuff ===========================\n\t */\n\n\tprivate static EFrame instance;\n\n\tprivate EFrame() {\n\n\t\t// set bounds.\n\t\tDimension mySize = StringConverter.toDimension(EProperties.getInstance().getProperty(\"EFRAME_SIZE\"));\n\t\tDimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();\n\t\tmySize.width = Math.min(mySize.width, screenSize.width);\n\t\tmySize.height = Math.min(mySize.height, screenSize.height);\n\t\tsetSize(mySize);\n\t\tsetLocation((screenSize.width - mySize.width) / 2, (screenSize.height - mySize.height) / 3);\n\n\t\t// create media tracker\n\t\t_mediaTracker = new MediaTracker(this);\n\n\t\t// add as singleton to starter\n\t\tStatus.LIFECYCLE.addListener(this);\n\t}\n\n\tpublic static EFrame getInstance() {\n\t\tif (instance == null) {\n\t\t\tinstance = new EFrame();\n\t\t}\n\t\treturn instance;\n\t}\n\n\t/**\n\t * Initializes this dvFrame. Listener registration is done, the frame is\n\t * layouted and finally brought to the screen.\n\t */\n\tpublic void toScreen() {\n\n\t\t// set window title\n\t\tsetTitle(Dictionary.MAIN_FRAME_TITLE.getText());\n\n\t\t// window listener\n\t\taddWindowListener(new WindowAdapter() {\n\t\t\tpublic void windowClosing(WindowEvent e) {\n\t\t\t\tManager.getInstance().stop();\n\t\t\t\tManager.getInstance().destroy();\n\t\t\t\tdispose();\n\t\t\t}\n\t\t});\n\n\t\t// init scrollPane\n\t\t_scrollPane = new JScrollPane();\n\t\tColor c = StringConverter.toColor(EProperties.getInstance().getProperty(\"BACKGROUND_COLOR\"));\n\t\t_scrollPane.getViewport().setBackground(c);\n\n\t\t// add components\n\t\t// create and init menu handler\n\t\tHashtable<String, EAction> actionDefaults = new Hashtable<>();\n\t\tMenuHandler handler = new MenuHandler(actionDefaults);\n\t\thandler.init();\n\n\t\tsetJMenuBar(handler.getMenuBar());\n\t\tgetContentPane().setLayout(new BorderLayout());\n\t\tgetContentPane().add(handler.getToolBar(), BorderLayout.NORTH);\n\t\tgetContentPane().add(_scrollPane, BorderLayout.CENTER);\n\n\t\t// update configurationPanel\n\t\t// TODO: find new way of initializing configuration\n\t\tupdateConfigPanel();\n\n\t\t// add this as propertyChangeListener\n\t\tStatus.CONFIGURATION.addListener(this);\n\t\tStatus.SKIN.addListener(this);\n\t\tStatus.LANGUAGE.addListener(this);\n\n\t\t// init LogWindow\n\t\t// LogWindow.getInstance();\n\t\tsetVisible(true);\n\t}\n\n\t/*\n\t * =============================== methods =================================\n\t */\n\n\t// update config panel. This method is called, when the current\n\t// configuration changed.\n\tprivate void updateConfigPanel() {\n\n\t\t// dispose the old panel if any\n\t\tif (_configPanel != null) {\n\t\t\t_scrollPane.setViewportView(null);\n\t\t\t_configPanel.dispose();\n\t\t}\n\n\t\t// get current configuration and the viewDimension\n\t\tConfiguration config = (Configuration) Status.CONFIGURATION.getValue();\n\n\t\t// determine which configPanel to set\n\t\tif (config == null) {\n\n\t\t\t// configuration is null. Set null.\n\t\t\t_configPanel = null;\n\t\t}\n\t\telse {\n\t\t\t// create new configurationPanel\n\t\t\t_configPanel = (ConfigPanel) config.makePanel();\n\t\t\t// add configPanel to scrollPane and init\n\t\t\t_configPanel.init();\n\t\t\t_scrollPane.setViewportView(_configPanel);\n\t\t}\n\n\t\t// tell OVWindow to adjust its panel to the new configPanel\n\t\tOVWindow.getInstance().configPanelChanged();\n\t}\n\n\tpublic int showFileChooser(JFileChooser chooser, String approveButtonText) {\n\t\treturn chooser.showDialog(this, approveButtonText);\n\t}\n\n\tpublic ConfigPanel getConfigPanel() {\n\t\treturn _configPanel;\n\t}\n\n\t/*\n\t * ===================== PropertyChangeListener methods ==================\n\t */\n\n\t/**\n\t * This method is called when a status property is changed\n\t * \n\t * @param evt\n\t * The propertyEvent indicating that the architecture changed\n\t */\n\tpublic void statusChanged(Status status, Object newValue) {\n\n\t\tswitch (status) {\n\n\t\t\tcase CONFIGURATION :\n\t\t\t\t// configuration changed. Update the configPanel.\n\t\t\t\tupdateConfigPanel();\n\t\t\t\tbreak;\n\t\t\tcase SKIN :\n\t\t\t\t// skin changed. repaint\n\t\t\t\trepaint();\n\t\t\t\tbreak;\n\n\t\t\tcase LANGUAGE :\n\t\t\t\t// language changed. repaint and adjust title.\n\t\t\t\trepaint();\n\n\t\t\t\t// set default locale to JComponent.\n\t\t\t\t// So optionPane buttons get the right language.\n\t\t\t\tJComponent.setDefaultLocale(new Locale((String) newValue));\n\t\t\t\tsetTitle(Dictionary.MAIN_FRAME_TITLE.getText());\n\t\t\t\tbreak;\n\n\t\t\tcase LIFECYCLE :\n\t\t\t\tif (newValue == Manager.LifeCycle.STOPPED) {\n\t\t\t\t\tsetVisible(false);\n\t\t\t\t}\n\t\t\t\telse if (newValue == Manager.LifeCycle.DESTROYED) {\n\t\t\t\t\tdispose();\n\t\t\t\t\tinstance = null;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\tdefault :\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\t/*\n\t * ============================ changelistener ===========================\n\t */\n\n\tpublic void addChangeListener(ChangeListener listener) {\n\t\t_scrollPane.getViewport().addChangeListener(listener);\n\t}\n\n\tpublic void removeChangeListener(ChangeListener listener) {\n\t\t_scrollPane.getViewport().removeChangeListener(listener);\n\t}\n\n\t/**\n\t * @param path\n\t * @return\n\t */\n\tpublic Image getResourceAsImage(String name) {\n\n\t\t// get url. If path cannot be resolved, return null.\n\t\tURL url = Manager.class.getClassLoader().getResource(name);\n\t\tif (url == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\tImage img = Toolkit.getDefaultToolkit().createImage(url);\n\t\t_mediaTracker.addImage(img, 1);\n\t\ttry {\n\t\t\t_mediaTracker.waitForAll();\n\t\t} catch (InterruptedException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\n\t\treturn img;\n\t}\n\n}"
] | import java.awt.event.ActionEvent;
import javax.swing.JScrollPane;
import eniac.data.type.EType;
import eniac.data.view.parent.ConfigPanel;
import eniac.skin.Descriptor;
import eniac.skin.Skin;
import eniac.util.Status;
import eniac.window.EFrame; | /*******************************************************************************
* Copyright (c) 2003-2005, 2013 Till Zoppke.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/gpl.html
*
* Contributors:
* Till Zoppke - initial API and implementation
******************************************************************************/
/*
* Created on 21.04.2004
*/
package eniac.menu.action;
/**
* @author zoppke
*/
public class ZoomFitWidth extends EAction {
/**
* @param e
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent e) {
// get variables
ConfigPanel cp = EFrame.getInstance().getConfigPanel();
JScrollPane scrollPane = (JScrollPane) cp.getParent().getParent();
int newWidth = scrollPane.getWidth();
EType configType = cp.getData().getType(); | Skin skin = (Skin) Status.SKIN.getValue(); | 4 |
Multiplayer-italia/AuthMe-Reloaded | src/main/java/uk/org/whoami/authme/commands/UnregisterCommand.java | [
"public class Utils {\r\n //private Settings settings = Settings.getInstance();\r\n private Player player;\r\n private String currentGroup;\r\n private static Utils singleton;\r\n private String unLoggedGroup = Settings.getUnloggedinGroup;\r\n /* \r\n public Utils(Player player) {\r\n this.player = player;\r\n \r\n }\r\n */\r\n public void setGroup(Player player, groupType group) {\r\n if (!player.isOnline())\r\n return;\r\n if(!Settings.isPermissionCheckEnabled)\r\n return;\r\n \r\n switch(group) {\r\n case UNREGISTERED: {\r\n currentGroup = AuthMe.permission.getPrimaryGroup(player);\r\n AuthMe.permission.playerRemoveGroup(player, currentGroup);\r\n AuthMe.permission.playerAddGroup(player, Settings.unRegisteredGroup);\r\n break;\r\n }\r\n case REGISTERED: {\r\n currentGroup = AuthMe.permission.getPrimaryGroup(player);\r\n AuthMe.permission.playerRemoveGroup(player, currentGroup);\r\n AuthMe.permission.playerAddGroup(player, Settings.getRegisteredGroup);\r\n break;\r\n } \r\n }\r\n return;\r\n }\r\n \r\n public String removeAll(Player player) {\r\n if(!Utils.getInstance().useGroupSystem()){\r\n return null;\r\n }\r\n \r\n /*if (AuthMe.permission.playerAdd(this.player,\"-*\") ) {\r\n AuthMe.permission.playerAdd(this.player,\"authme.login\");\r\n return true;\r\n }*/\r\n \r\n \r\n //System.out.println(\"permissions? \"+ hasPerm);\r\n if( !Settings.getJoinPermissions.isEmpty() ) {\r\n hasPermOnJoin(player);\r\n }\r\n \r\n this.currentGroup = AuthMe.permission.getPrimaryGroup(player.getWorld(),player.getName().toString());\r\n //System.out.println(\"current grop\" + currentGroup);\r\n if(AuthMe.permission.playerRemoveGroup(player.getWorld(),player.getName().toString(), currentGroup) && AuthMe.permission.playerAddGroup(player.getWorld(),player.getName().toString(),this.unLoggedGroup)) {\r\n \r\n return currentGroup;\r\n }\r\n \r\n return null;\r\n \r\n }\r\n \r\n public boolean addNormal(Player player, String group) {\r\n if(!Utils.getInstance().useGroupSystem()){\r\n return false;\r\n }\r\n // System.out.println(\"in add normal\");\r\n /* if (AuthMe.permission.playerRemove(this.player, \"-*\"))\r\n return true;\r\n */ \r\n if(AuthMe.permission.playerRemoveGroup(player.getWorld(),player.getName().toString(),this.unLoggedGroup) && AuthMe.permission.playerAddGroup(player.getWorld(),player.getName().toString(),group)) {\r\n //System.out.println(\"vecchio \"+this.unLoggedGroup+ \"nuovo\" + group);\r\n return true;\r\n \r\n }\r\n return false;\r\n } \r\n\r\n private String hasPermOnJoin(Player player) {\r\n /* if(Settings.getJoinPermissions.isEmpty())\r\n return null; */\r\n Iterator<String> iter = Settings.getJoinPermissions.iterator();\r\n while (iter.hasNext()) {\r\n String permission = iter.next();\r\n // System.out.println(\"permissions? \"+ permission);\r\n \r\n if(AuthMe.permission.playerHas(player, permission)){\r\n // System.out.println(\"player has permissions \" +permission);\r\n AuthMe.permission.playerAddTransient(player, permission);\r\n }\r\n }\r\n return null;\r\n }\r\n \r\n public boolean isUnrestricted(Player player) {\r\n \r\n \r\n if(Settings.getUnrestrictedName.isEmpty() || Settings.getUnrestrictedName == null)\r\n return false;\r\n \r\n // System.out.println(\"name to escape \"+player.getName());\r\n if(Settings.getUnrestrictedName.contains(player.getName())) {\r\n // System.out.println(\"name to escape correctly\"+player.getName());\r\n return true;\r\n }\r\n \r\n return false;\r\n \r\n \r\n }\r\n public static Utils getInstance() {\r\n \r\n singleton = new Utils();\r\n \r\n return singleton;\r\n } \r\n \r\n private boolean useGroupSystem() {\r\n \r\n if(Settings.isPermissionCheckEnabled && !Settings.getUnloggedinGroup.isEmpty()) {\r\n return true;\r\n } return false;\r\n \r\n }\r\n \r\n /*\r\n * Random Token for passpartu\r\n * \r\n */\r\n public boolean obtainToken() {\r\n File file = new File(\"plugins/AuthMe/passpartu.token\");\r\n\r\n\tif (file.exists())\r\n file.delete();\r\n\r\n\t\tFileWriter writer = null;\r\n\t\ttry {\r\n\t\t\tfile.createNewFile();\r\n\t\t\twriter = new FileWriter(file);\r\n String token = generateToken();\r\n writer.write(token+\":\"+System.currentTimeMillis()/1000+\"\\r\\n\");\r\n writer.flush();\r\n System.out.println(\"[AuthMe] Security passpartu token: \"+ token);\r\n writer.close();\r\n return true;\r\n } catch(Exception e) {\r\n e.printStackTrace(); \r\n }\r\n \r\n \r\n return false;\r\n }\r\n \r\n /*\r\n * Read Toekn\r\n */\r\n public boolean readToken(String inputToken) {\r\n File file = new File(\"plugins/AuthMe/passpartu.token\");\r\n \r\n\tif (!file.exists()) \t\r\n return false;\r\n \r\n if (inputToken.isEmpty() )\r\n return false;\r\n \r\n\t\tScanner reader = null;\r\n\t\ttry {\r\n\t\t\treader = new Scanner(file);\r\n\r\n\t\t\twhile (reader.hasNextLine()) {\r\n\t\t\t\tfinal String line = reader.nextLine();\r\n\r\n\t\t\t\tif (line.contains(\":\")) { \r\n String[] tokenInfo = line.split(\":\");\r\n //System.err.println(\"Authme input token \"+inputToken+\" saved token \"+tokenInfo[0]);\r\n //System.err.println(\"Authme time \"+System.currentTimeMillis()/1000+\"saved time \"+Integer.parseInt(tokenInfo[1]));\r\n if(tokenInfo[0].equals(inputToken) && System.currentTimeMillis()/1000-30 <= Integer.parseInt(tokenInfo[1]) ) { \r\n file.delete();\r\n reader.close();\r\n return true;\r\n }\r\n } \r\n }\r\n } catch(Exception e) {\r\n e.printStackTrace(); \r\n }\r\n \r\n\treader.close(); \r\n return false;\r\n }\r\n /*\r\n * Generate Random Token\r\n */\r\n private String generateToken() {\r\n // obtain new random token \r\n Random rnd = new Random ();\r\n char[] arr = new char[5];\r\n\r\n for (int i=0; i<5; i++) {\r\n int n = rnd.nextInt (36);\r\n arr[i] = (char) (n < 10 ? '0'+n : 'a'+n-10);\r\n }\r\n \r\n return new String(arr); \r\n }\r\n public enum groupType {\r\n UNREGISTERED, REGISTERED, NOTLOGGEDIN, LOGGEDIN\r\n }\r\n \r\n}\r",
"public class FileCache {\r\n //private HashMap<Enchantment, Integer> ench;\r\n \r\n \r\n\tpublic FileCache() {\r\n\t\tfinal File folder = new File(\"cache\");\r\n\t\tif (!folder.exists()) {\r\n\t\t\tfolder.mkdirs();\r\n\t\t}\r\n\t}\r\n\r\n\tpublic void createCache(String playername, DataFileCache playerData, String group, boolean operator) {\r\n\t\tfinal File file = new File(\"cache/\" + playername\r\n\t\t\t\t+ \".cache\");\r\n\r\n\t\tif (file.exists()) {\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tFileWriter writer = null;\r\n\t\ttry {\r\n\t\t\tfile.createNewFile();\r\n\r\n\t\t\twriter = new FileWriter(file);\r\n \r\n // put player group in cache\r\n // put if player is an op or not 1: is op 0: isnet op!\r\n // line format Group|OperatorStatus\r\n \r\n if(operator)\r\n writer.write(group+\";1\\r\\n\");\r\n else writer.write(group+\";0\\r\\n\");\r\n \r\n writer.flush();\r\n \r\n\t\t\tItemStack[] invstack = playerData.getInventory();\r\n\r\n\t\t\tfor (int i = 0; i < invstack.length; i++) {\r\n\r\n\t\t\t\tint itemid = 0;\r\n\t\t\t\tint amount = 0;\r\n\t\t\t\tint durability = 0;\r\n String enchList = \"\";\r\n //ench = new HashMap<Enchantment, Integer>();\r\n\r\n\t\t\t\tif (invstack[i] != null) {\r\n\t\t\t\t\titemid = invstack[i].getTypeId();\r\n\t\t\t\t\tamount = invstack[i].getAmount();\r\n\t\t\t\t\tdurability = invstack[i].getDurability();\r\n \r\n \r\n for(Enchantment e : invstack[i].getEnchantments().keySet())\r\n {\r\n //System.out.println(\"enchant \"+e.getName()+\" bog \"+invstack[i].getEnchantmentLevel(e));\r\n enchList = enchList.concat(e.getName()+\":\"+invstack[i].getEnchantmentLevel(e)+\":\");\r\n //System.out.println(enchList);\r\n \r\n }\r\n }\r\n \r\n\t\t\t\twriter.write(\"i\" + \":\" + itemid + \":\" + amount + \":\"\r\n\t\t\t\t\t\t+ durability + \":\"+ enchList + \"\\r\\n\");\r\n\t\t\t\twriter.flush();\r\n\t\t\t}\r\n\r\n\t\t\tItemStack[] armorstack = playerData.getArmour();\r\n\r\n\t\t\tfor (int i = 0; i < armorstack.length; i++) {\r\n\t\t\t\tint itemid = 0;\r\n\t\t\t\tint amount = 0;\r\n\t\t\t\tint durability = 0;\r\n String enchList = \"\";\r\n \r\n\t\t\t\tif (armorstack[i] != null) {\r\n\t\t\t\t\titemid = armorstack[i].getTypeId();\r\n\t\t\t\t\tamount = armorstack[i].getAmount();\r\n\t\t\t\t\tdurability = armorstack[i].getDurability();\r\n \r\n for(Enchantment e : armorstack[i].getEnchantments().keySet())\r\n {\r\n //System.out.println(\"enchant \"+e.getName()+\" bog \"+armorstack[i].getEnchantmentLevel(e));\r\n enchList = enchList.concat(e.getName()+\":\"+armorstack[i].getEnchantmentLevel(e)+\":\");\r\n //System.out.println(enchList);\r\n \r\n } \r\n\t\t\t\t}\r\n\r\n\t\t\t\twriter.write(\"w\" + \":\" + itemid + \":\" + amount + \":\"\r\n\t\t\t\t\t\t+ durability + \":\"+ enchList + \"\\r\\n\");\r\n\t\t\t\twriter.flush();\r\n\t\t\t}\r\n\r\n\t\t\twriter.close();\r\n\t\t} catch (final Exception e) {\r\n\t\t\te.printStackTrace();\r\n\t\t}\r\n\t}\r\n\r\n\tpublic DataFileCache readCache(String playername) {\r\n\t\tfinal File file = new File(\"cache/\" + playername\r\n\t\t\t\t+ \".cache\");\r\n\r\n\t\tItemStack[] stacki = new ItemStack[36];\r\n\t\tItemStack[] stacka = new ItemStack[4];\r\n String group = null;\r\n boolean op = false;\r\n \r\n\t\tif (!file.exists()) {\r\n\t\t\treturn new DataFileCache(stacki, stacka);\r\n\t\t}\r\n\r\n\t\tScanner reader = null;\r\n\t\ttry {\r\n\t\t\treader = new Scanner(file);\r\n\r\n\t\t\tint i = 0;\r\n\t\t\tint a = 0;\r\n\t\t\twhile (reader.hasNextLine()) {\r\n\t\t\t\tfinal String line = reader.nextLine();\r\n\r\n\t\t\t\tif (!line.contains(\":\")) {\r\n // the fist line rapresent the player group and operator status\r\n final String[] playerInfo = line.split(\";\");\r\n group = playerInfo[0];\r\n \r\n if (Integer.parseInt(playerInfo[1]) == 1) {\r\n op = true;\r\n } else op = false;\r\n \r\n continue;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tfinal String[] in = line.split(\":\");\r\n\r\n\t\t\t\t/*if (in.length != 4) {\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\t} */\r\n \r\n\t\t\t\tif (!in[0].equals(\"i\") && !in[0].equals(\"w\")) {\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n // can enchant item? size ofstring in file - 4 all / 2 = number of enchant\r\n\t\t\t\tif (in[0].equals(\"i\")) {\r\n Enchantment e = null; \r\n \r\n\t\t\t\t\tstacki[i] = new ItemStack(Integer.parseInt(in[1]),\r\n\t\t\t\t\t\t\tInteger.parseInt(in[2]), Short.parseShort((in[3])));\r\n\t\t\t\t\t// qui c'e' un problema serio!\r\n if(in.length > 4 && !in[4].isEmpty()) {\r\n for(int k=4;k<in.length-1;k++) {\r\n //System.out.println(\"enchant \"+in[k]);\r\n stacki[i].addUnsafeEnchantment(e.getByName(in[k]) ,Integer.parseInt(in[k+1]));\r\n k++;\r\n }\r\n }\r\n i++;\r\n\t\t\t\t} else {\r\n Enchantment e = null; \r\n\t\t\t\t\tstacka[a] = new ItemStack(Integer.parseInt(in[1]),\r\n\t\t\t\t\t\t\tInteger.parseInt(in[2]), Short.parseShort((in[3])));\r\n if(in.length > 4 && !in[4].isEmpty()) {\r\n for(int k=4;k<in.length-1;k++) {\r\n //System.out.println(\"enchant \"+in[k]);\r\n stacka[a].addUnsafeEnchantment(e.getByName(in[k]) ,Integer.parseInt(in[k+1]));\r\n k++;\r\n }\r\n }\r\n\t\t\t\t\ta++;\r\n\t\t\t\t}\r\n\r\n\t\t\t}\r\n\t\t} catch (final Exception e) {\r\n\t\t\te.printStackTrace();\r\n\t\t} finally {\r\n\t\t\tif (reader != null) {\r\n\t\t\t\treader.close();\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn new DataFileCache(stacki, stacka, group, op);\r\n\t}\r\n\r\n\tpublic void removeCache(String playername) {\r\n\t\tfinal File file = new File(\"cache/\" + playername\r\n\t\t\t\t+ \".cache\");\r\n\r\n\t\tif (file.exists()) {\r\n\t\t\tfile.delete();\r\n\t\t}\r\n\t}\r\n\r\n\tpublic boolean doesCacheExist(String playername) {\r\n\t\tfinal File file = new File(\"cache/\" + playername\r\n\t\t\t\t+ \".cache\");\r\n\r\n\t\tif (file.exists()) {\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\treturn false;\r\n\t}\r\n\r\n \r\n}\r",
"public class LimboCache {\r\n\r\n private static LimboCache singleton = null;\r\n private HashMap<String, LimboPlayer> cache;\r\n //private Settings settings = Settings.getInstance();\r\n private FileCache playerData = new FileCache();\r\n \r\n private LimboCache() {\r\n this.cache = new HashMap<String, LimboPlayer>();\r\n }\r\n\r\n public void addLimboPlayer(Player player) {\r\n String name = player.getName().toLowerCase();\r\n Location loc = player.getLocation();\r\n int gameMode = player.getGameMode().getValue();\r\n ItemStack[] arm;\r\n ItemStack[] inv;\r\n boolean operator;\r\n String playerGroup = \"\";\r\n \r\n if (playerData.doesCacheExist(name)) {\r\n //DataFileCache playerInvArmor = playerData.readCache(name); \r\n inv = playerData.readCache(name).getInventory();\r\n arm = playerData.readCache(name).getArmour();\r\n playerGroup = playerData.readCache(name).getGroup();\r\n operator = playerData.readCache(name).getOperator();\r\n } else {\r\n inv = player.getInventory().getContents();\r\n arm = player.getInventory().getArmorContents();\r\n \r\n // check if player is an operator, then save it to ram if cache dosent exist!\r\n \r\n if(player.isOp() ) {\r\n //System.out.println(\"player is an operator in limboCache\");\r\n operator = true;\r\n }\r\n else operator = false; \r\n }\r\n\r\n \r\n \r\n if(Settings.isForceSurvivalModeEnabled) {\r\n if(Settings.isResetInventoryIfCreative && gameMode != 0 ) {\r\n player.sendMessage(\"Your inventory has been cleaned!\");\r\n inv = new ItemStack[36];\r\n arm = new ItemStack[4];\r\n }\r\n gameMode = 0;\r\n } \r\n if(player.isDead()) {\r\n \tloc = player.getWorld().getSpawnLocation();\r\n }\r\n \r\n if(cache.containsKey(name) && playerGroup.isEmpty()) {\r\n //System.out.println(\"contiene il player \"+name);\r\n LimboPlayer groupLimbo = cache.get(name);\r\n playerGroup = groupLimbo.getGroup();\r\n }\r\n \r\n cache.put(player.getName().toLowerCase(), new LimboPlayer(name, loc, inv, arm, gameMode, operator, playerGroup));\r\n //System.out.println(\"il gruppo in limboChace \"+playerGroup);\r\n }\r\n \r\n public void addLimboPlayer(Player player, String group) {\r\n \r\n cache.put(player.getName().toLowerCase(), new LimboPlayer(player.getName().toLowerCase(), group));\r\n //System.out.println(\"il gruppo in limboChace \"+group);\r\n }\r\n \r\n public void deleteLimboPlayer(String name) {\r\n cache.remove(name);\r\n }\r\n\r\n public LimboPlayer getLimboPlayer(String name) {\r\n return cache.get(name);\r\n }\r\n\r\n public boolean hasLimboPlayer(String name) {\r\n return cache.containsKey(name);\r\n }\r\n \r\n \r\n public static LimboCache getInstance() {\r\n if (singleton == null) {\r\n singleton = new LimboCache();\r\n }\r\n return singleton;\r\n }\r\n}\r",
"public interface DataSource {\r\n\r\n public enum DataSourceType {\r\n\r\n MYSQL, FILE, SQLITE\r\n }\r\n\r\n boolean isAuthAvailable(String user);\r\n\r\n PlayerAuth getAuth(String user);\r\n\r\n boolean saveAuth(PlayerAuth auth);\r\n\r\n boolean updateSession(PlayerAuth auth);\r\n\r\n boolean updatePassword(PlayerAuth auth);\r\n\r\n int purgeDatabase(long until);\r\n\r\n boolean removeAuth(String user);\r\n \r\n boolean updateQuitLoc(PlayerAuth auth);\r\n \r\n int getIps(String ip);\r\n \r\n void close();\r\n\r\n void reload();\r\n}\r",
"public class PasswordSecurity {\r\n\r\n private static SecureRandom rnd = new SecureRandom();\r\n\r\n private static String getMD5(String message) throws NoSuchAlgorithmException {\r\n MessageDigest md5 = MessageDigest.getInstance(\"MD5\");\r\n\r\n md5.reset();\r\n md5.update(message.getBytes());\r\n byte[] digest = md5.digest();\r\n\r\n return String.format(\"%0\" + (digest.length << 1) + \"x\", new BigInteger(1,\r\n digest));\r\n }\r\n\r\n private static String getSHA1(String message) throws NoSuchAlgorithmException {\r\n MessageDigest sha1 = MessageDigest.getInstance(\"SHA1\");\r\n sha1.reset();\r\n sha1.update(message.getBytes());\r\n byte[] digest = sha1.digest();\r\n\r\n return String.format(\"%0\" + (digest.length << 1) + \"x\", new BigInteger(1,\r\n digest));\r\n }\r\n\r\n private static String getSHA256(String message) throws NoSuchAlgorithmException {\r\n MessageDigest sha256 = MessageDigest.getInstance(\"SHA-256\");\r\n\r\n sha256.reset();\r\n sha256.update(message.getBytes());\r\n byte[] digest = sha256.digest();\r\n\r\n return String.format(\"%0\" + (digest.length << 1) + \"x\", new BigInteger(1,\r\n digest));\r\n }\r\n\r\n public static String getWhirlpool(String message) {\r\n Whirlpool w = new Whirlpool();\r\n byte[] digest = new byte[Whirlpool.DIGESTBYTES];\r\n w.NESSIEinit();\r\n w.NESSIEadd(message);\r\n w.NESSIEfinalize(digest);\r\n return Whirlpool.display(digest);\r\n }\r\n\r\n private static String getSaltedHash(String message, String salt) throws NoSuchAlgorithmException {\r\n return \"$SHA$\" + salt + \"$\" + getSHA256(getSHA256(message) + salt);\r\n }\r\n \r\n //\r\n // VBULLETIN 3.X 4.X METHOD\r\n //\r\n \r\n private static String getSaltedMd5(String message, String salt) throws NoSuchAlgorithmException {\r\n return \"$MD5vb$\" + salt + \"$\" + getMD5(getMD5(message) + salt);\r\n }\r\n \r\n private static String getXAuth(String message, String salt) {\r\n String hash = getWhirlpool(salt + message).toLowerCase();\r\n int saltPos = (message.length() >= hash.length() ? hash.length() - 1 : message.length());\r\n return hash.substring(0, saltPos) + salt + hash.substring(saltPos);\r\n }\r\n\r\n private static String createSalt(int length) throws NoSuchAlgorithmException {\r\n byte[] msg = new byte[40];\r\n rnd.nextBytes(msg);\r\n\r\n MessageDigest sha1 = MessageDigest.getInstance(\"SHA1\");\r\n sha1.reset();\r\n byte[] digest = sha1.digest(msg);\r\n return String.format(\"%0\" + (digest.length << 1) + \"x\", new BigInteger(1,digest)).substring(0, length);\r\n }\r\n\r\n public static String getHash(HashAlgorithm alg, String password) throws NoSuchAlgorithmException {\r\n switch (alg) {\r\n case MD5:\r\n return getMD5(password);\r\n case SHA1:\r\n return getSHA1(password);\r\n case SHA256:\r\n String salt = createSalt(16);\r\n return getSaltedHash(password, salt);\r\n case MD5VB:\r\n String salt2 = createSalt(16);\r\n return getSaltedMd5(password, salt2);\r\n case WHIRLPOOL:\r\n return getWhirlpool(password);\r\n case XAUTH:\r\n String xsalt = createSalt(12);\r\n return getXAuth(password, xsalt);\r\n case PHPBB:\r\n return getPhpBB(password);\r\n case PLAINTEXT:\r\n return getPlainText(password);\r\n default:\r\n throw new NoSuchAlgorithmException(\"Unknown hash algorithm\");\r\n }\r\n }\r\n\r\n public static boolean comparePasswordWithHash(String password, String hash) throws NoSuchAlgorithmException {\r\n //System.out.println(\"[Authme Debug] debug hashString\"+hash);\r\n if(hash.contains(\"$H$\")) {\r\n PhpBB checkHash = new PhpBB();\r\n return checkHash.phpbb_check_hash(password, hash);\r\n }\r\n // PlainText Password\r\n if(hash.length() < 32 ) {\r\n return hash.equals(password);\r\n }\r\n \r\n if (hash.length() == 32) {\r\n return hash.equals(getMD5(password));\r\n }\r\n\r\n if (hash.length() == 40) {\r\n return hash.equals(getSHA1(password));\r\n }\r\n\r\n if (hash.length() == 140) {\r\n int saltPos = (password.length() >= hash.length() ? hash.length() - 1 : password.length());\r\n String salt = hash.substring(saltPos, saltPos + 12);\r\n return hash.equals(getXAuth(password, salt));\r\n }\r\n\r\n if (hash.contains(\"$\")) {\r\n //System.out.println(\"[Authme Debug] debug hashString\"+hash);\r\n String[] line = hash.split(\"\\\\$\");\r\n if (line.length > 3 && line[1].equals(\"SHA\")) {\r\n return hash.equals(getSaltedHash(password, line[2]));\r\n } else {\r\n if(line[1].equals(\"MD5vb\")) {\r\n //System.out.println(\"[Authme Debug] password hashed from Authme\"+getSaltedMd5(password, line[2]));\r\n //System.out.println(\"[Authme Debug] salt from Authme\"+line[2]);\r\n //System.out.println(\"[Authme Debug] equals? Authme: \"+hash);\r\n //hash = \"$MD5vb$\" + salt + \"$\" + hash;\r\n return hash.equals(getSaltedMd5(password, line[2]));\r\n }\r\n }\r\n }\r\n return false;\r\n }\r\n\r\n private static String getPhpBB(String password) {\r\n PhpBB hash = new PhpBB();\r\n String phpBBhash = hash.phpbb_hash(password);\r\n return phpBBhash;\r\n }\r\n\r\n private static String getPlainText(String password) {\r\n return password;\r\n }\r\n\r\n public enum HashAlgorithm {\r\n\r\n MD5, SHA1, SHA256, WHIRLPOOL, XAUTH, MD5VB, PHPBB, PLAINTEXT\r\n }\r\n}\r",
"public class Messages extends CustomConfiguration {\r\n\r\n private static Messages singleton = null;\r\n private HashMap<String, String> map;\r\n \r\n\r\n public Messages() {\r\n \r\n super(new File(Settings.MESSAGE_FILE+\"_\"+Settings.messagesLanguage+\".yml\"));\r\n loadDefaults();\r\n loadFile();\r\n singleton = this;\r\n \r\n }\r\n \r\n private void loadDefaults() {\r\n this.set(\"logged_in\", \"&cAlready logged in!\");\r\n this.set(\"not_logged_in\", \"&cNot logged in!\");\r\n this.set(\"reg_disabled\", \"&cRegistration is disabled\");\r\n this.set(\"user_regged\", \"&cUsername already registered\");\r\n this.set(\"usage_reg\", \"&cUsage: /register password ConfirmPassword\");\r\n this.set(\"usage_log\", \"&cUsage: /login password\");\r\n this.set(\"user_unknown\", \"&cUsername not registered\");\r\n this.set(\"pwd_changed\", \"&cPassword changed!\");\r\n this.set(\"reg_only\", \"Registered players only! Please visit http://example.com to register\");\r\n this.set(\"valid_session\", \"&cSession login\");\r\n this.set(\"login_msg\", \"&cPlease login with \\\"/login password\\\"\");\r\n this.set(\"reg_msg\", \"&cPlease register with \\\"/register password ConfirmPassword\\\"\");\r\n this.set(\"timeout\", \"Login Timeout\");\r\n this.set(\"wrong_pwd\", \"&cWrong password\");\r\n this.set(\"logout\", \"&cSuccessful logout\");\r\n this.set(\"usage_unreg\", \"&cUsage: /unregister password\");\r\n this.set(\"registered\", \"&cSuccessfully registered!\");\r\n this.set(\"unregistered\", \"&cSuccessfully unregistered!\");\r\n this.set(\"login\", \"&cSuccessful login!\");\r\n this.set(\"no_perm\", \"&cNo Permission\");\r\n this.set(\"same_nick\", \"Same nick is already playing\");\r\n this.set(\"reg_voluntarily\", \"You can register your nickname with the server with the command \\\"/register password ConfirmPassword\\\"\");\r\n this.set(\"reload\", \"Configuration and database has been reloaded\");\r\n this.set(\"error\", \"An error ocurred; Please contact the admin\");\r\n this.set(\"unknown_user\", \"User is not in database\");\r\n this.set(\"unsafe_spawn\",\"Your Quit location was unsafe, teleporting you to World Spawn\");\r\n this.set(\"unvalid_session\",\"Session Dataes doesnt corrispond Plaese wait the end of session\");\r\n this.set(\"max_reg\",\"You have Exeded the max number of Registration for your Account\"); \r\n this.set(\"password_error\",\"Password doesnt match\");\r\n this.set(\"pass_len\",\"Your password dind't reach the minimum length or exeded the max length\");\r\n this.set(\"vb_nonActiv\",\"Your Account isent Activated yet check your Emails!\");\r\n this.set(\"usage_changepassword\", \"Usage: /changepassword oldPassword newPassword\");\r\n \r\n }\r\n\r\n\tprivate void loadFile() {\r\n this.load();\r\n this.save();\r\n \r\n }\r\n\r\n public String _(String msg) {\r\n String loc = this.getString(msg);\r\n if (loc != null) {\r\n return loc.replace(\"&\", \"\\u00a7\");\r\n }\r\n return msg;\r\n }\r\n \r\n \r\n public static Messages getInstance() {\r\n if (singleton == null) {\r\n singleton = new Messages();\r\n } \r\n return singleton;\r\n }\r\n \r\n}\r",
"public final class Settings extends YamlConfiguration {\r\n\r\n public static final String PLUGIN_FOLDER = \"./plugins/AuthMe\";\r\n public static final String CACHE_FOLDER = Settings.PLUGIN_FOLDER + \"/cache\";\r\n public static final String AUTH_FILE = Settings.PLUGIN_FOLDER + \"/auths.db\";\r\n public static final String MESSAGE_FILE = Settings.PLUGIN_FOLDER + \"/messages\";\r\n public static final String SETTINGS_FILE = Settings.PLUGIN_FOLDER + \"/config.yml\";\r\n public static List<String> getJoinPermissions = null;\r\n public static List<String> getUnrestrictedName = null;\r\n private static List<String> getRestrictedIp;\r\n \r\n private int numSettings = 59;\r\n public final Plugin plugin;\r\n private final File file; \r\n \r\n public static DataSourceType getDataSource;\r\n public static HashAlgorithm getPasswordHash;\r\n \r\n public static Boolean isPermissionCheckEnabled, isRegistrationEnabled, isForcedRegistrationEnabled,\r\n isTeleportToSpawnEnabled, isSessionsEnabled, isChatAllowed, isAllowRestrictedIp, \r\n isMovementAllowed, isKickNonRegisteredEnabled, isForceSingleSessionEnabled,\r\n isForceSpawnLocOnJoinEnabled, isForceExactSpawnEnabled, isSaveQuitLocationEnabled,\r\n isForceSurvivalModeEnabled, isResetInventoryIfCreative, isCachingEnabled, isKickOnWrongPasswordEnabled,\r\n getEnablePasswordVerifier, protectInventoryBeforeLogInEnabled, isBackupActivated, isBackupOnStart,\r\n isBackupOnStop, enablePasspartu;\r\n \r\n \r\n public static String getNickRegex, getUnloggedinGroup, getMySQLHost, getMySQLPort, \r\n getMySQLUsername, getMySQLPassword, getMySQLDatabase, getMySQLTablename, \r\n getMySQLColumnName, getMySQLColumnPassword, getMySQLColumnIp, getMySQLColumnLastLogin,\r\n getMySQLColumnSalt, getMySQLColumnGroup, unRegisteredGroup, backupWindowsPath,\r\n getcUnrestrictedName, getRegisteredGroup, messagesLanguage;\r\n \r\n \r\n public static int getWarnMessageInterval, getSessionTimeout, getRegistrationTimeout, getMaxNickLength,\r\n getMinNickLength, getPasswordMinLen, getMovementRadius, getmaxRegPerIp, getNonActivatedGroup,\r\n passwordMaxLength;\r\n \r\n protected static YamlConfiguration configFile;\r\n \r\n public Settings(Plugin plugin) {\r\n //super(new File(Settings.PLUGIN_FOLDER + \"/config.yml\"), this.plugin);\r\n this.file = new File(plugin.getDataFolder(),\"config.yml\");\r\n \r\n this.plugin = plugin;\r\n\r\n \r\n\r\n //options().indent(4); \r\n // Override to always indent 4 spaces\r\n if(exists()) {\r\n load(); \r\n }\r\n else {\r\n loadDefaults(file.getName());\r\n load();\r\n }\r\n \r\n configFile = (YamlConfiguration) plugin.getConfig();\r\n \r\n //saveDefaults();\r\n \r\n }\r\n \r\n public void loadConfigOptions() {\r\n \r\n plugin.getLogger().info(\"Loading Configuration File...\");\r\n \r\n mergeConfig();\r\n \r\n messagesLanguage = checkLang(configFile.getString(\"settings.messagesLanguage\",\"en\"));\r\n isPermissionCheckEnabled = configFile.getBoolean(\"permission.EnablePermissionCheck\", false);\r\n isForcedRegistrationEnabled = configFile.getBoolean(\"settings.registration.force\", true);\r\n isRegistrationEnabled = configFile.getBoolean(\"settings.registration.enabled\", true);\r\n isTeleportToSpawnEnabled = configFile.getBoolean(\"settings.restrictions.teleportUnAuthedToSpawn\",false);\r\n getWarnMessageInterval = configFile.getInt(\"settings.registration.messageInterval\",5);\r\n isSessionsEnabled = configFile.getBoolean(\"settings.sessions.enabled\",false);\r\n getSessionTimeout = configFile.getInt(\"settings.sessions.timeout\",10);\r\n getRegistrationTimeout = configFile.getInt(\"settings.restrictions.timeout\",30);\r\n isChatAllowed = configFile.getBoolean(\"settings.restrictions.allowChat\",false);\r\n getMaxNickLength = configFile.getInt(\"settings.restrictions.maxNicknameLength\",20);\r\n getMinNickLength = configFile.getInt(\"settings.restrictions.minNicknameLength\",3);\r\n getPasswordMinLen = configFile.getInt(\"settings.security.minPasswordLength\",4);\r\n getNickRegex = configFile.getString(\"settings.restrictions.allowedNicknameCharacters\",\"[a-zA-Z0-9_?]*\");\r\n isAllowRestrictedIp = configFile.getBoolean(\"settings.restrictions.AllowRestrictedUser\",false);\r\n getRestrictedIp = configFile.getStringList(\"settings.restrictions.AllowedRestrictedUser\");\r\n isMovementAllowed = configFile.getBoolean(\"settings.restrictions.allowMovement\",false);\r\n getMovementRadius = configFile.getInt(\"settings.restrictions.allowedMovementRadius\",100);\r\n getJoinPermissions = configFile.getStringList(\"GroupOptions.Permissions.PermissionsOnJoin\");\r\n isKickOnWrongPasswordEnabled = configFile.getBoolean(\"settings.restrictions.kickOnWrongPassword\",false);\r\n isKickNonRegisteredEnabled = configFile.getBoolean(\"settings.restrictions.kickNonRegistered\",false);\r\n isForceSingleSessionEnabled = configFile.getBoolean(\"settings.restrictions.ForceSingleSession\",true);\r\n isForceSpawnLocOnJoinEnabled = configFile.getBoolean(\"settings.restrictions.ForceSpawnLocOnJoinEnabled\",false);\r\n isSaveQuitLocationEnabled = configFile.getBoolean(\"settings.restrictions.SaveQuitLocation\", false);\r\n isForceSurvivalModeEnabled = configFile.getBoolean(\"settings.GameMode.ForceSurvivalMode\", false);\r\n isResetInventoryIfCreative = configFile.getBoolean(\"settings.GameMode.ResetInventotyIfCreative\",false);\r\n getmaxRegPerIp = configFile.getInt(\"settings.restrictions.maxRegPerIp\",1);\r\n getPasswordHash = getPasswordHash();\r\n getUnloggedinGroup = configFile.getString(\"settings.security.unLoggedinGroup\",\"unLoggedInGroup\");\r\n getDataSource = getDataSource();\r\n isCachingEnabled = configFile.getBoolean(\"DataSource.caching\",true);\r\n getMySQLHost = configFile.getString(\"DataSource.mySQLHost\",\"127.0.0.1\");\r\n getMySQLPort = configFile.getString(\"DataSource.mySQLPort\",\"3306\");\r\n getMySQLUsername = configFile.getString(\"DataSource.mySQLUsername\",\"authme\");\r\n getMySQLPassword = configFile.getString(\"DataSource.mySQLPassword\",\"12345\");\r\n getMySQLDatabase = configFile.getString(\"DataSource.mySQLDatabase\",\"authme\");\r\n getMySQLTablename = configFile.getString(\"DataSource.mySQLTablename\",\"authme\");\r\n getMySQLColumnName = configFile.getString(\"DataSource.mySQLColumnName\",\"username\");\r\n getMySQLColumnPassword = configFile.getString(\"DataSource.mySQLColumnPassword\",\"password\");\r\n getMySQLColumnIp = configFile.getString(\"DataSource.mySQLColumnIp\",\"ip\");\r\n getMySQLColumnLastLogin = configFile.getString(\"DataSource.mySQLColumnLastLogin\",\"lastlogin\");\r\n getMySQLColumnSalt = configFile.getString(\"ExternalBoardOptions.mySQLColumnSalt\");\r\n getMySQLColumnGroup = configFile.getString(\"ExternalBoardOptions.mySQLColumnGroup\",\"\");\r\n getNonActivatedGroup = configFile.getInt(\"ExternalBoardOptions.nonActivedUserGroup\", -1);\r\n unRegisteredGroup = configFile.getString(\"GroupOptions.UnregisteredPlayerGroup\",\"\");\r\n getUnrestrictedName = configFile.getStringList(\"settings.unrestrictions.UnrestrictedName\");\r\n getRegisteredGroup = configFile.getString(\"GroupOptions.RegisteredPlayerGroup\",\"\");\r\n getEnablePasswordVerifier = configFile.getBoolean(\"settings.restrictions.enablePasswordVerifier\" , true);\r\n protectInventoryBeforeLogInEnabled = configFile.getBoolean(\"settings.restrictions.ProtectInventoryBeforeLogIn\", true);\r\n passwordMaxLength = configFile.getInt(\"settings.security.passwordMaxLength\", 20);\r\n isBackupActivated = configFile.getBoolean(\"BackupSystem.ActivateBackup\",false);\r\n isBackupOnStart = configFile.getBoolean(\"BackupSystem.OnServerStart\",false);\r\n isBackupOnStop = configFile.getBoolean(\"BackupSystem.OnServeStop\",false);\r\n backupWindowsPath = configFile.getString(\"BackupSystem.MysqlWindowsPath\", \"C:\\\\Program Files\\\\MySQL\\\\MySQL Server 5.1\\\\\");\r\n enablePasspartu = configFile.getBoolean(\"Passpartu.enablePasspartu\",false);\r\n\r\n\r\n saveDefaults();\r\n \r\n //System.out.println(\"[AuthMe debug] Config \" + getEnablePasswordVerifier.toString());\r\n //System.out.println(\"[AuthMe debug] Config \" + getEnablePasswordVerifier.toString());\r\n\r\n \r\n }\r\n \r\n public static void reloadConfigOptions(YamlConfiguration newConfig) {\r\n configFile = newConfig;\r\n \r\n //plugin.getLogger().info(\"RELoading Configuration File...\");\r\n messagesLanguage = checkLang(configFile.getString(\"settings.messagesLanguage\",\"en\"));\r\n isPermissionCheckEnabled = configFile.getBoolean(\"permission.EnablePermissionCheck\", false);\r\n isForcedRegistrationEnabled = configFile.getBoolean(\"settings.registration.force\", true);\r\n isRegistrationEnabled = configFile.getBoolean(\"settings.registration.enabled\", true);\r\n isTeleportToSpawnEnabled = configFile.getBoolean(\"settings.restrictions.teleportUnAuthedToSpawn\",false);\r\n getWarnMessageInterval = configFile.getInt(\"settings.registration.messageInterval\",5);\r\n isSessionsEnabled = configFile.getBoolean(\"settings.sessions.enabled\",false);\r\n getSessionTimeout = configFile.getInt(\"settings.sessions.timeout\",10);\r\n getRegistrationTimeout = configFile.getInt(\"settings.restrictions.timeout\",30);\r\n isChatAllowed = configFile.getBoolean(\"settings.restrictions.allowChat\",false);\r\n getMaxNickLength = configFile.getInt(\"settings.restrictions.maxNicknameLength\",20);\r\n getMinNickLength = configFile.getInt(\"settings.restrictions.minNicknameLength\",3);\r\n getPasswordMinLen = configFile.getInt(\"settings.security.minPasswordLength\",4);\r\n getNickRegex = configFile.getString(\"settings.restrictions.allowedNicknameCharacters\",\"[a-zA-Z0-9_?]*\");\r\n isAllowRestrictedIp = configFile.getBoolean(\"settings.restrictions.AllowRestrictedUser\",false);\r\n getRestrictedIp = configFile.getStringList(\"settings.restrictions.AllowedRestrictedUser\");\r\n isMovementAllowed = configFile.getBoolean(\"settings.restrictions.allowMovement\",false);\r\n getMovementRadius = configFile.getInt(\"settings.restrictions.allowedMovementRadius\",100);\r\n getJoinPermissions = configFile.getStringList(\"GroupOptions.Permissions.PermissionsOnJoin\");\r\n isKickOnWrongPasswordEnabled = configFile.getBoolean(\"settings.restrictions.kickOnWrongPassword\",false);\r\n isKickNonRegisteredEnabled = configFile.getBoolean(\"settings.restrictions.kickNonRegistered\",false);\r\n isForceSingleSessionEnabled = configFile.getBoolean(\"settings.restrictions.ForceSingleSession\",true);\r\n isForceSpawnLocOnJoinEnabled = configFile.getBoolean(\"settings.restrictions.ForceSpawnLocOnJoinEnabled\",false); \r\n isSaveQuitLocationEnabled = configFile.getBoolean(\"settings.restrictions.SaveQuitLocation\",false);\r\n isForceSurvivalModeEnabled = configFile.getBoolean(\"settings.GameMode.ForceSurvivalMode\",false);\r\n isResetInventoryIfCreative = configFile.getBoolean(\"settings.GameMode.ResetInventotyIfCreative\",false);\r\n getmaxRegPerIp = configFile.getInt(\"settings.restrictions.maxRegPerIp\",1);\r\n getPasswordHash = getPasswordHash();\r\n getUnloggedinGroup = configFile.getString(\"settings.security.unLoggedinGroup\",\"unLoggedInGroup\");\r\n getDataSource = getDataSource();\r\n isCachingEnabled = configFile.getBoolean(\"DataSource.caching\",true);\r\n getMySQLHost = configFile.getString(\"DataSource.mySQLHost\",\"127.0.0.1\");\r\n getMySQLPort = configFile.getString(\"DataSource.mySQLPort\",\"3306\");\r\n getMySQLUsername = configFile.getString(\"DataSource.mySQLUsername\",\"authme\");\r\n getMySQLPassword = configFile.getString(\"DataSource.mySQLPassword\",\"12345\");\r\n getMySQLDatabase = configFile.getString(\"DataSource.mySQLDatabase\",\"authme\");\r\n getMySQLTablename = configFile.getString(\"DataSource.mySQLTablename\",\"authme\");\r\n getMySQLColumnName = configFile.getString(\"DataSource.mySQLColumnName\",\"username\");\r\n getMySQLColumnPassword = configFile.getString(\"DataSource.mySQLColumnPassword\",\"password\");\r\n getMySQLColumnIp = configFile.getString(\"DataSource.mySQLColumnIp\",\"ip\");\r\n getMySQLColumnLastLogin = configFile.getString(\"DataSource.mySQLColumnLastLogin\",\"lastlogin\");\r\n getMySQLColumnSalt = configFile.getString(\"ExternalBoardOptions.mySQLColumnSalt\",\"\");\r\n getMySQLColumnGroup = configFile.getString(\"ExternalBoardOptions.mySQLColumnGroup\",\"\");\r\n getNonActivatedGroup = configFile.getInt(\"ExternalBoardOptions.nonActivedUserGroup\", -1);\r\n unRegisteredGroup = configFile.getString(\"GroupOptions.UnregisteredPlayerGroup\",\"\");\r\n getUnrestrictedName = configFile.getStringList(\"settings.unrestrictions.UnrestrictedName\");\r\n getRegisteredGroup = configFile.getString(\"GroupOptions.RegisteredPlayerGroup\",\"\"); \r\n getEnablePasswordVerifier = configFile.getBoolean(\"settings.restrictions.enablePasswordVerifier\" , true);\r\n protectInventoryBeforeLogInEnabled = configFile.getBoolean(\"settings.restrictions.ProtectInventoryBeforeLogIn\", true);\r\n passwordMaxLength = configFile.getInt(\"settings.security.passwordMaxLength\", 20);\r\n isBackupActivated = configFile.getBoolean(\"BackupSystem.ActivateBackup\",false);\r\n isBackupOnStart = configFile.getBoolean(\"BackupSystem.OnServerStart\",false);\r\n isBackupOnStop = configFile.getBoolean(\"BackupSystem.OnServeStop\",false); \r\n backupWindowsPath = configFile.getString(\"BackupSystem.MysqlWindowsPath\", \"C:\\\\Program Files\\\\MySQL\\\\MySQL Server 5.1\\\\\");\r\n enablePasspartu = configFile.getBoolean(\"Passpartu.enablePasspartu\",false);\r\n \r\n //System.out.println(getMySQLDatabase);\r\n \r\n \r\n }\r\n \r\n public void mergeConfig() {\r\n \r\n //options().copyDefaults(false);\r\n //System.out.println(\"merging config?\"+contains(\"settings.restrictions.ProtectInventoryBeforeLogIn\")+checkDefaults());\r\n if(!contains(\"settings.restrictions.ProtectInventoryBeforeLogIn\")) {\r\n set(\"settings.restrictions.enablePasswordVerifier\", true);\r\n set(\"settings.restrictions.ProtectInventoryBeforeLogIn\", true);\r\n } \r\n \r\n if(!contains(\"settings.security.passwordMaxLength\")) {\r\n set(\"settings.security.passwordMaxLength\", 20);\r\n }\r\n \r\n if(!contains(\"BackupSystem.ActivateBackup\")) {\r\n set(\"BackupSystem.ActivateBackup\",false);\r\n set(\"BackupSystem.OnServerStart\",false);\r\n set(\"BackupSystem.OnServeStop\",false);\r\n }\r\n \r\n \r\n if(!contains(\"BackupSystem.MysqlWindowsPath\")) {\r\n set(\"BackupSystem.MysqlWindowsPath\", \"C:\\\\Program Files\\\\MySQL\\\\MySQL Server 5.1\\\\\");\r\n }\r\n \r\n if(!contains(\"settings.messagesLanguage\")) {\r\n set(\"settings.messagesLanguage\",\"en\");\r\n }\r\n \r\n if(!contains(\"passpartu.enablePasspartu\")) {\r\n set(\"Passpartu.enablePasspartu\",false);\r\n } else return;\r\n \r\n plugin.getLogger().info(\"Merge new Config Options..\");\r\n plugin.saveConfig();\r\n \r\n return;\r\n }\r\n /** \r\n * \r\n * \r\n * \r\n */ \r\n private static HashAlgorithm getPasswordHash() {\r\n String key = \"settings.security.passwordHash\";\r\n\r\n try {\r\n return PasswordSecurity.HashAlgorithm.valueOf(configFile.getString(key,\"SHA256\").toUpperCase());\r\n } catch (IllegalArgumentException ex) {\r\n ConsoleLogger.showError(\"Unknown Hash Algorithm; defaulting to SHA256\");\r\n return PasswordSecurity.HashAlgorithm.SHA256;\r\n }\r\n }\r\n \r\n /** \r\n * \r\n * \r\n * \r\n */\r\n private static DataSourceType getDataSource() {\r\n String key = \"DataSource.backend\";\r\n\r\n try {\r\n return DataSource.DataSourceType.valueOf(configFile.getString(key).toUpperCase());\r\n } catch (IllegalArgumentException ex) {\r\n ConsoleLogger.showError(\"Unknown database backend; defaulting to file database\");\r\n return DataSource.DataSourceType.FILE;\r\n }\r\n }\r\n\r\n /**\r\n * Config option for setting and check restricted user by\r\n * username;ip , return false if ip and name doesnt amtch with\r\n * player that join the server, so player has a restricted access\r\n */ \r\n public static Boolean getRestrictedIp(String name, String ip) {\r\n \r\n Iterator<String> iter = getRestrictedIp.iterator();\r\n while (iter.hasNext()) {\r\n String[] args = iter.next().split(\";\");\r\n //System.out.println(\"name restricted \"+args[0]+\"name 2:\"+name+\"ip\"+args[1]+\"ip2\"+ip);\r\n if(args[0].equalsIgnoreCase(name) ) {\r\n if(args[1].equalsIgnoreCase(ip)) {\r\n //System.out.println(\"name restricted \"+args[0]+\"name 2:\"+name+\"ip\"+args[1]+\"ip2\"+ip);\r\n return true;\r\n } else return false;\r\n } \r\n }\r\n return true;\r\n }\r\n\r\n \r\n /**\r\n * Loads the configuration from disk\r\n *\r\n * @return True if loaded successfully\r\n */\r\n public final boolean load() {\r\n try {\r\n load(file);\r\n return true;\r\n } catch (Exception ex) {\r\n return false;\r\n }\r\n }\r\n \r\n public final void reload() {\r\n load();\r\n loadDefaults(file.getName());\r\n }\r\n\r\n /**\r\n * Saves the configuration to disk\r\n *\r\n * @return True if saved successfully\r\n */\r\n public final boolean save() {\r\n try {\r\n save(file);\r\n return true;\r\n } catch (Exception ex) {\r\n return false;\r\n }\r\n }\r\n\r\n /**\r\n * Simple function for if the Configuration file exists\r\n *\r\n * @return True if configuration exists on disk\r\n */\r\n public final boolean exists() {\r\n return file.exists();\r\n }\r\n\r\n /**\r\n * Loads a file from the plugin jar and sets as default\r\n *\r\n * @param filename The filename to open\r\n */\r\n public final void loadDefaults(String filename) {\r\n InputStream stream = plugin.getResource(filename);\r\n if(stream == null) return;\r\n\r\n setDefaults(YamlConfiguration.loadConfiguration(stream));\r\n }\r\n\r\n /**\r\n * Saves current configuration (plus defaults) to disk.\r\n *\r\n * If defaults and configuration are empty, saves blank file.\r\n *\r\n * @return True if saved successfully\r\n */\r\n public final boolean saveDefaults() {\r\n options().copyDefaults(true);\r\n options().copyHeader(true);\r\n boolean success = save();\r\n options().copyDefaults(false);\r\n options().copyHeader(false);\r\n\r\n return success;\r\n }\r\n\r\n\r\n /**\r\n * Clears current configuration defaults\r\n */\r\n public final void clearDefaults() {\r\n setDefaults(new MemoryConfiguration());\r\n }\r\n\r\n /**\r\n* Check loaded defaults against current configuration\r\n*\r\n* @return false When all defaults aren't present in config\r\n*/\r\n public boolean checkDefaults() {\r\n if (getDefaults() == null) {\r\n return true;\r\n }\r\n return getKeys(true).containsAll(getDefaults().getKeys(true));\r\n }\r\n /* \r\n public static Settings getInstance() {\r\n if (singleton == null) {\r\n singleton = new Settings();\r\n }\r\n return singleton;\r\n }\r\n*/\r\n public static String checkLang(String lang) {\r\n for(messagesLang language: messagesLang.values()) {\r\n //System.out.println(language.toString());\r\n if(lang.toLowerCase().contains(language.toString())) {\r\n ConsoleLogger.info(\"Set Language: \"+lang);\r\n return lang;\r\n } \r\n }\r\n ConsoleLogger.info(\"Set Default Language: En \");\r\n return \"en\";\r\n }\r\n \r\n public enum messagesLang {\r\n en, de, br, cz\r\n } \r\n}\r",
"public class TimeoutTask implements Runnable {\r\n\r\n private JavaPlugin plugin;\r\n private String name;\r\n private Messages m = Messages.getInstance();\r\n private Utils utils = Utils.getInstance();\r\n private FileCache playerCache = new FileCache();\r\n\r\n public TimeoutTask(JavaPlugin plugin, String name) {\r\n this.plugin = plugin;\r\n this.name = name;\r\n }\r\n\r\n public String getName() {\r\n return name;\r\n }\r\n\r\n @Override\r\n public void run() {\r\n if (PlayerCache.getInstance().isAuthenticated(name)) {\r\n return;\r\n }\r\n\r\n for (Player player : plugin.getServer().getOnlinePlayers()) {\r\n if (player.getName().toLowerCase().equals(name)) {\r\n if (LimboCache.getInstance().hasLimboPlayer(name)) {\r\n LimboPlayer inv = LimboCache.getInstance().getLimboPlayer(name);\r\n player.getServer().getScheduler().cancelTask(inv.getTimeoutTaskId());\r\n /*\r\n player.getInventory().setArmorContents(inv.getArmour());\r\n player.getInventory().setContents(inv.getInventory());\r\n utils.addNormal(player, inv.getGroup());\r\n player.setOp(inv.getOperator());\r\n //System.out.println(\"debug timout group reset \"+inv.getGroup());\r\n LimboCache.getInstance().deleteLimboPlayer(name); */\r\n if(playerCache.doesCacheExist(name)) {\r\n playerCache.removeCache(name);\r\n } \r\n } \r\n\r\n player.kickPlayer(m._(\"timeout\"));\r\n break;\r\n }\r\n }\r\n }\r\n}\r"
] | import java.security.NoSuchAlgorithmException;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitScheduler;
import uk.org.whoami.authme.ConsoleLogger;
import uk.org.whoami.authme.Utils;
import uk.org.whoami.authme.cache.auth.PlayerCache;
import uk.org.whoami.authme.cache.backup.FileCache;
import uk.org.whoami.authme.cache.limbo.LimboCache;
import uk.org.whoami.authme.datasource.DataSource;
import uk.org.whoami.authme.security.PasswordSecurity;
import uk.org.whoami.authme.settings.Messages;
import uk.org.whoami.authme.settings.Settings;
import uk.org.whoami.authme.task.MessageTask;
import uk.org.whoami.authme.task.TimeoutTask;
| /*
* Copyright 2011 Sebastian Köhler <[email protected]>.
*
* 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 uk.org.whoami.authme.commands;
public class UnregisterCommand implements CommandExecutor {
private Messages m = Messages.getInstance();
//private Settings settings = Settings.getInstance();
private JavaPlugin plugin;
private DataSource database;
private FileCache playerCache = new FileCache();
public UnregisterCommand(JavaPlugin plugin, DataSource database) {
this.plugin = plugin;
this.database = database;
}
@Override
public boolean onCommand(CommandSender sender, Command cmnd, String label, String[] args) {
if (!(sender instanceof Player)) {
return true;
}
if (!sender.hasPermission("authme." + label.toLowerCase())) {
sender.sendMessage(m._("no_perm"));
return true;
}
Player player = (Player) sender;
String name = player.getName().toLowerCase();
if (!PlayerCache.getInstance().isAuthenticated(name)) {
player.sendMessage(m._("not_logged_in"));
return true;
}
if (args.length != 1) {
player.sendMessage(m._("usage_unreg"));
return true;
}
try {
if (PasswordSecurity.comparePasswordWithHash(args[0], PlayerCache.getInstance().getAuth(name).getHash())) {
if (!database.removeAuth(name)) {
player.sendMessage("error");
return true;
}
if(Settings.isForcedRegistrationEnabled) {
player.getInventory().setArmorContents(new ItemStack[4]);
player.getInventory().setContents(new ItemStack[36]);
player.saveData();
PlayerCache.getInstance().removePlayer(player.getName().toLowerCase());
| LimboCache.getInstance().addLimboPlayer(player);
| 2 |
EXTER7/Substratum | src/main/java/exter/substratum/init/InitRecipes.java | [
"public class BlockOre extends Block implements IBlockVariants\n{\n\n public enum EnumVariant implements IStringSerializable\n {\n COPPER(EnumMaterial.COPPER,1),\n TIN(EnumMaterial.TIN,1),\n NICKEL(EnumMaterial.NICKEL,2),\n ZINC(EnumMaterial.ZINC,1),\n SILVER(EnumMaterial.SILVER,2),\n LEAD(EnumMaterial.LEAD,2),\n PLATINUM(EnumMaterial.PLATINUM,2),\n ALUMINA(EnumMaterial.ALUMINA,2),\n CHROMIUM(EnumMaterial.CHROMIUM,2);\n \n public final EnumMaterial material;\n public final int harvest_level;\n\n private EnumVariant(EnumMaterial material,int harvest_level)\n {\n this.material = material;\n this.harvest_level = harvest_level;\n }\n\n @Override\n public String getName()\n {\n return material.suffix_lc;\n }\n\n @Override\n public String toString()\n {\n return getName();\n }\n }\n\n public static final PropertyEnum<EnumVariant> VARIANT = PropertyEnum.create(\"variant\", EnumVariant.class);\n\n public BlockOre()\n {\n super(Material.ROCK);\n setHardness(3.0F);\n setResistance(5.0F);\n setSoundType(SoundType.STONE);\n setUnlocalizedName(\"substratum.ore\");\n setCreativeTab(TabMaterials.tab);\n setRegistryName(\"ore\");\n for(EnumVariant variant:EnumVariant.values())\n {\n setHarvestLevel(\"pickaxe\", variant.harvest_level, getDefaultState().withProperty(VARIANT, variant));\n }\n }\n\n @Override\n protected BlockStateContainer createBlockState()\n {\n return new BlockStateContainer(this, VARIANT);\n }\n\n @Override\n public IBlockState getStateFromMeta(int meta)\n {\n return getDefaultState().withProperty(VARIANT, EnumVariant.values()[meta]);\n }\n\n @Override\n public int getMetaFromState(IBlockState state)\n {\n return state.getValue(VARIANT).ordinal();\n }\n\n @Override\n public int damageDropped(IBlockState state)\n {\n return getMetaFromState(state);\n }\n \n @Override\n @SideOnly(Side.CLIENT)\n public void getSubBlocks(Item item, CreativeTabs tab, NonNullList<ItemStack> list)\n {\n for(EnumVariant ore:EnumVariant.values())\n {\n list.add(new ItemStack(item, 1, ore.ordinal()));\n }\n }\n \n public ItemStack asItemStack(EnumVariant ore)\n {\n return new ItemStack(this,1,ore.ordinal());\n }\n\n public IBlockState asState(EnumVariant ore)\n {\n return getDefaultState().withProperty(VARIANT, ore);\n }\n\n @Override\n public String getUnlocalizedName(int meta)\n {\n return String.format(\"%s_%s\", getUnlocalizedName(), getStateFromMeta(meta).getValue(VARIANT).material.suffix_lc);\n }\n}",
"public class SubstratumBlocks\n{\n private static final BlockMetal.Variant[] BLOCK1_METALS = \n {\n new BlockMetal.Variant(EnumMaterial.COPPER),\n new BlockMetal.Variant(EnumMaterial.TIN),\n new BlockMetal.Variant(EnumMaterial.BRONZE),\n new BlockMetal.Variant(EnumMaterial.ELECTRUM),\n new BlockMetal.Variant(EnumMaterial.INVAR),\n new BlockMetal.Variant(EnumMaterial.NICKEL),\n new BlockMetal.Variant(EnumMaterial.ZINC),\n new BlockMetal.Variant(EnumMaterial.BRASS),\n new BlockMetal.Variant(EnumMaterial.SILVER),\n new BlockMetal.Variant(EnumMaterial.STEEL),\n new BlockMetal.Variant(EnumMaterial.LEAD),\n new BlockMetal.Variant(EnumMaterial.PLATINUM),\n new BlockMetal.Variant(EnumMaterial.CUPRONICKEL),\n new BlockMetal.Variant(EnumMaterial.SIGNALUM),\n new BlockMetal.Variant(EnumMaterial.LUMIUM),\n };\n\n private static final BlockMetal.Variant[] BLOCK2_METALS = \n {\n new BlockMetal.Variant(EnumMaterial.ENDERIUM),\n new BlockMetal.Variant(EnumMaterial.ALUMINIUM),\n new BlockMetal.Variant(EnumMaterial.CHROMIUM)\n };\n\n private static final BlockMetalSlab.Variant[] SLAB1_METALS = \n {\n new BlockMetalSlab.Variant(EnumMaterial.IRON),\n new BlockMetalSlab.Variant(EnumMaterial.GOLD),\n new BlockMetalSlab.Variant(EnumMaterial.COPPER),\n new BlockMetalSlab.Variant(EnumMaterial.TIN),\n new BlockMetalSlab.Variant(EnumMaterial.BRONZE),\n new BlockMetalSlab.Variant(EnumMaterial.ELECTRUM),\n new BlockMetalSlab.Variant(EnumMaterial.INVAR),\n new BlockMetalSlab.Variant(EnumMaterial.NICKEL)\n };\n \n private static final BlockMetalSlab.Variant[] SLAB2_METALS = \n {\n new BlockMetalSlab.Variant(EnumMaterial.ZINC),\n new BlockMetalSlab.Variant(EnumMaterial.BRASS),\n new BlockMetalSlab.Variant(EnumMaterial.SILVER),\n new BlockMetalSlab.Variant(EnumMaterial.STEEL),\n new BlockMetalSlab.Variant(EnumMaterial.LEAD),\n new BlockMetalSlab.Variant(EnumMaterial.PLATINUM),\n new BlockMetalSlab.Variant(EnumMaterial.CUPRONICKEL),\n new BlockMetalSlab.Variant(EnumMaterial.SIGNALUM)\n };\n\n private static final BlockMetalSlab.Variant[] SLAB3_METALS = \n {\n new BlockMetalSlab.Variant(EnumMaterial.LUMIUM),\n new BlockMetalSlab.Variant(EnumMaterial.ENDERIUM),\n new BlockMetalSlab.Variant(EnumMaterial.ALUMINIUM),\n new BlockMetalSlab.Variant(EnumMaterial.CHROMIUM)\n };\n\n public static BlockMetal[] block_metal;\n public static BlockOre block_ore;\n public static BlockDustOre block_ore_dust;\n \n public static BlockMetalSlab[] block_slab;\n\n public static BlockMetalSlab[] block_slabdouble;\n \n// public static final Map<EnumMaterial,BlockMetalStairs> stairs_blocks = new EnumMap<String,BlockMetalStairs>();\n\n //All ores mapped by the metal name.\n public static final Map<EnumMaterial,ItemStack> ore_stacks = new EnumMap<EnumMaterial,ItemStack>(EnumMaterial.class);\n\n //All blocks mapped by the metal name.\n public static final Map<EnumMaterial,ItemStack> block_stacks = new EnumMap<EnumMaterial,ItemStack>(EnumMaterial.class);\n \n //All slabs mapped by the metal name.\n public static final Map<EnumMaterial,ItemStack> slab_stacks = new EnumMap<EnumMaterial,ItemStack>(EnumMaterial.class);\n\n //All stairs mapped by the metal name.\n public static final Map<EnumMaterial,ItemStack> stairs_stacks = new EnumMap<EnumMaterial,ItemStack>(EnumMaterial.class);\n\n\n static public void register(Block block)\n {\n GameRegistry.register(block);\n GameRegistry.register(new ItemBlock(block).setRegistryName(block.getRegistryName()));\n \n }\n\n static private <T extends Block & IBlockVariants>void registerMulti(T block)\n {\n GameRegistry.register(block);\n GameRegistry.register(new ItemBlockMulti(block).setRegistryName(block.getRegistryName()));\n }\n\n static private void registerSlab(BlockSlab block,BlockSlab slabdouble)\n {\n GameRegistry.register(block);\n GameRegistry.register(new ItemSlab(block,block,slabdouble).setRegistryName(block.getRegistryName())); \n }\n\n static private void registerHalfSlabs()\n {\n int i;\n block_slab = new BlockMetalSlab[3];\n block_slab[0] = new BlockMetalSlab(null,\"slab_1\") { @Override public Variant[] getVariants() { return SLAB1_METALS; } };\n block_slab[1] = new BlockMetalSlab(null,\"slab_2\") { @Override public Variant[] getVariants() { return SLAB2_METALS; } };\n block_slab[2] = new BlockMetalSlab(null,\"slab_3\") { @Override public Variant[] getVariants() { return SLAB3_METALS; } };\n\n block_slabdouble = new BlockMetalSlab[3];\n block_slabdouble[0] = new BlockMetalSlab(block_slab[0],\"slab_double_1\") {\n @Override public Variant[] getVariants() { return SLAB1_METALS; }\n @Override public IProperty<BlockMetalSlab.Variant> getVariantProperty() { return block_slab[0].getVariantProperty(); } };\n block_slabdouble[1] = new BlockMetalSlab(block_slab[1],\"slab_double_2\") {\n @Override public Variant[] getVariants() { return SLAB2_METALS; }\n @Override public IProperty<BlockMetalSlab.Variant> getVariantProperty() { return block_slab[1].getVariantProperty(); } };\n block_slabdouble[2] = new BlockMetalSlab(block_slab[2],\"slab_double_3\") {\n @Override public Variant[] getVariants() { return SLAB3_METALS; }\n @Override public IProperty<BlockMetalSlab.Variant> getVariantProperty() { return block_slab[2].getVariantProperty(); } };\n\n for(i = 0; i < block_slab.length; i++)\n {\n BlockSlab slab = block_slab[i];\n BlockSlab slabdouble = block_slabdouble[i];\n registerSlab(slab, slabdouble);\n registerSlab(slabdouble, slabdouble);\n for(BlockMetalSlab.Variant v:block_slab[i].getVariants())\n {\n IBlockState state = block_slab[i].getBottomVariant(v);\n ItemStack item = new ItemStack(block_slab[i],1,block_slab[i].getMetaFromState(state));\n slab_stacks.put(v.material, item);\n OreDictionary.registerOre(\"slab\" + v.material.suffix, item);\n if(v.material.suffix_alias != null)\n {\n OreDictionary.registerOre(\"slab\" + v.material.suffix_alias, item);\n }\n }\n }\n }\n \n static private void registerStairs(EnumMaterial material,IBlockState model_state)\n {\n BlockMetalStairs block = new BlockMetalStairs(model_state,material);\n register(block);\n ItemStack item = new ItemStack(block);\n stairs_stacks.put(material,item);\n OreDictionary.registerOre(\"stairs\" + material.suffix, item);\n if(material.suffix_alias != null)\n {\n OreDictionary.registerOre(\"stairs\" + material.suffix_alias, item);\n }\n }\n \n static public void registerBlocks()\n {\n int i;\n block_metal = new BlockMetal[2];\n block_metal[0] = new BlockMetal(\"block_metal_1\") { public Variant[] getVariants() { return BLOCK1_METALS; } };\n block_metal[1] = new BlockMetal(\"block_metal_2\") { public Variant[] getVariants() { return BLOCK2_METALS; } };\n block_ore = new BlockOre();\n block_ore_dust = new BlockDustOre();\n\n for(i = 0; i < block_metal.length; i++)\n {\n \n registerMulti(block_metal[i]);\n for(BlockMetal.Variant v:block_metal[i].getVariants())\n {\n IBlockState state = block_metal[i].getVariantState(v);\n ItemStack item = new ItemStack(block_metal[i],1,block_metal[i].getMetaFromState(state));\n block_stacks.put(v.material, item);\n OreDictionary.registerOre(\"block\" + v.material.suffix, item);\n if(v.material.suffix_alias != null)\n {\n OreDictionary.registerOre(\"block\" + v.material.suffix_alias, item);\n }\n registerStairs(v.material,state);\n }\n }\n\n registerMulti(block_ore);\n for(BlockOre.EnumVariant ore:BlockOre.EnumVariant.values())\n {\n ItemStack item = block_ore.asItemStack(ore);\n ore_stacks.put(ore.material, item);\n OreDictionary.registerOre(\"ore\" + ore.material.suffix, item);\n if(ore.material.suffix_alias != null)\n {\n OreDictionary.registerOre(\"ore\" + ore.material.suffix_alias, item);\n }\n }\n\n registerMulti(block_ore_dust);\n for(BlockDustOre.EnumVariant ore:BlockDustOre.EnumVariant.values())\n {\n ItemStack item = block_ore_dust.asItemStack(ore);\n ore_stacks.put(ore.material, item);\n OreDictionary.registerOre(\"ore\" + ore.material.suffix, item);\n if(ore.material.suffix_alias != null)\n {\n OreDictionary.registerOre(\"ore\" + ore.material.suffix_alias, item);\n }\n }\n\n registerHalfSlabs();\n \n registerStairs(EnumMaterial.IRON,Blocks.IRON_BLOCK.getDefaultState());\n registerStairs(EnumMaterial.GOLD,Blocks.GOLD_BLOCK.getDefaultState());\n }\n}",
"public class SubstratumConfig\n{\n static public class WorldgenConfig\n {\n public final boolean enabled;\n public final int min_y;\n public final int max_y;\n public final int min_frequency;\n public final int max_frequency;\n public final int cluster_size;\n\n public WorldgenConfig(Configuration config, String ore, int min_y, int max_y, int min_frequency, int max_frequency, int cluster_size)\n {\n String category = \"worldgen.\" + ore;\n this.enabled = config.getBoolean(\"enabled\", \"worldgen.\" + ore, true, \"Enable/disable worldgen for this ore.\");\n this.min_y = config.getInt(\"minY\", category, min_y, 0, 256, \"Lowest Y level the ore is generated.\");\n this.max_y = config.getInt(\"maxY\", category, max_y, 0, 256, \"Highest Y level the ore is generated.\");\n\n int minfreq = min_frequency;\n int maxfreq = max_frequency;\n \n if(config.hasKey(category, \"min_clusters\") && config.hasKey(category, \"max_clusters\"))\n {\n // Convert old cluster config to frequency config\n int minc = config.get(category, \"min_clusters\", min_frequency).getInt();\n int maxc = config.get(category, \"max_clusters\", max_frequency).getInt();\n minfreq = (int)Math.round((double)(minc * 1000) / (double)Math.abs(this.max_y - this.min_y));\n maxfreq = (int)Math.round((double)(maxc * 1000) / (double)Math.abs(this.max_y - this.min_y));\n }\n config.getCategory(category).remove(\"min_clusters\");\n config.getCategory(category).remove(\"max_clusters\");\n \n this.min_frequency = config.getInt(\"min_frequency\", category, minfreq, 1, 10000, \"Minimum ore frequency.\");\n this.max_frequency = config.getInt(\"max_frequency\", category, maxfreq, 1, 10000, \"Maximum ore frequency.\");\n \n this.cluster_size = config.getInt(\"cluster_size\", category, cluster_size, 1, 100, \"Size of ore cluster.\");\n }\n }\n \n static public class MaterialRecipeConfig\n {\n public final boolean dust_bottle;\n public final boolean gear_crafting;\n public final boolean plate_crafting;\n public final boolean dust_from_ingot;\n public final boolean rod_crafting;\n \n public final boolean ingot_from_plate;\n public final boolean ingots_from_gear;\n public final boolean ingot_from_dust;\n public final boolean dust_from_rod;\n public final boolean slab_from_blocks;\n public final boolean stairs_from_blocks;\n \n \n public final boolean tool_pickaxe;\n public final boolean tool_axe;\n public final boolean tool_shovel;\n public final boolean tool_hoe;\n public final boolean tool_sword;\n\n public final boolean armor_helmet;\n public final boolean armor_chestplate;\n public final boolean armor_leggings;\n public final boolean armor_boots;\n\n \n static private boolean hasIngot(EnumMaterial material)\n {\n return EnumMaterialItem.INGOT.materials.contains(material) || material == EnumMaterial.IRON || material == EnumMaterial.GOLD;\n }\n \n public MaterialRecipeConfig(Configuration config,EnumMaterial material)\n {\n String name = material.suffix_lc;\n String category = \"recipes.\" + name;\n if(EnumMaterialItem.DUST.materials.contains(material) && material != EnumMaterial.SULFUR && material != EnumMaterial.NITER)\n {\n String property = hasIngot(material) ? \"dust_from_ingot\" : \"dust_from_item\";\n dust_from_ingot = config.getBoolean(property, category, true, \"Enable/disable \" + name + \" dust with mortar crafting recipe.\");\n } else\n {\n dust_from_ingot = false;\n }\n\n if(EnumMaterialItem.BOTTLE_DUST.materials.contains(material))\n {\n config.renameProperty(category, \"dust_bucket\", \"dust_bottle\");\n dust_bottle = config.getBoolean(\"dust_bottle\", category, true, \"Enable/disable \" + name + \" dust bottle recipes.\");\n } else\n {\n dust_bottle = false;\n }\n\n if(hasIngot(material))\n {\n ingot_from_dust = config.getBoolean(\"ingot_from_dust\", \"recipes.\" + name, true, \"Enable/disable \" + name + \" dust to ingot smelting recipe.\");\n } else\n {\n ingot_from_dust = false;\n }\n \n if(EnumMaterialItem.PLATE.materials.contains(material))\n {\n plate_crafting = config.getBoolean(\"plate_crafting\", \"recipes.\" + name, true, \"Enable/disable \" + name + \" plate crafting recipe.\");\n ingot_from_plate = config.getBoolean(\"ingot_from_plate\", \"recipes.\" + name, true, \"Enable/disable \" + name + \" plate to ingot smelting recipe.\");\n } else\n {\n plate_crafting = false;\n ingot_from_plate = false;\n }\n \n if(EnumMaterialItem.GEAR.materials.contains(material))\n {\n gear_crafting = config.getBoolean(\"gear_crafting\", \"recipes.\" + name, true, \"Enable/disable \" + name + \" gear crafting recipe.\");\n ingots_from_gear = config.getBoolean(\"ingots_from_gear\", \"recipes.\" + name, true, \"Enable/disable \" + name + \" gear to ingot smelting recipe.\");\n } else\n {\n gear_crafting = false;\n ingots_from_gear = false;\n }\n \n if(EnumMaterialItem.ROD.materials.contains(material))\n {\n rod_crafting = config.getBoolean(\"rod_crafting\", \"recipes.\" + name, true, \"Enable/disable \" + name + \" rod crafting recipe.\");\n dust_from_rod = config.getBoolean(\"dust_from_rod\", \"recipes.\" + name, true, \"Enable/disable \" + name + \" rod to dusts mortar crafting recipe.\");\n } else\n {\n rod_crafting = false;\n dust_from_rod = false;\n }\n\n if(SubstratumBlocks.slab_stacks.containsKey(material))\n {\n slab_from_blocks = config.getBoolean(\"slab_from_blocks\", \"recipes.\" + name, true, \"Enable/disable \" + name + \" slab crafting recipe.\");\n } else\n {\n slab_from_blocks = false;\n }\n\n if(SubstratumBlocks.stairs_stacks.containsKey(material))\n {\n stairs_from_blocks = config.getBoolean(\"stairs_from_blocks\", \"recipes.\" + name, true, \"Enable/disable \" + name + \" stairs crafting recipe.\");\n } else\n {\n stairs_from_blocks = false;\n }\n\n Set<EnumMaterial> equipment_materials = EnumMaterialEquipment.getMaterials();\n \n if(equipment_materials.contains(material))\n {\n tool_pickaxe = config.getBoolean(\"pickaxe\", \"equipment.\" + name, true, \"Enable/disable \" + name + \" pickaxe.\");\n tool_axe = config.getBoolean(\"axe\", \"equipment.\" + name, true, \"Enable/disable \" + name + \" axe.\");\n tool_shovel = config.getBoolean(\"shovel\", \"equipment.\" + name, true, \"Enable/disable \" + name + \" shovel.\");\n tool_hoe = config.getBoolean(\"hoe\", \"equipment.\" + name, true, \"Enable/disable \" + name + \" hoe.\");\n tool_sword = config.getBoolean(\"sword\", \"equipment.\" + name, true, \"Enable/disable \" + name + \" sword.\");\n\n armor_helmet = config.getBoolean(\"helmet\", \"equipment.\" + name, true, \"Enable/disable \" + name + \" helmet.\");\n armor_chestplate = config.getBoolean(\"chestplate\", \"equipment.\" + name, true, \"Enable/disable \" + name + \" chestplate.\");\n armor_leggings = config.getBoolean(\"leggings\", \"equipment.\" + name, true, \"Enable/disable \" + name + \" leggings.\");\n armor_boots = config.getBoolean(\"boots\", \"equipment.\" + name, true, \"Enable/disable \" + name + \" boots.\");\n } else\n {\n tool_pickaxe = false;\n tool_axe = false;\n tool_shovel = false;\n tool_hoe = false;\n tool_sword = false;\n\n armor_helmet = false;\n armor_chestplate = false;\n armor_leggings = false;\n armor_boots = false;\n }\n }\n }\n \n static public enum AluminiumRecipe\n {\n NONE,\n NORMAL,\n CHEAP\n }\n \n public static WorldgenConfig worldgen_copper;\n public static WorldgenConfig worldgen_tin;\n public static WorldgenConfig worldgen_zinc;\n public static WorldgenConfig worldgen_nickel;\n public static WorldgenConfig worldgen_silver;\n public static WorldgenConfig worldgen_lead;\n public static WorldgenConfig worldgen_platinum;\n public static WorldgenConfig worldgen_alumina;\n public static WorldgenConfig worldgen_chromium;\n\n public static WorldgenConfig worldgen_sulfur;\n public static WorldgenConfig worldgen_niter;\n\n public static boolean blend_bronze_enable;\n public static boolean blend_brass_enable;\n public static boolean blend_invar_enable;\n public static boolean blend_electrum_enable;\n public static boolean blend_cupronickel_enable;\n\n public static boolean blend_steel_enable;\n public static boolean blend_signalum_enable;\n public static boolean blend_lumium_enable;\n public static boolean blend_enderium_enable;\n\n public static boolean blend_gunpowder_enable;\n \n\n public static boolean cheaper_plate_recipes;\n public static boolean cheaper_rod_recipes;\n public static boolean cheaper_gear_recipes;\n \n public static AluminiumRecipe aluminium_recipe;\n \n public static Map<EnumMaterial,MaterialRecipeConfig> material_recipes = new EnumMap<EnumMaterial,MaterialRecipeConfig>(EnumMaterial.class);\n\n public static int misc_mortar_uses;\n\n public static boolean dye_enabled;\n\n static public void load(Configuration config)\n {\n worldgen_copper = new WorldgenConfig(config, \"copper\", 20, 80, 167, 333, 7); \n worldgen_tin = new WorldgenConfig(config, \"tin\", 20, 52, 188, 375, 7);\n worldgen_zinc = new WorldgenConfig(config, \"zinc\", 8, 48, 175, 175, 7); \n worldgen_nickel = new WorldgenConfig(config, \"nickel\", 8, 36, 107, 214, 7);\n worldgen_silver = new WorldgenConfig(config, \"silver\", 8, 30, 136, 182, 7);\n worldgen_lead = new WorldgenConfig(config, \"lead\", 8, 48, 125, 150, 7);\n worldgen_platinum = new WorldgenConfig(config, \"platinum\", 2, 12, 100, 150, 3);\n worldgen_alumina = new WorldgenConfig(config, \"alumina\", 16, 32, 125, 312, 7);\n worldgen_chromium = new WorldgenConfig(config, \"chromium\", 8, 24, 100, 150, 5);\n \n worldgen_sulfur = new WorldgenConfig(config, \"sulfur\", 5, 123, 127, 169, 7);\n worldgen_niter = new WorldgenConfig(config, \"niter\", 5, 123, 85, 127, 7);\n\n blend_bronze_enable = config.getBoolean(\"blend\", \"recipes.bronze\", true, \"Enable/disable bronze dust blending recipe.\");\n blend_brass_enable = config.getBoolean(\"blend\", \"recipes.brass\", true, \"Enable/disable brass dust blending recipe.\");\n blend_invar_enable = config.getBoolean(\"blend\", \"recipes.invar\", true, \"Enable/disable invar dust blending recipe.\");\n blend_electrum_enable = config.getBoolean(\"blend\", \"recipes.electrum\", true, \"Enable/disable electrum dust blending recipe.\");\n blend_cupronickel_enable = config.getBoolean(\"blend\", \"recipes.cupronickel\", true, \"Enable/disable cupronickel dust blending recipe.\");\n\n blend_steel_enable = config.getBoolean(\"blend\", \"recipes.steel\", false, \"Enable/disable steel dust blending recipe.\");\n blend_signalum_enable = config.getBoolean(\"blend\", \"recipes.signalum\", true, \"Enable/disable signalum dust blending recipe.\");\n blend_lumium_enable = config.getBoolean(\"blend\", \"recipes.lumium\", true, \"Enable/disable lumium dust blending recipe.\");\n blend_enderium_enable = config.getBoolean(\"blend\", \"recipes.enderium\", true, \"Enable/disable enderium dust blending recipe.\");\n\n blend_gunpowder_enable = config.getBoolean(\"blend\", \"recipes.gunpowder\", true, \"Enable/disable gunpowder dust blending recipe.\");\n\n config.renameProperty(\"recipes.aluminium\", \"ingot_from_alumina\", \"nugget_from_alumina\");\n boolean alumina_nugget_smelting = config.getBoolean(\"nugget_from_alumina\", \"recipes.aluminium\", true, \"\");\n config.getCategory(\"recipes.aluminium\").remove(\"nugget_from_alumina\");\n \n aluminium_recipe = AluminiumRecipe.values()[config.getInt(\"recipe_from_alumina\", \"recipes.aluminium\", alumina_nugget_smelting?1:0,0,2, \"Recipe for making aluminium from alumina:\\n\"\n + \"0 = No recipe (aluminium cannot be made without another mod adding a way to make it).\\n\"\n + \"1 = Normal recipe (1 alumina dust/ore -> 3 aluminium nuggets in a furnace).\\n\"\n + \"2 = Cheaper recipe (1 alumina dust/ore -> 1 aluminium ingot in a furnace).\\n\")];\n \n misc_mortar_uses = config.getInt(\"mortar_uses\", \"misc\", 20, 0, 1000, \"How many uses the mortar has unti it breaks. Setting this to 0 disables the item.\");\n dye_enabled = config.getBoolean(\"enabled\", \"dyes\", true, \"Enable/disable dye powders.\");\n\n cheaper_plate_recipes = config.getBoolean(\"cheaper_plate_recipes\", \"recipes.balance\", false, \"Require less materials to make plates.\");\n cheaper_rod_recipes = config.getBoolean(\"cheaper_rod_recipes\", \"recipes.balance\", false, \"Require less materials to make rods.\");\n cheaper_gear_recipes = config.getBoolean(\"cheaper_gear_recipes\", \"recipes.balance\", false, \"Require less materials to make gears.\");\n\n for(EnumMaterial mat:EnumMaterial.values())\n {\n if(mat != EnumMaterial.NULL)\n {\n material_recipes.put(mat, new MaterialRecipeConfig(config,mat));\n }\n }\n }\n}",
"public class SubstratumItems\n{\n static private class MaterialItem\n {\n public final EnumMaterialItem item;\n public final EnumMaterial material;\n\n public MaterialItem(EnumMaterialItem item, EnumMaterial material)\n {\n this.item = item;\n this.material = material;\n }\n \n @Override\n public int hashCode()\n {\n return item.ordinal() * 256 + material.ordinal();\n }\n \n @Override\n public boolean equals(Object obj)\n {\n if(this == obj)\n {\n return true;\n }\n if(obj == null)\n {\n return false;\n }\n if(getClass() != obj.getClass())\n {\n return false;\n }\n MaterialItem other = (MaterialItem) obj;\n if(item != other.item)\n {\n return false;\n }\n if(material != other.material)\n {\n return false;\n }\n return true;\n }\n }\n\n static public Map<EnumMaterialItem,ItemMaterial> item_materials = new EnumMap<EnumMaterialItem,ItemMaterial>(EnumMaterialItem.class);\n\n static public ItemMortar item_mortar = null;\n \n static public ItemDyePowder item_dye_powder = null;\n static public ItemDyePowderSmall item_dye_powder_small = null;\n \n static private Map<MaterialItem,ItemStack> vanilla_items;\n \n \n static public Map<EnumMaterial,ItemPickaxeSubstratum> pickaxes = new EnumMap<EnumMaterial,ItemPickaxeSubstratum>(EnumMaterial.class);\n static public Map<EnumMaterial,ItemAxeSubstratum> axes = new EnumMap<EnumMaterial,ItemAxeSubstratum>(EnumMaterial.class);\n static public Map<EnumMaterial,ItemShovelSubstratum> shovels = new EnumMap<EnumMaterial,ItemShovelSubstratum>(EnumMaterial.class);\n static public Map<EnumMaterial,ItemHoeSubstratum> hoes = new EnumMap<EnumMaterial,ItemHoeSubstratum>(EnumMaterial.class);\n static public Map<EnumMaterial,ItemSwordSubstratum> swords = new EnumMap<EnumMaterial,ItemSwordSubstratum>(EnumMaterial.class);\n \n static public Map<EnumMaterial,ItemArmorSubstratum> helmets = new EnumMap<EnumMaterial,ItemArmorSubstratum>(EnumMaterial.class);\n static public Map<EnumMaterial,ItemArmorSubstratum> chestplates = new EnumMap<EnumMaterial,ItemArmorSubstratum>(EnumMaterial.class);\n static public Map<EnumMaterial,ItemArmorSubstratum> leggings = new EnumMap<EnumMaterial,ItemArmorSubstratum>(EnumMaterial.class);\n static public Map<EnumMaterial,ItemArmorSubstratum> boots = new EnumMap<EnumMaterial,ItemArmorSubstratum>(EnumMaterial.class);\n \n static public void registerItems(Configuration config)\n {\n for(EnumMaterialItem matitem:EnumMaterialItem.values())\n {\n ItemMaterial item = new ItemMaterial(matitem);\n item_materials.put(matitem, item);\n GameRegistry.register(item);\n for(EnumMaterial mat:matitem.materials)\n {\n mat.registerItemInOreDictionary(item.getStack(mat), matitem.prefix);\n }\n }\n item_materials.get(EnumMaterialItem.BOTTLE_DUST).setContainerItem(Items.GLASS_BOTTLE);\n item_materials.get(EnumMaterialItem.BUCKET_LIQUID).setSpecialHandler(new BucketSpecialHandler()).setContainerItem(Items.BUCKET).setMaxStackSize(1);\n item_materials.get(EnumMaterialItem.BOTTLE_LIQUID).setSpecialHandler(new FluidSpecialHandler(Fluid.BUCKET_VOLUME / 4)).setContainerItem(Items.GLASS_BOTTLE);\n SubstratumItems.item_materials.get(EnumMaterialItem.BUCKET_LIQUID);\n \n \n if(SubstratumConfig.misc_mortar_uses > 0)\n {\n item_mortar = new ItemMortar(SubstratumConfig.misc_mortar_uses);\n GameRegistry.register(item_mortar);\n }\n \n if(SubstratumConfig.dye_enabled)\n {\n item_dye_powder = new ItemDyePowder();\n item_dye_powder_small = new ItemDyePowderSmall();\n \n GameRegistry.register(item_dye_powder);\n GameRegistry.register(item_dye_powder_small);\n \n for(EnumDyePowderColor color:EnumDyePowderColor.values())\n {\n OreDictionary.registerOre(color.oredict, item_dye_powder.getStack(color));\n OreDictionary.registerOre(color.oredict_small, item_dye_powder_small.getStack(color));\n OreDictionary.registerOre(color.oredict_dust, item_dye_powder.getStack(color));\n OreDictionary.registerOre(color.oredict_dust_small, item_dye_powder_small.getStack(color));\n }\n }\n OreDictionary.registerOre(\"dustGunpowder\", new ItemStack(Items.GUNPOWDER));\n OreDictionary.registerOre(\"dustBlaze\", new ItemStack(Items.BLAZE_POWDER));\n vanilla_items = new HashMap<MaterialItem,ItemStack>();\n vanilla_items.put(new MaterialItem(EnumMaterialItem.INGOT, EnumMaterial.IRON), new ItemStack(Items.IRON_INGOT));\n vanilla_items.put(new MaterialItem(EnumMaterialItem.INGOT, EnumMaterial.GOLD), new ItemStack(Items.GOLD_INGOT));\n vanilla_items.put(new MaterialItem(EnumMaterialItem.NUGGET, EnumMaterial.GOLD), new ItemStack(Items.GOLD_NUGGET));\n vanilla_items.put(new MaterialItem(EnumMaterialItem.NUGGET, EnumMaterial.IRON), new ItemStack(Items.field_191525_da/*IRON_NUGGET*/));\n vanilla_items.put(new MaterialItem(EnumMaterialItem.DUST, EnumMaterial.REDSTONE), new ItemStack(Items.REDSTONE));\n vanilla_items.put(new MaterialItem(EnumMaterialItem.DUST, EnumMaterial.GLOWSTONE), new ItemStack(Items.GLOWSTONE_DUST));\n vanilla_items.put(new MaterialItem(EnumMaterialItem.DUST, EnumMaterial.GUNPOWDER), new ItemStack(Items.GUNPOWDER));\n vanilla_items.put(new MaterialItem(EnumMaterialItem.DUST, EnumMaterial.BLAZE), new ItemStack(Items.BLAZE_POWDER));\n \n\n for(EnumMaterialEquipment equipment:EnumMaterialEquipment.values())\n {\n equipment.tool.setRepairItem(getStack(EnumMaterialItem.INGOT,equipment.material));\n MaterialRecipeConfig mat_config = SubstratumConfig.material_recipes.get(equipment.material);\n if(mat_config.tool_pickaxe)\n {\n ItemPickaxeSubstratum item = new ItemPickaxeSubstratum(equipment);\n GameRegistry.register(item);\n pickaxes.put(equipment.material, item);\n equipment.material.registerItemInOreDictionary(new ItemStack(item,1,0), \"pickaxe\");\n }\n if(mat_config.tool_axe)\n {\n ItemAxeSubstratum item = new ItemAxeSubstratum(equipment);\n GameRegistry.register(item);\n axes.put(equipment.material, item);\n equipment.material.registerItemInOreDictionary(new ItemStack(item,1,0), \"axe\");\n }\n if(mat_config.tool_shovel)\n {\n ItemShovelSubstratum item = new ItemShovelSubstratum(equipment);\n GameRegistry.register(item);\n shovels.put(equipment.material, item);\n equipment.material.registerItemInOreDictionary(new ItemStack(item,1,0), \"shovel\");\n }\n if(mat_config.tool_hoe)\n {\n ItemHoeSubstratum item = new ItemHoeSubstratum(equipment);\n GameRegistry.register(item);\n hoes.put(equipment.material, item);\n equipment.material.registerItemInOreDictionary(new ItemStack(item,1,0), \"hoe\");\n }\n if(mat_config.tool_sword)\n {\n ItemSwordSubstratum item = new ItemSwordSubstratum(equipment);\n GameRegistry.register(item);\n swords.put(equipment.material, item);\n equipment.material.registerItemInOreDictionary(new ItemStack(item,1,0), \"sword\");\n }\n\n if(mat_config.armor_helmet)\n {\n ItemArmorSubstratum item = new ItemArmorSubstratum(equipment,EntityEquipmentSlot.HEAD);\n GameRegistry.register(item);\n helmets.put(equipment.material, item);\n equipment.material.registerItemInOreDictionary(new ItemStack(item,1,0), \"helmet\");\n }\n if(mat_config.armor_chestplate)\n {\n ItemArmorSubstratum item = new ItemArmorSubstratum(equipment,EntityEquipmentSlot.CHEST);\n GameRegistry.register(item);\n chestplates.put(equipment.material, item);\n equipment.material.registerItemInOreDictionary(new ItemStack(item,1,0), \"chestplate\");\n }\n if(mat_config.armor_leggings)\n {\n ItemArmorSubstratum item = new ItemArmorSubstratum(equipment,EntityEquipmentSlot.LEGS);\n GameRegistry.register(item); \n leggings.put(equipment.material, item);\n equipment.material.registerItemInOreDictionary(new ItemStack(item,1,0), \"leggings\");\n }\n if(mat_config.armor_boots)\n {\n ItemArmorSubstratum item = new ItemArmorSubstratum(equipment,EntityEquipmentSlot.FEET);\n GameRegistry.register(item);\n boots.put(equipment.material, item);\n equipment.material.registerItemInOreDictionary(new ItemStack(item,1,0), \"boots\");\n }\n }\n }\n\n\n static public ItemStack getStack(EnumMaterialItem item, EnumMaterial material)\n {\n return getStack(item, material, 1, true);\n }\n\n static public ItemStack getStack(EnumMaterialItem item, EnumMaterial material,int amount)\n {\n return getStack(item, material, amount, true);\n }\n\n static public ItemStack getStack(EnumMaterialItem item, EnumMaterial material, boolean vanilla)\n {\n return getStack(item, material, 1, vanilla);\n }\n\n static public ItemStack getStack(EnumMaterialItem item, EnumMaterial material,int amount, boolean vanilla)\n {\n if(material == EnumMaterial.NULL)\n {\n return null;\n }\n if(vanilla)\n {\n ItemStack stack = vanilla_items.get(new MaterialItem(item, material));\n if(stack != null)\n {\n stack = stack.copy();\n stack.setCount(amount);\n return stack;\n }\n }\n\n // Deprecate Iron Nugget TODO: Remove in later versions\n if(item == EnumMaterialItem.NUGGET && material == EnumMaterial.IRON)\n {\n return null;\n }\n\n return item_materials.get(item).getStack(material, amount);\n }\n}",
"public enum EnumDyePowderColor\n{\n BLACK(\"Black\",EnumDyeColor.BLACK),\n RED(\"Red\",EnumDyeColor.RED),\n GREEN(\"Green\",EnumDyeColor.GREEN),\n BROWN(\"Brown\",EnumDyeColor.BROWN),\n BLUE(\"Blue\",EnumDyeColor.BLUE),\n PURPLE(\"Purple\",EnumDyeColor.PURPLE),\n CYAN(\"Cyan\",EnumDyeColor.CYAN),\n LIGHT_GRAY(\"LightGray\",EnumDyeColor.SILVER),\n GRAY(\"Gray\",EnumDyeColor.GRAY),\n PINK(\"Pink\",EnumDyeColor.PINK),\n LIME(\"Lime\",EnumDyeColor.LIME),\n YELLOW(\"Yellow\",EnumDyeColor.YELLOW),\n LIGHT_BLUE(\"LightBlue\",EnumDyeColor.LIGHT_BLUE),\n MAGENTA(\"Magenta\",EnumDyeColor.MAGENTA),\n ORANGE(\"Orange\",EnumDyeColor.ORANGE),\n WHITE(\"White\",EnumDyeColor.WHITE);\n \n public final String name;\n public final String oredict;\n public final String oredict_small;\n public final String oredict_dust;\n public final String oredict_dust_small;\n public final String name_lc;\n public final EnumDyeColor dye;\n \n EnumDyePowderColor(String name,EnumDyeColor dye)\n {\n this.name = name;\n this.oredict = \"dye\" + name;\n this.oredict_small = \"dyeSmall\" + name;\n this.oredict_dust = \"dustDye\" + name;\n this.oredict_dust_small = \"dustSmallDye\" + name;\n this.dye = dye;\n this.name_lc = SubstratumUtils.convertToRegistryName(name);\n }\n}",
"public enum EnumMaterial\n{\n NULL(null),\n STONE(\"Stone\"),\n COAL(\"Coal\"),\n CHARCOAL(\"Charcoal\"),\n IRON(\"Iron\"),\n GOLD(\"Gold\"),\n COPPER(\"Copper\"),\n TIN(\"Tin\"),\n BRONZE(\"Bronze\"),\n ELECTRUM(\"Electrum\"),\n INVAR(\"Invar\"),\n NICKEL(\"Nickel\"),\n ZINC(\"Zinc\"),\n BRASS(\"Brass\"),\n SILVER(\"Silver\"),\n STEEL(\"Steel\"),\n LEAD(\"Lead\"),\n PLATINUM(\"Platinum\"),\n CUPRONICKEL(\"Cupronickel\", \"Constantan\"),\n REDSTONE(\"Redstone\"),\n GLOWSTONE(\"Glowstone\"),\n ENDERPEARL(\"Enderpearl\"),\n SIGNALUM(\"Signalum\"),\n LUMIUM(\"Lumium\"),\n ENDERIUM(\"Enderium\"),\n SULFUR(\"Sulfur\"),\n NITER(\"Niter\"),\n GUNPOWDER(\"Gunpowder\"),\n OBSIDIAN(\"Obsidian\"),\n BLAZE(\"Blaze\"),\n ALUMINA(\"Alumina\"),\n ALUMINIUM(\"Aluminium\", \"Aluminum\"),\n CHROMIUM(\"Chrome\", \"Chromium\");\n \n public final String suffix;\n\n public final String suffix_alias;\n\n public final String suffix_lc;\n \n public void registerItemInOreDictionary(ItemStack item,String prefix)\n {\n if(suffix != null)\n {\n OreDictionary.registerOre(prefix + suffix, item);\n }\n if(suffix_alias != null)\n {\n OreDictionary.registerOre(prefix + suffix_alias, item);\n }\n }\n\n EnumMaterial(String suffix)\n {\n this.suffix = suffix;\n this.suffix_alias = null;\n this.suffix_lc = SubstratumUtils.convertToRegistryName(suffix);\n }\n\n EnumMaterial(String suffix, String suffix_alias)\n {\n this.suffix = suffix;\n this.suffix_alias = suffix_alias;\n this.suffix_lc = SubstratumUtils.convertToRegistryName(suffix);\n }\n}",
"public enum EnumMaterialItem\n{\n INGOT(\"ingot\",ImmutableList.of(\n EnumMaterial.COPPER,\n EnumMaterial.TIN,\n EnumMaterial.BRONZE,\n EnumMaterial.ELECTRUM,\n EnumMaterial.INVAR,\n EnumMaterial.NICKEL,\n EnumMaterial.ZINC,\n EnumMaterial.BRASS,\n EnumMaterial.SILVER,\n EnumMaterial.STEEL,\n EnumMaterial.LEAD,\n EnumMaterial.PLATINUM,\n EnumMaterial.CUPRONICKEL,\n EnumMaterial.SIGNALUM,\n EnumMaterial.LUMIUM,\n EnumMaterial.ENDERIUM,\n EnumMaterial.NULL,\n EnumMaterial.ALUMINIUM,\n EnumMaterial.CHROMIUM)),\n \n DUST(\"dust\",ImmutableList.of(\n EnumMaterial.COAL,\n EnumMaterial.IRON,\n EnumMaterial.GOLD,\n EnumMaterial.COPPER,\n EnumMaterial.TIN,\n EnumMaterial.BRONZE,\n EnumMaterial.ELECTRUM,\n EnumMaterial.INVAR,\n EnumMaterial.NICKEL,\n EnumMaterial.ZINC,\n EnumMaterial.BRASS,\n EnumMaterial.SILVER,\n EnumMaterial.STEEL,\n EnumMaterial.LEAD,\n EnumMaterial.PLATINUM,\n EnumMaterial.CUPRONICKEL,\n EnumMaterial.ENDERPEARL,\n EnumMaterial.SIGNALUM,\n EnumMaterial.LUMIUM,\n EnumMaterial.ENDERIUM,\n EnumMaterial.CHARCOAL,\n EnumMaterial.OBSIDIAN,\n EnumMaterial.SULFUR,\n EnumMaterial.NITER,\n EnumMaterial.ALUMINA,\n EnumMaterial.ALUMINIUM,\n EnumMaterial.CHROMIUM)),\n \n NUGGET(\"nugget\",ImmutableList.of(\n EnumMaterial.IRON,\n EnumMaterial.COPPER,\n EnumMaterial.TIN,\n EnumMaterial.BRONZE,\n EnumMaterial.ELECTRUM,\n EnumMaterial.INVAR,\n EnumMaterial.NICKEL,\n EnumMaterial.ZINC,\n EnumMaterial.BRASS,\n EnumMaterial.SILVER,\n EnumMaterial.STEEL,\n EnumMaterial.LEAD,\n EnumMaterial.PLATINUM,\n EnumMaterial.CUPRONICKEL,\n EnumMaterial.SIGNALUM,\n EnumMaterial.LUMIUM,\n EnumMaterial.ENDERIUM,\n EnumMaterial.NULL,\n EnumMaterial.ALUMINIUM,\n EnumMaterial.CHROMIUM)),\n\n //1 gear = 4 ingots\n GEAR(\"gear\",ImmutableList.of(\n EnumMaterial.STONE,\n EnumMaterial.IRON,\n EnumMaterial.GOLD,\n EnumMaterial.COPPER,\n EnumMaterial.TIN,\n EnumMaterial.BRONZE,\n EnumMaterial.ELECTRUM,\n EnumMaterial.INVAR,\n EnumMaterial.NICKEL,\n EnumMaterial.ZINC,\n EnumMaterial.BRASS,\n EnumMaterial.SILVER,\n EnumMaterial.STEEL,\n EnumMaterial.LEAD,\n EnumMaterial.PLATINUM,\n EnumMaterial.CUPRONICKEL,\n EnumMaterial.SIGNALUM,\n EnumMaterial.LUMIUM,\n EnumMaterial.ENDERIUM,\n EnumMaterial.ALUMINIUM,\n EnumMaterial.CHROMIUM)),\n\n //1 plate = 1 ingot\n PLATE(\"plate\",ImmutableList.of(\n EnumMaterial.IRON,\n EnumMaterial.GOLD,\n EnumMaterial.COPPER,\n EnumMaterial.TIN,\n EnumMaterial.BRONZE,\n EnumMaterial.ELECTRUM,\n EnumMaterial.INVAR,\n EnumMaterial.NICKEL,\n EnumMaterial.ZINC,\n EnumMaterial.BRASS,\n EnumMaterial.SILVER,\n EnumMaterial.STEEL,\n EnumMaterial.LEAD,\n EnumMaterial.PLATINUM,\n EnumMaterial.CUPRONICKEL,\n EnumMaterial.SIGNALUM,\n EnumMaterial.LUMIUM,\n EnumMaterial.ENDERIUM,\n EnumMaterial.ALUMINIUM,\n EnumMaterial.CHROMIUM)), \n \n BOTTLE_DUST(\"bottleDust\", ImmutableList.of(\n EnumMaterial.REDSTONE,\n EnumMaterial.GLOWSTONE,\n EnumMaterial.ENDERPEARL)),\n\n BUCKET_LIQUID(\"bucketLiquid\", ImmutableList.of(\n EnumMaterial.REDSTONE,\n EnumMaterial.GLOWSTONE,\n EnumMaterial.ENDERPEARL)),\n\n //4 bottles = 1 bucket\n BOTTLE_LIQUID(\"bottleLiquid\", ImmutableList.of(\n EnumMaterial.REDSTONE,\n EnumMaterial.GLOWSTONE,\n EnumMaterial.ENDERPEARL)),\n\n //2 rods = 1 ingot\n ROD(\"rod\",ImmutableList.of(\n EnumMaterial.IRON,\n EnumMaterial.GOLD,\n EnumMaterial.COPPER,\n EnumMaterial.TIN,\n EnumMaterial.BRONZE,\n EnumMaterial.ELECTRUM,\n EnumMaterial.INVAR,\n EnumMaterial.NICKEL,\n EnumMaterial.ZINC,\n EnumMaterial.BRASS,\n EnumMaterial.SILVER,\n EnumMaterial.STEEL,\n EnumMaterial.LEAD,\n EnumMaterial.PLATINUM,\n EnumMaterial.CUPRONICKEL,\n EnumMaterial.SIGNALUM,\n EnumMaterial.LUMIUM,\n EnumMaterial.ENDERIUM,\n EnumMaterial.ALUMINIUM,\n EnumMaterial.CHROMIUM)),\n \n //4 small dust = 1 dust\n DUST_SMALL(\"dustSmall\",ImmutableList.of(\n EnumMaterial.COAL,\n EnumMaterial.IRON,\n EnumMaterial.GOLD,\n EnumMaterial.COPPER,\n EnumMaterial.TIN,\n EnumMaterial.BRONZE,\n EnumMaterial.ELECTRUM,\n EnumMaterial.INVAR,\n EnumMaterial.NICKEL,\n EnumMaterial.ZINC,\n EnumMaterial.BRASS,\n EnumMaterial.SILVER,\n EnumMaterial.STEEL,\n EnumMaterial.LEAD,\n EnumMaterial.PLATINUM,\n EnumMaterial.CUPRONICKEL,\n EnumMaterial.ENDERPEARL,\n EnumMaterial.SIGNALUM,\n EnumMaterial.LUMIUM,\n EnumMaterial.ENDERIUM,\n EnumMaterial.CHARCOAL,\n EnumMaterial.OBSIDIAN,\n EnumMaterial.SULFUR,\n EnumMaterial.NITER,\n EnumMaterial.GUNPOWDER,\n EnumMaterial.BLAZE,\n EnumMaterial.REDSTONE,\n EnumMaterial.GLOWSTONE,\n EnumMaterial.ALUMINA,\n EnumMaterial.ALUMINIUM,\n EnumMaterial.CHROMIUM));\n \n public final ImmutableList<EnumMaterial> materials;\n public final String prefix;\n public final String prefix_lc;\n\n EnumMaterialItem(String prefix, ImmutableList<EnumMaterial> materials)\n {\n this.materials = materials;\n this.prefix = prefix;\n this.prefix_lc = SubstratumUtils.convertToRegistryName(prefix);\n }\n}"
] | import java.util.Map;
import exter.substratum.block.BlockOre;
import exter.substratum.block.SubstratumBlocks;
import exter.substratum.config.SubstratumConfig;
import exter.substratum.item.SubstratumItems;
import exter.substratum.material.EnumDyePowderColor;
import exter.substratum.material.EnumMaterial;
import exter.substratum.material.EnumMaterialItem;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.oredict.OreDictionary;
import net.minecraftforge.oredict.ShapedOreRecipe;
import net.minecraftforge.oredict.ShapelessOreRecipe; | package exter.substratum.init;
public class InitRecipes
{
static private void addDyeMix(EnumDyePowderColor result,String... ingredients)
{
Object[] ing_oredict = new Object[ingredients.length];
for(int i = 0; i < ingredients.length; i++)
{
ing_oredict[i] = "dustDye" + ingredients[i];
}
GameRegistry.addRecipe(new ShapelessOreRecipe(
SubstratumItems.item_dye_powder.getStack(result,ingredients.length),
ing_oredict));
for(int i = 0; i < ingredients.length; i++)
{
ing_oredict[i] = "dustSmallDye" + ingredients[i];
}
GameRegistry.addRecipe(new ShapelessOreRecipe(
SubstratumItems.item_dye_powder_small.getStack(result,ingredients.length),
ing_oredict));
}
static public void init()
{
InitBlendRecipes.init();
InitEquipmentRecipes.init();
switch(SubstratumConfig.aluminium_recipe)
{
case NONE:
break;
case NORMAL:
GameRegistry.addSmelting( | SubstratumItems.getStack(EnumMaterialItem.DUST,EnumMaterial.ALUMINA), | 6 |
OpenCryptoProject/JCMathLib | JCMathLibTests/test/JCMathLibTests.java | [
"public class ECExample extends Applet {\n ECConfig ecc = null;\n ECCurve curve = null;\n ECPoint point1 = null;\n ECPoint point2 = null;\n \n final static byte[] ECPOINT_TEST_VALUE = {(byte)0x04, (byte) 0x3B, (byte) 0xC1, (byte) 0x5B, (byte) 0xE5, (byte) 0xF7, (byte) 0x52, (byte) 0xB3, (byte) 0x27, (byte) 0x0D, (byte) 0xB0, (byte) 0xAE, (byte) 0xF2, (byte) 0xBC, (byte) 0xF0, (byte) 0xEC, (byte) 0xBD, (byte) 0xB5, (byte) 0x78, (byte) 0x8F, (byte) 0x88, (byte) 0xE6, (byte) 0x14, (byte) 0x32, (byte) 0x30, (byte) 0x68, (byte) 0xC4, (byte) 0xC4, (byte) 0x88, (byte) 0x6B, (byte) 0x43, (byte) 0x91, (byte) 0x4C, (byte) 0x22, (byte) 0xE1, (byte) 0x67, (byte) 0x68, (byte) 0x3B, (byte) 0x32, (byte) 0x95, (byte) 0x98, (byte) 0x31, (byte) 0x19, (byte) 0x6D, (byte) 0x41, (byte) 0x88, (byte) 0x0C, (byte) 0x9F, (byte) 0x8C, (byte) 0x59, (byte) 0x67, (byte) 0x60, (byte) 0x86, (byte) 0x1A, (byte) 0x86, (byte) 0xF8, (byte) 0x0D, (byte) 0x01, (byte) 0x46, (byte) 0x0C, (byte) 0xB5, (byte) 0x8D, (byte) 0x86, (byte) 0x6C, (byte) 0x09};\n final static byte[] SCALAR_TEST_VALUE = {(byte) 0xE8, (byte) 0x05, (byte) 0xE8, (byte) 0x02, (byte) 0xBF, (byte) 0xEC, (byte) 0xEE, (byte) 0x91, (byte) 0x9B, (byte) 0x3D, (byte) 0x3B, (byte) 0xD8, (byte) 0x3C, (byte) 0x7B, (byte) 0x52, (byte) 0xA5, (byte) 0xD5, (byte) 0x35, (byte) 0x4C, (byte) 0x4C, (byte) 0x06, (byte) 0x89, (byte) 0x80, (byte) 0x54, (byte) 0xB9, (byte) 0x76, (byte) 0xFA, (byte) 0xB1, (byte) 0xD3, (byte) 0x5A, (byte) 0x10, (byte) 0x91};\n\n public ECExample() {\n OperationSupport.getInstance().setCard(OperationSupport.SIMULATOR); // TODO set your card\n // Pre-allocate all helper structures\n ecc = new ECConfig((short) 256); \n // Pre-allocate standard SecP256r1 curve and two EC points on this curve\n curve = new ECCurve(false, SecP256r1.p, SecP256r1.a, SecP256r1.b, SecP256r1.G, SecP256r1.r);\n point1 = new ECPoint(curve, ecc.ech);\n point2 = new ECPoint(curve, ecc.ech);\n }\n \n public static void install(byte[] bArray, short bOffset, byte bLength) {\n new ECExample().register();\n }\n\n public boolean select() {\n ecc.refreshAfterReset();\n return true;\n }\n \n public void process(APDU apdu) {\n if (selectingApplet()) { return; }\n // NOTE: very simple EC usage example - no cla/ins, no communication with host... \n point1.randomize(); // Generate first point at random\n point2.setW(ECPOINT_TEST_VALUE, (short) 0, (short) ECPOINT_TEST_VALUE.length); // Set second point to predefined value\n point1.add(point2); // Add two points together \n point1.multiplication(SCALAR_TEST_VALUE, (short) 0, (short) SCALAR_TEST_VALUE.length); // Multiply point by large scalar\n }\n}",
"public class CardManager {\n boolean m_bDebug = false;\n byte[] m_APPLET_AID = null;\n Long m_lastTransmitTime = (long) 0;\n CommandAPDU m_lastCommand = null;\n CardChannel m_channel = null;\n \n public CardManager(boolean bDebug, byte[] appletAID) {\n this.m_bDebug = bDebug;\n this.m_APPLET_AID = appletAID;\n }\n \n // Card Logistics\n public boolean Connect(RunConfig runCfg) throws Exception {\n boolean bConnected = false;\n switch (runCfg.testCardType) {\n case PHYSICAL: {\n m_channel = ConnectPhysicalCard(runCfg.targetReaderIndex);\n break;\n }\n case JCOPSIM: {\n m_channel = ConnectJCOPSimulator(runCfg.targetReaderIndex);\n break;\n }\n case JCARDSIMLOCAL: {\n m_channel = ConnectJCardSimLocalSimulator(runCfg.appletToSimulate);\n break;\n }\n case JCARDSIMREMOTE: {\n m_channel = null; // Not implemented yet\n break;\n }\n default:\n m_channel = null;\n bConnected = false;\n \n }\n if (m_channel != null) {\n bConnected = true;\n }\n return bConnected;\n }\n \n public void Disconnect(boolean bReset) throws CardException {\n m_channel.getCard().disconnect(bReset); // Disconnect from the card\n }\n\n public CardChannel ConnectPhysicalCard(int targetReaderIndex) throws Exception {\n // JCOP Simulators\n System.out.print(\"Looking for physical cards... \");\n return connectToCardByTerminalFactory(TerminalFactory.getDefault(), targetReaderIndex);\n }\n\n public CardChannel ConnectJCOPSimulator(int targetReaderIndex) throws Exception {\n // JCOP Simulators\n System.out.print(\"Looking for JCOP simulators...\");\n int[] ports = new int[]{8050};\n return connectToCardByTerminalFactory(TerminalFactory.getInstance(\"JcopEmulator\", ports), targetReaderIndex);\n }\n\n private CardChannel ConnectJCardSimLocalSimulator(Class appletClass) throws Exception {\n System.setProperty(\"com.licel.jcardsim.terminal.type\", \"2\");\n CAD cad = new CAD(System.getProperties());\n JavaxSmartCardInterface simulator = (JavaxSmartCardInterface) cad.getCardInterface();\n byte[] installData = new byte[0];\n AID appletAID = new AID(m_APPLET_AID, (short) 0, (byte) m_APPLET_AID.length);\n\n AID appletAIDRes = simulator.installApplet(appletAID, appletClass, installData, (short) 0, (byte) installData.length);\n simulator.selectApplet(appletAID);\n\n return new SimulatedCardChannelLocal(simulator);\n }\n\n private CardChannel connectToCardByTerminalFactory(TerminalFactory factory, int targetReaderIndex) throws CardException {\n List<CardTerminal> terminals = new ArrayList<>();\n\n boolean card_found = false;\n CardTerminal terminal = null;\n Card card = null;\n try {\n for (CardTerminal t : factory.terminals().list()) {\n terminals.add(t);\n if (t.isCardPresent()) {\n card_found = true;\n }\n }\n System.out.println(\"Success.\");\n } catch (Exception e) {\n System.out.println(\"Failed.\");\n }\n\n if (card_found) {\n System.out.println(\"Cards found: \" + terminals);\n\n terminal = terminals.get(targetReaderIndex); // Prioritize physical card over simulations\n\n System.out.print(\"Connecting...\");\n card = terminal.connect(\"*\"); // Connect with the card\n\n System.out.println(\" Done.\");\n\n System.out.print(\"Establishing channel...\");\n m_channel = card.getBasicChannel();\n\n System.out.println(\" Done.\");\n\n // Select applet (mpcapplet)\n System.out.println(\"Smartcard: Selecting applet...\");\n\n CommandAPDU cmd = new CommandAPDU(0x00, 0xa4, 0x04, 0x00, m_APPLET_AID);\n ResponseAPDU response = transmit(cmd);\n } else {\n System.out.print(\"Failed to find physical card.\");\n }\n\n if (card != null) {\n return card.getBasicChannel();\n } else {\n return null;\n }\n }\n \n public ResponseAPDU transmit(CommandAPDU cmd)\n throws CardException {\n\n m_lastCommand = cmd;\n if (m_bDebug == true) {\n log(cmd);\n }\n\n long elapsed = -System.currentTimeMillis();\n ResponseAPDU response = m_channel.transmit(cmd);\n elapsed += System.currentTimeMillis();\n m_lastTransmitTime = elapsed;\n\n if (m_bDebug == true) {\n log(response, m_lastTransmitTime);\n }\n\n return response;\n }\n\n private void log(CommandAPDU cmd) {\n System.out.printf(\"--> %s\\n\", Util.toHex(cmd.getBytes()),\n cmd.getBytes().length);\n }\n\n private void log(ResponseAPDU response, long time) {\n String swStr = String.format(\"%02X\", response.getSW());\n byte[] data = response.getData();\n if (data.length > 0) {\n System.out.printf(\"<-- %s %s (%d) [%d ms]\\n\", Util.toHex(data), swStr,\n data.length, time);\n } else {\n System.out.printf(\"<-- %s [%d ms]\\n\", swStr, time);\n }\n }\n\n private void log(ResponseAPDU response) {\n log(response, 0);\n }\n\n private Card waitForCard(CardTerminals terminals)\n throws CardException {\n while (true) {\n for (CardTerminal ct : terminals\n .list(CardTerminals.State.CARD_INSERTION)) {\n\n return ct.connect(\"*\");\n }\n terminals.waitForChange();\n }\n }\n \n}",
"public class PerfTests {\n public static HashMap<Short, String> PERF_STOP_MAPPING = new HashMap<>();\n public static byte[] PERF_COMMAND = {OCUnitTests.CLA_OC_UT, OCUnitTests.INS_PERF_SETSTOP, 0, 0, 2, 0, 0};\n public static byte[] APDU_RESET = {(byte) 0xB0, (byte) 0x03, (byte) 0x00, (byte) 0x00};\n public static final byte[] PERF_COMMAND_NONE = {OCUnitTests.CLA_OC_UT, OCUnitTests.INS_PERF_SETSTOP, 0, 0, 2, 0, 0};\n \n static final String PERF_TRAP_CALL = \"PM.check(PM.\";\n static final String PERF_TRAP_CALL_END = \");\";\n \n boolean MODIFY_SOURCE_FILES_BY_PERF = true;\n\n class PerfConfig {\n public String cardName = \"noCardName\";\n public FileOutputStream perfFile = null;\n public ArrayList<Entry<String, Long>> perfResultsSingleOp = new ArrayList<>();\n public ArrayList<String> perfResultsSubparts = new ArrayList<>();\n public HashMap<Short, Entry<Short, Long>> perfResultsSubpartsRaw = new HashMap<>(); // hashmap with key being perf trap id, folowed by pair <prevTrapID, elapsedTimeFromPrev>\n public boolean bMeasurePerf = true;\n public short[] perfStops = null;\n public short perfStopComplete = -1;\n public ArrayList<String> failedPerfTraps = new ArrayList<>();\n } \n\n PerfTests() {\n buildPerfMapping(); \n }\n \n void printOperationAverageTime(String opName, RunConfig runCfg, PerfConfig perfCfg) {\n if (runCfg.bMeasureOnlyTargetOp) {\n long avgOpTimeFirst = 0;\n long avgOpTimeSecond = 0;\n // Compute average for first stop\n \n System.out.println(String.format(\"Average time: %d\", avgOpTimeSecond - avgOpTimeFirst));\n }\n }\n void RunPerformanceTests(RunConfig runCfg) throws Exception {\n PerfConfig cfg = new PerfConfig();\n cfg.cardName = \"gd60\";\n String experimentID = String.format(\"%d\", System.currentTimeMillis());\n cfg.perfFile = new FileOutputStream(String.format(\"OC_PERF_log_%s.csv\", experimentID));\n\n try {\n CardManager cardMngr = new CardManager(true, TestClient.OPENCRYPTO_UNITTEST_APPLET_AID);\n System.out.print(\"Connecting to card...\");\n runCfg.testCardType = RunConfig.CARD_TYPE.JCARDSIMLOCAL;\n //runCfg.testCardType = RunConfig.CARD_TYPE.PHYSICAL;\n cardMngr.Connect(runCfg);\n System.out.println(\" Done.\");\n\n cardMngr.transmit(new CommandAPDU(PERF_COMMAND_NONE)); // erase any previous performance stop \n cardMngr.transmit(new CommandAPDU(APDU_RESET));\n\n byte[] bogusArray = new byte[1]; // Bogus array with single zero byte - NXP J3H145G P60 fails when no data are provided\n\n if (runCfg.bTestBN) {\n short[] PERFSTOPS_BigNatural_Addition = {PM.TRAP_BN_ADD_1, PM.TRAP_BN_ADD_2, PM.TRAP_BN_ADD_3, PM.TRAP_BN_ADD_4, PM.TRAP_BN_ADD_5, PM.TRAP_BN_ADD_6, PM.TRAP_BN_ADD_7, PM.TRAP_BN_ADD_COMPLETE};\n short[] PERFSTOPS_BigNatural_Addition_onlyTarget = {PM.TRAP_BN_ADD_6, PM.TRAP_BN_ADD_7};\n cfg.perfStops = runCfg.bMeasureOnlyTargetOp ? PERFSTOPS_BigNatural_Addition_onlyTarget : PERFSTOPS_BigNatural_Addition;\n cfg.perfStopComplete = PM.TRAP_BN_ADD_COMPLETE;\n long avgOpTime = 0;\n String opName = \"BigNatural Addition: \";\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n BigInteger num1 = Util.randomBigNat(runCfg.bnBaseTestLength - 1);//Generate Int1\n BigInteger num2 = Util.randomBigNat(runCfg.bnBaseTestLength - 1);//Generate Int2\n CommandAPDU cmd = new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_BN_ADD, num1.toByteArray().length, 0, Util.concat(num1.toByteArray(), num2.toByteArray()));\n avgOpTime += PerfAnalyzeCommand(opName, cmd, cardMngr, cfg);\n }\n printOperationAverageTime(opName, runCfg, cfg);\n System.out.println(String.format(\"%s: average time: %d\", opName, avgOpTime / runCfg.numRepeats));\n \n short[] PERFSTOPS_BigNatural_Subtraction = {PM.TRAP_BN_SUB_1, PM.TRAP_BN_SUB_2, PM.TRAP_BN_SUB_3, PM.TRAP_BN_SUB_4, PM.TRAP_BN_SUB_5, PM.TRAP_BN_SUB_6, PM.TRAP_BN_SUB_7, PM.TRAP_BN_SUB_COMPLETE};\n short[] PERFSTOPS_BigNatural_Subtraction_onlyTarget = {PM.TRAP_BN_SUB_6, PM.TRAP_BN_SUB_7};\n cfg.perfStops = runCfg.bMeasureOnlyTargetOp ? PERFSTOPS_BigNatural_Subtraction_onlyTarget : PERFSTOPS_BigNatural_Subtraction;\n cfg.perfStopComplete = PM.TRAP_BN_SUB_COMPLETE;\n avgOpTime = 0;\n opName = \"BigNatural Subtraction: \";\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n BigInteger num1 = Util.randomBigNat(runCfg.bnBaseTestLength);//Generate Int1\n BigInteger num2 = Util.randomBigNat(runCfg.bnBaseTestLength - 1);//Generate Int2\n CommandAPDU cmd = new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_BN_SUB, num1.toByteArray().length, 0, Util.concat(num1.toByteArray(), num2.toByteArray()));\n avgOpTime += PerfAnalyzeCommand(opName, cmd, cardMngr, cfg);\n }\n System.out.println(String.format(\"%s: average time: %d\", opName, avgOpTime / runCfg.numRepeats));\n\n short[] PERFSTOPS_BigNatural_Multiplication = {PM.TRAP_BN_MUL_1, PM.TRAP_BN_MUL_2, PM.TRAP_BN_MUL_3, PM.TRAP_BN_MUL_4, PM.TRAP_BN_MUL_5, PM.TRAP_BN_MUL_6, PM.TRAP_BN_MUL_COMPLETE};\n short[] PERFSTOPS_BigNatural_Multiplication_onlyTarget = {PM.TRAP_BN_MUL_5, PM.TRAP_BN_MUL_6};\n cfg.perfStops = runCfg.bMeasureOnlyTargetOp ? PERFSTOPS_BigNatural_Multiplication_onlyTarget : PERFSTOPS_BigNatural_Multiplication;\n cfg.perfStopComplete = PM.TRAP_BN_MUL_COMPLETE;\n avgOpTime = 0;\n opName = \"BigNatural Multiplication: \";\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n BigInteger num1 = Util.randomBigNat(runCfg.bnBaseTestLength / 2);//Generate Int1\n BigInteger num2 = Util.randomBigNat(runCfg.bnBaseTestLength / 2);//Generate Int2\n CommandAPDU cmd = new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_BN_MUL, num1.toByteArray().length, 0, Util.concat(num1.toByteArray(), num2.toByteArray()));\n avgOpTime += PerfAnalyzeCommand(opName, cmd, cardMngr, cfg);\n }\n System.out.println(String.format(\"%s: average time: %d\", opName, avgOpTime / runCfg.numRepeats));\n \n \n short[] PERFSTOPS_Bignat_sqrt = {PM.TRAP_BIGNAT_SQRT_1, PM.TRAP_BIGNAT_SQRT_2, PM.TRAP_BIGNAT_SQRT_3, PM.TRAP_BIGNAT_SQRT_4, PM.TRAP_BIGNAT_SQRT_5, PM.TRAP_BIGNAT_SQRT_6, PM.TRAP_BIGNAT_SQRT_7, PM.TRAP_BIGNAT_SQRT_8, PM.TRAP_BIGNAT_SQRT_9, PM.TRAP_BIGNAT_SQRT_10, PM.TRAP_BIGNAT_SQRT_11, PM.TRAP_BIGNAT_SQRT_12, PM.TRAP_BIGNAT_SQRT_13, PM.TRAP_BIGNAT_SQRT_14, PM.TRAP_BIGNAT_SQRT_15, PM.TRAP_BIGNAT_SQRT_COMPLETE};\n short[] PERFSTOPS_Bignat_sqrt_onlyTarget = {PM.TRAP_BIGNAT_SQRT_1, PM.TRAP_BIGNAT_SQRT_2, PM.TRAP_BIGNAT_SQRT_3, PM.TRAP_BIGNAT_SQRT_4, PM.TRAP_BIGNAT_SQRT_5, PM.TRAP_BIGNAT_SQRT_6, PM.TRAP_BIGNAT_SQRT_7, PM.TRAP_BIGNAT_SQRT_8, PM.TRAP_BIGNAT_SQRT_9, PM.TRAP_BIGNAT_SQRT_10, PM.TRAP_BIGNAT_SQRT_11, PM.TRAP_BIGNAT_SQRT_12, PM.TRAP_BIGNAT_SQRT_13, PM.TRAP_BIGNAT_SQRT_14, PM.TRAP_BIGNAT_SQRT_15, PM.TRAP_BIGNAT_SQRT_COMPLETE};\n cfg.perfStops = runCfg.bMeasureOnlyTargetOp ? PERFSTOPS_Bignat_sqrt_onlyTarget : PERFSTOPS_Bignat_sqrt;\n cfg.perfStopComplete = PM.TRAP_BIGNAT_SQRT_COMPLETE;\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n BigInteger num = Util.randomBigNat(runCfg.bnBaseTestLength);//Generate Int\n CommandAPDU cmd = new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_BN_SQRT, num.toByteArray().length, 0, num.toByteArray());\n PerfAnalyzeCommand(\"Bignat_sqrt_FP: \", cmd, cardMngr, cfg);\n }\n\n short[] PERFSTOPS_BigNatural_Storage = {PM.TRAP_BN_STR_1, PM.TRAP_BN_STR_2, PM.TRAP_BN_STR_3, PM.TRAP_BN_STR_COMPLETE};\n cfg.perfStops = PERFSTOPS_BigNatural_Storage;\n cfg.perfStopComplete = PM.TRAP_BN_STR_COMPLETE;\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n BigInteger num = Util.randomBigNat(runCfg.bnBaseTestLength / 2);//Generate Int\n CommandAPDU cmd = new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_BN_STR, 0, 0, num.toByteArray());\n PerfAnalyzeCommand(\"BigNatural Storage: \", cmd, cardMngr, cfg);\n }\n\n\n short[] PERFSTOPS_BigNatural_Exponentiation = {PM.TRAP_BN_EXP_1, PM.TRAP_BN_EXP_2, PM.TRAP_BN_EXP_3, PM.TRAP_BN_EXP_4, PM.TRAP_BN_EXP_5, PM.TRAP_BN_EXP_6, PM.TRAP_BN_EXP_COMPLETE};\n cfg.perfStops = PERFSTOPS_BigNatural_Exponentiation;\n cfg.perfStopComplete = PM.TRAP_BN_EXP_COMPLETE;\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n BigInteger num1 = BigInteger.valueOf(14); //Generate Int1\t\t\n BigInteger num2 = BigInteger.valueOf(8); //Generate Int2\n CommandAPDU cmd = new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_BN_EXP, num1.toByteArray().length, 0, Util.concat(num1.toByteArray(), num2.toByteArray()));\n PerfAnalyzeCommand(\"BigNatural Exponentiation: \", cmd, cardMngr, cfg);\n }\n\n short[] PERFSTOPS_BigNatural_Modulo = {PM.TRAP_BN_MOD_1, PM.TRAP_BN_MOD_2, PM.TRAP_BN_MOD_3, PM.TRAP_BN_MOD_4, PM.TRAP_BN_MOD_5, PM.TRAP_BN_MOD_COMPLETE};\n cfg.perfStops = PERFSTOPS_BigNatural_Modulo;\n cfg.perfStopComplete = PM.TRAP_BN_MOD_COMPLETE;\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n BigInteger num1 = Util.randomBigNat(runCfg.bnBaseTestLength);//Generate Int1\n BigInteger num2 = Util.randomBigNat(runCfg.bnBaseTestLength - 1);//Generate Int2\n CommandAPDU cmd = new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_BN_MOD, (num1.toByteArray()).length, 0, Util.concat((num1.toByteArray()), (num2.toByteArray())));\n PerfAnalyzeCommand(\"BigNatural Modulo: \", cmd, cardMngr, cfg);\n }\n\n short[] PERFSTOPS_BigNatural_Addition__Modulo_ = {PM.TRAP_BN_ADD_MOD_1, PM.TRAP_BN_ADD_MOD_2, PM.TRAP_BN_ADD_MOD_3, PM.TRAP_BN_ADD_MOD_4, PM.TRAP_BN_ADD_MOD_5, PM.TRAP_BN_ADD_MOD_6, PM.TRAP_BN_ADD_MOD_7, PM.TRAP_BN_ADD_MOD_COMPLETE};\n cfg.perfStops = PERFSTOPS_BigNatural_Addition__Modulo_;\n cfg.perfStopComplete = PM.TRAP_BN_ADD_MOD_COMPLETE;\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n BigInteger num1 = Util.randomBigNat(runCfg.bnBaseTestLength);//Generate Int1\n BigInteger num2 = Util.randomBigNat(runCfg.bnBaseTestLength);//Generate Int2\n BigInteger num3 = Util.randomBigNat(runCfg.bnBaseTestLength / 8);//Generate Int3\n CommandAPDU cmd = new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_BN_ADD_MOD, (num1.toByteArray()).length, (num2.toByteArray()).length, Util.concat((num1.toByteArray()), (num2.toByteArray()), (num3.toByteArray())));\n PerfAnalyzeCommand(\"BigNatural Addition (Modulo): \", cmd, cardMngr, cfg);\n }\n\n short[] PERFSTOPS_BigNatural_Subtraction__Modulo_ = {PM.TRAP_BN_SUB_MOD_1, PM.TRAP_BN_SUB_MOD_2, PM.TRAP_BN_SUB_MOD_3, PM.TRAP_BN_SUB_MOD_4, PM.TRAP_BN_SUB_MOD_5, PM.TRAP_BN_SUB_MOD_6, PM.TRAP_BN_SUB_MOD_COMPLETE};\n cfg.perfStops = PERFSTOPS_BigNatural_Subtraction__Modulo_;\n cfg.perfStopComplete = PM.TRAP_BN_SUB_MOD_COMPLETE;\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n BigInteger num1 = Util.randomBigNat(runCfg.bnBaseTestLength / 2);//Generate Int1\n BigInteger num2 = Util.randomBigNat(runCfg.bnBaseTestLength);//Generate Int2\n BigInteger num3 = Util.randomBigNat(runCfg.bnBaseTestLength / 8);//Generate Int3\n CommandAPDU cmd = new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_BN_SUB_MOD, (num1.toByteArray()).length, (num2.toByteArray()).length, Util.concat((num1.toByteArray()), (num2.toByteArray()), (num3.toByteArray())));\n PerfAnalyzeCommand(\"BigNatural Subtraction (Modulo): \", cmd, cardMngr, cfg);\n }\n\n short[] PERFSTOPS_BigNatural_Multiplication__Modulo_ = {PM.TRAP_BN_MUL_MOD_1, PM.TRAP_BN_MUL_MOD_2, PM.TRAP_BN_MUL_MOD_3, PM.TRAP_BN_MUL_MOD_4, PM.TRAP_BN_MUL_MOD_5, PM.TRAP_BN_MUL_MOD_6, PM.TRAP_BN_MUL_MOD_COMPLETE};\n cfg.perfStops = PERFSTOPS_BigNatural_Multiplication__Modulo_;\n cfg.perfStopComplete = PM.TRAP_BN_MUL_MOD_COMPLETE;\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n BigInteger num1 = Util.randomBigNat(runCfg.bnBaseTestLength / 2);//Generate Int1\n BigInteger num2 = Util.randomBigNat(runCfg.bnBaseTestLength / 2);//Generate Int2\n BigInteger num3 = Util.randomBigNat(runCfg.bnBaseTestLength / 8);//Generate Int3\n CommandAPDU cmd = new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_BN_MUL_MOD, (num1.toByteArray()).length, (num2.toByteArray()).length, Util.concat((num1.toByteArray()), (num2.toByteArray()), (num3.toByteArray())));\n PerfAnalyzeCommand(\"BigNatural Multiplication (Modulo): \", cmd, cardMngr, cfg);\n }\n\n short[] PERFSTOPS_BigNatural_Exponentiation__Modulo_ = {PM.TRAP_BN_EXP_MOD_1, PM.TRAP_BN_EXP_MOD_2, PM.TRAP_BN_EXP_MOD_3, PM.TRAP_BN_EXP_MOD_4, PM.TRAP_BN_EXP_MOD_5, PM.TRAP_BN_EXP_MOD_6, PM.TRAP_BN_EXP_MOD_COMPLETE};\n cfg.perfStops = PERFSTOPS_BigNatural_Exponentiation__Modulo_;\n cfg.perfStopComplete = PM.TRAP_BN_EXP_MOD_COMPLETE;\n int power = 2;\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n BigInteger num1 = Util.randomBigNat(runCfg.bnBaseTestLength); //Generate Int1 (base)\n BigInteger num2 = BigInteger.valueOf(power); //Generate Int2 (exp)\n BigInteger num3 = Util.randomBigNat(runCfg.bnBaseTestLength);//Generate Int3 (mod)\n CommandAPDU cmd = new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_BN_EXP_MOD, Util.trimLeadingZeroes(num1.toByteArray()).length, Util.trimLeadingZeroes(num2.toByteArray()).length, Util.concat(Util.trimLeadingZeroes(num1.toByteArray()), Util.trimLeadingZeroes(num2.toByteArray()), Util.trimLeadingZeroes(num3.toByteArray())));\n PerfAnalyzeCommand(\"BigNatural Exponentiation (Modulo): \", cmd, cardMngr, cfg);\n }\n\n short[] PERFSTOPS_BigNatural_Pow2__Modulo_ = {PM.TRAP_BN_POW2_MOD_1, PM.TRAP_BN_POW2_MOD_2, PM.TRAP_BN_POW2_MOD_3, PM.TRAP_BN_POW2_COMPLETE};\n cfg.perfStops = PERFSTOPS_BigNatural_Pow2__Modulo_;\n cfg.perfStopComplete = PM.TRAP_BN_POW2_COMPLETE;\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n BigInteger num1 = Util.randomBigNat(runCfg.bnBaseTestLength); //Generate Int1 (base)\n BigInteger mod = Util.randomBigNat(runCfg.bnBaseTestLength);//Generate Int3 (mod)\n CommandAPDU cmd = new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_BN_POW2_MOD, Util.trimLeadingZeroes(num1.toByteArray()).length, Util.trimLeadingZeroes(mod.toByteArray()).length, Util.concat(Util.trimLeadingZeroes(num1.toByteArray()), Util.trimLeadingZeroes(mod.toByteArray())));\n PerfAnalyzeCommand(\"BigNatural Power2 (Modulo): \", cmd, cardMngr, cfg);\n }\n\n short[] PERFSTOPS_BigNatural_Inversion__Modulo_ = {PM.TRAP_BN_INV_MOD_1, PM.TRAP_BN_INV_MOD_2, PM.TRAP_BN_INV_MOD_3, PM.TRAP_BN_INV_MOD_4, PM.TRAP_BN_INV_MOD_5, PM.TRAP_BN_INV_MOD_COMPLETE};\n cfg.perfStops = PERFSTOPS_BigNatural_Inversion__Modulo_;\n cfg.perfStopComplete = PM.TRAP_BN_INV_MOD_COMPLETE;\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n BigInteger num1 = Util.randomBigNat(runCfg.bnBaseTestLength + runCfg.bnBaseTestLength / 2); //Generate base\n BigInteger num2 = new BigInteger(1, SecP256r1.p);//Generate mod\n CommandAPDU cmd = new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_BN_INV_MOD, Util.trimLeadingZeroes(num1.toByteArray()).length, 0, Util.concat(Util.trimLeadingZeroes(num1.toByteArray()), Util.trimLeadingZeroes(num2.toByteArray())));\n PerfAnalyzeCommand(\"BigNatural Inversion (Modulo): \", cmd, cardMngr, cfg); \n }\n\n }\n\n if (runCfg.bTestINT) {\n short[] PERFSTOPS_Integer_Storage = {PM.TRAP_INT_STR_1, PM.TRAP_INT_STR_2, PM.TRAP_INT_STR_COMPLETE};\n cfg.perfStops = PERFSTOPS_Integer_Storage;\n cfg.perfStopComplete = PM.TRAP_INT_STR_COMPLETE;\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n int num = ThreadLocalRandom.current().nextInt(Integer.MIN_VALUE, Integer.MAX_VALUE);\n CommandAPDU cmd = new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_INT_STR, 0, 0, Util.IntToBytes(num));\n PerfAnalyzeCommand(\"Integer Storage: \", cmd, cardMngr, cfg);\n }\n\n short[] PERFSTOPS_Integer_Addition = {PM.TRAP_INT_ADD_1, PM.TRAP_INT_ADD_2, PM.TRAP_INT_ADD_3, PM.TRAP_INT_ADD_4, PM.TRAP_INT_ADD_COMPLETE};\n cfg.perfStops = PERFSTOPS_Integer_Addition;\n cfg.perfStopComplete = PM.TRAP_INT_ADD_COMPLETE;\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n int num_add_1 = ThreadLocalRandom.current().nextInt(Integer.MIN_VALUE, Integer.MAX_VALUE);\n int num_add_2 = ThreadLocalRandom.current().nextInt(Integer.MIN_VALUE, Integer.MAX_VALUE);\n\n CommandAPDU cmd = new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_INT_ADD, Util.IntToBytes(num_add_1).length, 0, Util.concat(Util.IntToBytes(num_add_1), Util.IntToBytes(num_add_2)));\n PerfAnalyzeCommand(\"Integer Addition: \", cmd, cardMngr, cfg);\n }\n\n short[] PERFSTOPS_Integer_Subtraction = {PM.TRAP_INT_SUB_1, PM.TRAP_INT_SUB_2, PM.TRAP_INT_SUB_3, PM.TRAP_INT_SUB_COMPLETE};\n cfg.perfStops = PERFSTOPS_Integer_Subtraction;\n cfg.perfStopComplete = PM.TRAP_INT_SUB_COMPLETE;\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n int num_sub_1 = ThreadLocalRandom.current().nextInt(Integer.MIN_VALUE, Integer.MAX_VALUE);\n int num_sub_2 = ThreadLocalRandom.current().nextInt(Integer.MIN_VALUE, Integer.MAX_VALUE);\n CommandAPDU cmd = new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_INT_SUB, Util.IntToBytes(num_sub_1).length, 0, Util.concat(Util.IntToBytes(num_sub_1), Util.IntToBytes(num_sub_2)));\n PerfAnalyzeCommand(\"Integer Subtraction: \", cmd, cardMngr, cfg);\n }\n\n short[] PERFSTOPS_Integer_Multiplication = {PM.TRAP_INT_MUL_1, PM.TRAP_INT_MUL_2, PM.TRAP_INT_MUL_3, PM.TRAP_INT_MUL_COMPLETE};\n cfg.perfStops = PERFSTOPS_Integer_Multiplication;\n cfg.perfStopComplete = PM.TRAP_INT_MUL_COMPLETE;\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n int num_mul_1 = ThreadLocalRandom.current().nextInt((int) (Math.sqrt(Integer.MIN_VALUE)), (int) (Math.sqrt(Integer.MAX_VALUE)));\n int num_mul_2 = ThreadLocalRandom.current().nextInt((int) (Math.sqrt(Integer.MIN_VALUE)), (int) (Math.sqrt(Integer.MAX_VALUE)));\n CommandAPDU cmd = new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_INT_MUL, Util.IntToBytes(num_mul_1).length, 0, Util.concat(Util.IntToBytes(num_mul_1), Util.IntToBytes(num_mul_2)));\n PerfAnalyzeCommand(\"Integer Multiplication: \", cmd, cardMngr, cfg);\n }\n\n short[] PERFSTOPS_Integer_Division = {PM.TRAP_INT_DIV_1, PM.TRAP_INT_DIV_2, PM.TRAP_INT_DIV_3, PM.TRAP_INT_DIV_COMPLETE};\n cfg.perfStops = PERFSTOPS_Integer_Division;\n cfg.perfStopComplete = PM.TRAP_INT_DIV_COMPLETE;\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n int num_div_1 = ThreadLocalRandom.current().nextInt(Integer.MIN_VALUE, Integer.MAX_VALUE);\n int num_div_2 = ThreadLocalRandom.current().nextInt(Integer.MIN_VALUE, Integer.MAX_VALUE);\n CommandAPDU cmd = new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_INT_DIV, Util.IntToBytes(num_div_1).length, 0, Util.concat(Util.IntToBytes(num_div_1), Util.IntToBytes(num_div_2)));\n PerfAnalyzeCommand(\"Integer Division: \", cmd, cardMngr, cfg);\n }\n /*\n short[] PERFSTOPS_Integer_Exponentiation = {PerfMeasure.TRAP_INT_EXP_1, PerfMeasure.TRAP_INT_EXP_2, PerfMeasure.TRAP_INT_EXP_3, PerfMeasure.TRAP_INT_EXP_4, PerfMeasure.TRAP_INT_EXP_COMPLETE};\n cfg.perfStops = PERFSTOPS_Integer_Exponentiation;\n cfg.perfStopComplete = PerfMeasure.TRAP_INT_EXP_COMPLETE;\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n PerfAnalyzeCommand(\"Integer Exponentiation: \", cmd, cardMngr, cfg);\n }\n */\n short[] PERFSTOPS_Integer_Modulo = {PM.TRAP_INT_MOD_1, PM.TRAP_INT_MOD_2, PM.TRAP_INT_MOD_3, PM.TRAP_INT_MOD_COMPLETE};\n cfg.perfStops = PERFSTOPS_Integer_Modulo;\n cfg.perfStopComplete = PM.TRAP_INT_MOD_COMPLETE;\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n int num_mod_1 = ThreadLocalRandom.current().nextInt(Integer.MIN_VALUE, Integer.MAX_VALUE);\n int num_mod_2 = ThreadLocalRandom.current().nextInt(Integer.MIN_VALUE, Integer.MAX_VALUE);\n CommandAPDU cmd = new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_INT_MOD, Util.IntToBytes(num_mod_1).length, 0, Util.concat(Util.IntToBytes(num_mod_1), Util.IntToBytes(num_mod_2)));\n PerfAnalyzeCommand(\"Integer Modulo: \", cmd, cardMngr, cfg);\n }\n }\n\n if (runCfg.bTestECPoint) {\n // Details of ECPoint\n \n/* \n short[] PERFSTOPS_ECPoint_multiplication_double = {PerfMeasure.TRAP_ECPOINT_MULT_1, PerfMeasure.TRAP_ECPOINT_MULT_2, PerfMeasure.TRAP_ECPOINT_MULT_3, PerfMeasure.TRAP_ECPOINT_MULT_4, PerfMeasure.TRAP_ECPOINT_MULT_5, PerfMeasure.TRAP_ECPOINT_MULT_6, PerfMeasure.TRAP_ECPOINT_MULT_7, PerfMeasure.TRAP_ECPOINT_MULT_8, PerfMeasure.TRAP_ECPOINT_MULT_9, PerfMeasure.TRAP_ECPOINT_MULT_10, PerfMeasure.TRAP_ECPOINT_MULT_11, PerfMeasure.TRAP_ECPOINT_MULT_12, PerfMeasure.TRAP_ECPOINT_MULT_COMPLETE};\n cfg.perfStops = PERFSTOPS_ECPoint_multiplication_double;\n cfg.perfStopComplete = PerfMeasure.TRAP_ECPOINT_MULT_COMPLETE;\n/**/\n /*\n short[] PERFSTOPS_ECPoint_multiplication_x2 = {PerfMeasure.TRAP_ECPOINT_MULT_X_1, PerfMeasure.TRAP_ECPOINT_MULT_X_2, PerfMeasure.TRAP_ECPOINT_MULT_X_3, PerfMeasure.TRAP_ECPOINT_MULT_X_4, PerfMeasure.TRAP_ECPOINT_MULT_X_5, PerfMeasure.TRAP_ECPOINT_MULT_X_COMPLETE};\n cfg.perfStops = PERFSTOPS_ECPoint_multiplication_x2;\n cfg.perfStopComplete = PerfMeasure.TRAP_ECPOINT_MULT_X_COMPLETE;\n*/ \n/* \n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n ECPoint pnt = Util.randECPoint();\n System.out.println(String.format(\"Random ECPoint == G: %s\", Util.toHex(pnt.getEncoded(false))));\n // Set modified parameter G of the curve (our random point) \n cardMngr.transmit(new CommandAPDU(Configuration.CLA_MPC, Configuration.INS_EC_SETCURVE_G, 0, 0, pnt.getEncoded(false)));\n\n CommandAPDU cmd = new CommandAPDU(Configuration.CLA_MPC, Configuration.INS_EC_DBL, 0, 0, pnt.getEncoded(false));\n PerfAnalyzeCommand(\"ECPoint_double: \", cmd, cardMngr, cfg);\n }\n*/\n short[] PERFSTOPS_ECPoint_multiplication = {PM.TRAP_ECPOINT_MULT_1, PM.TRAP_ECPOINT_MULT_2, PM.TRAP_ECPOINT_MULT_3, PM.TRAP_ECPOINT_MULT_4, PM.TRAP_ECPOINT_MULT_5, PM.TRAP_ECPOINT_MULT_6, PM.TRAP_ECPOINT_MULT_7, PM.TRAP_ECPOINT_MULT_8, PM.TRAP_ECPOINT_MULT_9, PM.TRAP_ECPOINT_MULT_10, PM.TRAP_ECPOINT_MULT_11, PM.TRAP_ECPOINT_MULT_12, PM.TRAP_ECPOINT_MULT_COMPLETE};\n cfg.perfStops = PERFSTOPS_ECPoint_multiplication;\n cfg.perfStopComplete = PM.TRAP_ECPOINT_MULT_COMPLETE;\n Security.addProvider(new BouncyCastleProvider());\n ECParameterSpec ecSpec2 = ECNamedCurveTable.getParameterSpec(\"secp256r1\");\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n ECPoint pnt = ecSpec2.getG(); // Use standard G point\n BigInteger scalar = Util.randomBigNat(runCfg.bnBaseTestLength);\n CommandAPDU cmd = new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_EC_MUL, scalar.toByteArray().length, 0, Util.concat(scalar.toByteArray(), pnt.getEncoded(false)));\n PerfAnalyzeCommand(\"ECPoint_multiplication: \", cmd, cardMngr, cfg);\n }\n\n short[] PERFSTOPS_ECPoint_add = {PM.TRAP_ECPOINT_ADD_1, PM.TRAP_ECPOINT_ADD_2, PM.TRAP_ECPOINT_ADD_3, PM.TRAP_ECPOINT_ADD_4, PM.TRAP_ECPOINT_ADD_5, PM.TRAP_ECPOINT_ADD_6, PM.TRAP_ECPOINT_ADD_7, PM.TRAP_ECPOINT_ADD_8, PM.TRAP_ECPOINT_ADD_9, PM.TRAP_ECPOINT_ADD_10, PM.TRAP_ECPOINT_ADD_11, PM.TRAP_ECPOINT_ADD_12, PM.TRAP_ECPOINT_ADD_13, PM.TRAP_ECPOINT_ADD_COMPLETE};\n cfg.perfStops = PERFSTOPS_ECPoint_add;\n cfg.perfStopComplete = PM.TRAP_ECPOINT_ADD_COMPLETE;\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n ECPoint pnt_1 = Util.randECPoint();\n ECPoint pnt_2 = Util.randECPoint();\n CommandAPDU cmd = new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_EC_ADD, 0, 0, Util.concat(pnt_1.getEncoded(false), pnt_2.getEncoded(false)));\n //CommandAPDU cmd = new CommandAPDU(hexStringToByteArray(\"B041000041041D1D96E2B171DFCC457587259E28E597258BF86EA0CFCB97BB6FCE62E7539E2879F3FDE52075AACAD1BA7637F816B6145C01E646831C259409FB89309AB03FD9\"));\n PerfAnalyzeCommand(\"ECPoint_add: \", cmd, cardMngr, cfg);\n }\n\n // Details of ECCurve\n /* \n short[] PERFSTOPS_ECCurve_newKeyPair = {PerfMeasure.TRAP_ECCURVE_NEWKEYPAIR_1, PerfMeasure.TRAP_ECCURVE_NEWKEYPAIR_2, PerfMeasure.TRAP_ECCURVE_NEWKEYPAIR_3, PerfMeasure.TRAP_ECCURVE_NEWKEYPAIR_4, PerfMeasure.TRAP_ECCURVE_NEWKEYPAIR_5, PerfMeasure.TRAP_ECCURVE_NEWKEYPAIR_6, PerfMeasure.TRAP_ECCURVE_NEWKEYPAIR_7, PerfMeasure.TRAP_ECCURVE_NEWKEYPAIR_COMPLETE};\n cfg.perfStops = PERFSTOPS_ECCurve_newKeyPair;\n cfg.perfStopComplete = PerfMeasure.TRAP_ECCURVE_NEWKEYPAIR_COMPLETE;\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n CommandAPDU cmd = new CommandAPDU(Configuration.CLA_MPC, Configuration.INS_EC_GEN, 0, 0, bogusArray);\n PerfAnalyzeCommand(\"ECCurve_newKeyPair: \", cmd, cardMngr, cfg);\n }\n */\n\n short[] PERFSTOPS_ECPoint_multiplication_x = {PM.TRAP_ECPOINT_MULT_X_1, PM.TRAP_ECPOINT_MULT_X_2, PM.TRAP_ECPOINT_MULT_X_3, PM.TRAP_ECPOINT_MULT_X_4, PM.TRAP_ECPOINT_MULT_X_5, PM.TRAP_ECPOINT_MULT_X_COMPLETE};\n cfg.perfStops = PERFSTOPS_ECPoint_multiplication_x;\n cfg.perfStopComplete = PM.TRAP_ECPOINT_MULT_X_COMPLETE;\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n ECPoint pnt = ecSpec2.getG(); // Use standard G point\n BigInteger scalar = Util.randomBigNat(runCfg.bnBaseTestLength);\n CommandAPDU cmd = new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_EC_MUL, scalar.toByteArray().length, 0, Util.concat(scalar.toByteArray(), pnt.getEncoded(false)));\n PerfAnalyzeCommand(\"ECPoint_multiplication_x: \", cmd, cardMngr, cfg);\n }\n\n\n short[] PERFSTOPS_ECPoint_negate = {PM.TRAP_ECPOINT_NEGATE_1, PM.TRAP_ECPOINT_NEGATE_2, PM.TRAP_ECPOINT_NEGATE_3, PM.TRAP_ECPOINT_NEGATE_4, PM.TRAP_ECPOINT_NEGATE_5, PM.TRAP_ECPOINT_NEGATE_COMPLETE};\n cfg.perfStops = PERFSTOPS_ECPoint_negate;\n cfg.perfStopComplete = PM.TRAP_ECPOINT_NEGATE_COMPLETE;\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n ECPoint pnt = Util.randECPoint();\n ECPoint negPnt = pnt.negate();\n CommandAPDU cmd = new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_EC_NEG, pnt.getEncoded(false).length, 0, pnt.getEncoded(false));\n PerfAnalyzeCommand(\"ECPoint_negate: \", cmd, cardMngr, cfg);\n }\n }\n\n if (runCfg.bTestEC) {\n short[] PERFSTOPS_ECPOINT_GEN = {PM.TRAP_EC_GEN_1, PM.TRAP_EC_GEN_2, PM.TRAP_EC_GEN_3, PM.TRAP_EC_GEN_COMPLETE};\n cfg.perfStops = PERFSTOPS_ECPOINT_GEN;\n cfg.perfStopComplete = PM.TRAP_EC_GEN_COMPLETE;\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n PerfAnalyzeCommand(\"EC Point Generation: \", new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_EC_GEN, 0, 0, bogusArray), cardMngr, cfg);\n }\n\n short[] PERFSTOPS_ECPOINT_ADD = {PM.TRAP_EC_ADD_1, PM.TRAP_EC_ADD_2, PM.TRAP_EC_ADD_3, PM.TRAP_EC_ADD_4, PM.TRAP_EC_ADD_5, PM.TRAP_EC_ADD_COMPLETE};\n cfg.perfStops = PERFSTOPS_ECPOINT_ADD;\n cfg.perfStopComplete = PM.TRAP_EC_ADD_COMPLETE;\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n ECPoint pnt_1 = Util.randECPoint();\n ECPoint pnt_2 = Util.randECPoint();\n PerfAnalyzeCommand(\"EC Point Add: \", new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_EC_ADD, 0, 0, Util.concat(pnt_1.getEncoded(false), pnt_2.getEncoded(false))), cardMngr, cfg);\n }\n\n short[] PERFSTOPS_EC_scalar_point_multiplication = {PM.TRAP_EC_MUL_1, PM.TRAP_EC_MUL_2, PM.TRAP_EC_MUL_3, PM.TRAP_EC_MUL_4, PM.TRAP_EC_MUL_5, PM.TRAP_EC_MUL_COMPLETE};\n cfg.perfStops = PERFSTOPS_EC_scalar_point_multiplication;\n cfg.perfStopComplete = PM.TRAP_EC_MUL_COMPLETE;\n Security.addProvider(new BouncyCastleProvider());\n ECParameterSpec ecSpec2 = ECNamedCurveTable.getParameterSpec(\"secp256r1\");\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n ECPoint base = ecSpec2.getG();\n Random rnd = new Random();\n BigInteger priv1 = new BigInteger(runCfg.bnBaseTestLength, rnd);\n PerfAnalyzeCommand(\"EC scalar-point multiplication: \", new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_EC_MUL, priv1.toByteArray().length, 0, Util.concat(priv1.toByteArray(), base.getEncoded(false))), cardMngr, cfg);\n } \n \n short[] PERFSTOPS_ECPOINT_DOUBLE = {PM.TRAP_EC_DBL_1, PM.TRAP_EC_DBL_2, PM.TRAP_EC_DBL_3, PM.TRAP_EC_DBL_4, PM.TRAP_EC_DBL_COMPLETE};\n cfg.perfStops = PERFSTOPS_ECPOINT_DOUBLE;\n cfg.perfStopComplete = PM.TRAP_EC_DBL_COMPLETE;\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n ECPoint pnt = Util.randECPoint();\n System.out.println(String.format(\"Random ECPoint == G: %s\", Util.toHex(pnt.getEncoded(false))));\n // Set modified parameter G of the curve (our random point) \n cardMngr.transmit(new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_EC_SETCURVE_G, 0, 0, pnt.getEncoded(false)));\n\n PerfAnalyzeCommand(\"EC Point Double: \", new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_EC_DBL, 0, 0, pnt.getEncoded(false)), cardMngr, cfg);\n }\n }\n\n \n System.out.println(\"\\n-------------- Performance tests--------------\\n\\n\");\n System.out.print(\"Disconnecting from card...\");\n cardMngr.Disconnect(true); // Disconnect from the card\n System.out.println(\" Done.\");\n } catch (Exception e) {\n e.printStackTrace();\n }\n \n if (cfg.failedPerfTraps.size() > 0) {\n System.out.println(\"#########################\");\n System.out.println(\"!!! SOME PERFORMANCE TRAPS NOT REACHED !!!\");\n System.out.println(\"#########################\");\n for (String trap : cfg.failedPerfTraps) {\n System.out.println(trap);\n }\n } else {\n System.out.println(\"##########################\");\n System.out.println(\"ALL PERFORMANCE TRAPS REACHED CORRECTLY\");\n System.out.println(\"##########################\");\n } \n \n // Save performance traps into single file\n String perfFileName = String.format(\"TRAP_RAW_%s.csv\", experimentID);\n SavePerformanceResults(cfg.perfResultsSubpartsRaw, perfFileName);\n \n // If required, modification of source code files is attempted\n if (MODIFY_SOURCE_FILES_BY_PERF) {\n String dirPath = \"..\\\\!PerfSRC\\\\Lib\\\\\";\n InsertPerfInfoIntoFiles(dirPath, cfg.cardName, experimentID, cfg.perfResultsSubpartsRaw);\n }\n } \n \n static void SavePerformanceResults(HashMap<Short, Entry<Short, Long>> perfResultsSubpartsRaw, String fileName) throws FileNotFoundException, IOException {\n // Save performance traps into single file\n FileOutputStream perfLog = new FileOutputStream(fileName);\n String output = \"perfID, previous perfID, time difference between perfID and previous perfID (ms)\\n\";\n perfLog.write(output.getBytes());\n for (Short perfID : perfResultsSubpartsRaw.keySet()) {\n output = String.format(\"%d, %d, %d\\n\", perfID, perfResultsSubpartsRaw.get(perfID).getKey(), perfResultsSubpartsRaw.get(perfID).getValue());\n perfLog.write(output.getBytes());\n }\n perfLog.close();\n }\n \n static void LoadPerformanceResults(String fileName, HashMap<Short, Entry<Short, Long>> perfResultsSubpartsRaw) throws FileNotFoundException, IOException {\n BufferedReader br = new BufferedReader(new FileReader(fileName));\n String strLine;\n while ((strLine = br.readLine()) != null) {\n if (strLine.contains(\"perfID,\")) {\n // skip header line\n }\n else {\n String[] cols = strLine.split(\",\");\n Short perfID = Short.parseShort(cols[0].trim());\n Short prevPerfID = Short.parseShort(cols[1].trim());\n Long elapsed = Long.parseLong(cols[2].trim());\n \n perfResultsSubpartsRaw.put(perfID, new SimpleEntry(prevPerfID, elapsed));\n }\n }\n br.close();\n } \n \n static void testInsertPerfIntoFiles() throws IOException {\n String dirPath = \"..\\\\!PerfSRC\\\\Lib\\\\\";\n HashMap<Short, Entry<Short, Long>> results = new HashMap<>(); \n results.put(PM.TRAP_EC_ADD_2, new SimpleEntry(PM.TRAP_EC_ADD_1, 37));\n results.put(PM.TRAP_EC_GEN_3, new SimpleEntry(PM.TRAP_EC_GEN_2, 123));\n results.put(PM.TRAP_EC_DBL_2, new SimpleEntry(PM.TRAP_EC_DBL_1, 567));\n\n String perfFileName = String.format(\"TRAP_RAW_123456.csv\");\n SavePerformanceResults(results, perfFileName);\n HashMap<Short, Entry<Short, Long>> perfResultsSubpartsRaw = new HashMap<>();\n LoadPerformanceResults(perfFileName, perfResultsSubpartsRaw);\n assert (perfResultsSubpartsRaw.size() == results.size());\n \n InsertPerfInfoIntoFiles(dirPath, \"test\", \"123456\", results);\n }\n \n long PerfAnalyzeCommand(String operationName, CommandAPDU cmd, CardManager cardMngr, PerfConfig cfg) throws CardException, IOException {\n System.out.println(operationName);\n short prevPerfStop = PM.PERF_START;\n long prevTransmitTime = 0;\n long lastFromPrevTime = 0;\n short currentPerfStop = 0;\n try {\n for (short perfStop : cfg.perfStops) {\n currentPerfStop = perfStop;\n System.arraycopy(Util.shortToByteArray(perfStop), 0, PERF_COMMAND, ISO7816.OFFSET_CDATA, 2); // set required stop condition\n String operationNamePerf = String.format(\"%s_%s\", operationName, getPerfStopName(perfStop));\n System.out.println(operationNamePerf);\n cardMngr.transmit(new CommandAPDU(PERF_COMMAND)); // set performance trap\n ResponseAPDU response = cardMngr.transmit(cmd); // execute target operation\n boolean bFailedToReachTrap = false;\n if (perfStop != cfg.perfStopComplete) { // Check expected error to be equal performance trap\n if (response.getSW() != (perfStop & 0xffff)) {\n // we have not reached expected performance trap\n cfg.failedPerfTraps.add(getPerfStopName(perfStop));\n bFailedToReachTrap = true;\n }\n }\n writePerfLog(operationNamePerf, response.getSW() == (ISO7816.SW_NO_ERROR & 0xffff), cardMngr.m_lastTransmitTime, cfg.perfResultsSingleOp, cfg.perfFile);\n long fromPrevTime = cardMngr.m_lastTransmitTime - prevTransmitTime;\n if (bFailedToReachTrap) {\n cfg.perfResultsSubparts.add(String.format(\"[%s-%s], \\tfailed to reach after %d ms (0x%x)\", getPerfStopName(prevPerfStop), getPerfStopName(perfStop), cardMngr.m_lastTransmitTime, response.getSW()));\n }\n else {\n cfg.perfResultsSubparts.add(String.format(\"[%s-%s], \\t%d ms\", getPerfStopName(prevPerfStop), getPerfStopName(perfStop), fromPrevTime));\n cfg.perfResultsSubpartsRaw.put(perfStop, new SimpleEntry(prevPerfStop, fromPrevTime)); \n lastFromPrevTime = fromPrevTime;\n }\n\n prevPerfStop = perfStop;\n prevTransmitTime = cardMngr.m_lastTransmitTime;\n\n cardMngr.transmit(new CommandAPDU(APDU_RESET)); // free memory after command\n }\n }\n catch (Exception e) {\n // Print what we have measured so far\n for (String res : cfg.perfResultsSubparts) {\n System.out.println(res);\n }\n cfg.failedPerfTraps.add(getPerfStopName(currentPerfStop));\n throw e;\n }\n // Print measured performance info\n for (String res : cfg.perfResultsSubparts) {\n System.out.println(res);\n }\n \n return lastFromPrevTime;\n } \n \n \n static void writePerfLog(String operationName, boolean bResult, Long time, ArrayList<Entry<String, Long>> perfResults, FileOutputStream perfFile) throws IOException {\n perfResults.add(new SimpleEntry(operationName, time));\n perfFile.write(String.format(\"%s,%d,%s\\n\", operationName, time, bResult).getBytes());\n perfFile.flush();\n }\n \n \n static void InsertPerfInfoIntoFiles(String basePath, String cardName, String experimentID, HashMap<Short, Entry<Short, Long>> perfResultsSubpartsRaw) throws FileNotFoundException, IOException {\n File dir = new File(basePath);\n String[] filesArray = dir.list();\n if ((filesArray != null) && (dir.isDirectory() == true)) {\n // make subdir for results\n String outputDir = String.format(\"%s\\\\perf\\\\%s\\\\\", basePath, experimentID);\n new File(outputDir).mkdirs();\n\n for (String fileName : filesArray) {\n File dir2 = new File(basePath + fileName);\n if (!dir2.isDirectory()) {\n InsertPerfInfoIntoFile(String.format(\"%s\\\\%s\", basePath, fileName), cardName, experimentID, outputDir, perfResultsSubpartsRaw);\n }\n }\n }\n }\n \n static void InsertPerfInfoIntoFile(String filePath, String cardName, String experimentID, String outputDir, HashMap<Short, Entry<Short, Long>> perfResultsSubpartsRaw) throws FileNotFoundException, IOException {\n try {\n BufferedReader br = new BufferedReader(new FileReader(filePath));\n String basePath = filePath.substring(0, filePath.lastIndexOf(\"\\\\\"));\n String fileName = filePath.substring(filePath.lastIndexOf(\"\\\\\"));\n \n String fileNamePerf = String.format(\"%s\\\\%s\", outputDir, fileName);\n FileOutputStream fileOut = new FileOutputStream(fileNamePerf);\n String strLine;\n String resLine;\n // For every line of program try to find perfromance trap. If found and perf. is available, then insert comment into code\n while ((strLine = br.readLine()) != null) {\n \n if (strLine.contains(PERF_TRAP_CALL)) {\n int trapStart = strLine.indexOf(PERF_TRAP_CALL);\n int trapEnd = strLine.indexOf(PERF_TRAP_CALL_END);\n // We have perf. trap, now check if we also corresponding measurement\n String perfTrapName = (String) strLine.substring(trapStart + PERF_TRAP_CALL.length(), trapEnd);\n short perfID = getPerfStopFromName(perfTrapName);\n \n if (perfResultsSubpartsRaw.containsKey(perfID)) {\n // We have measurement for this trap, add into comment section\n resLine = String.format(\"%s // %d ms (%s,%s) %s\", (String) strLine.substring(0, trapEnd + PERF_TRAP_CALL_END.length()), perfResultsSubpartsRaw.get(perfID).getValue(), cardName, experimentID, (String) strLine.subSequence(trapEnd + PERF_TRAP_CALL_END.length(), strLine.length()));\n }\n else {\n resLine = strLine;\n }\n }\n else {\n resLine = strLine;\n }\n resLine += \"\\n\";\n fileOut.write(resLine.getBytes());\n }\n \n fileOut.close();\n }\n catch(Exception e) {\n System.out.println(String.format(\"Failed to transform file %s \", filePath) + e);\n }\n }\n \n\n public static void buildPerfMapping() {\n PERF_STOP_MAPPING.put(PM.PERF_START, \"PERF_START\");\n //PERF_STOP_MAPPING.put(PerfMeasure.PERF_COMPLETE, \"PERF_COMPLETE\");\n\n PERF_STOP_MAPPING.put(PM.TRAP_EC_GEN_1, \"TRAP_EC_GEN_1\");\n PERF_STOP_MAPPING.put(PM.TRAP_EC_GEN_2, \"TRAP_EC_GEN_2\");\n PERF_STOP_MAPPING.put(PM.TRAP_EC_GEN_3, \"TRAP_EC_GEN_3\");\n PERF_STOP_MAPPING.put(PM.TRAP_EC_GEN_COMPLETE, \"TRAP_EC_GEN_COMPLETE\");\n\n PERF_STOP_MAPPING.put(PM.TRAP_EC_DBL_1, \"TRAP_EC_DBL_1\");\n PERF_STOP_MAPPING.put(PM.TRAP_EC_DBL_2, \"TRAP_EC_DBL_2\");\n PERF_STOP_MAPPING.put(PM.TRAP_EC_DBL_3, \"TRAP_EC_DBL_3\");\n PERF_STOP_MAPPING.put(PM.TRAP_EC_DBL_4, \"TRAP_EC_DBL_4\");\n PERF_STOP_MAPPING.put(PM.TRAP_EC_DBL_COMPLETE, \"TRAP_EC_DBL_COMPLETE\");\n\n PERF_STOP_MAPPING.put(PM.TRAP_EC_MUL_1, \"TRAP_EC_MUL_1\");\n PERF_STOP_MAPPING.put(PM.TRAP_EC_MUL_2, \"TRAP_EC_MUL_2\");\n PERF_STOP_MAPPING.put(PM.TRAP_EC_MUL_3, \"TRAP_EC_MUL_3\");\n PERF_STOP_MAPPING.put(PM.TRAP_EC_MUL_4, \"TRAP_EC_MUL_4\");\n PERF_STOP_MAPPING.put(PM.TRAP_EC_MUL_5, \"TRAP_EC_MUL_5\");\n PERF_STOP_MAPPING.put(PM.TRAP_EC_MUL_6, \"TRAP_EC_MUL_6\");\n PERF_STOP_MAPPING.put(PM.TRAP_EC_MUL_COMPLETE, \"TRAP_EC_MUL_COMPLETE\");\n\n PERF_STOP_MAPPING.put(PM.TRAP_EC_ADD_1, \"TRAP_EC_ADD_1\");\n PERF_STOP_MAPPING.put(PM.TRAP_EC_ADD_2, \"TRAP_EC_ADD_2\");\n PERF_STOP_MAPPING.put(PM.TRAP_EC_ADD_3, \"TRAP_EC_ADD_3\");\n PERF_STOP_MAPPING.put(PM.TRAP_EC_ADD_4, \"TRAP_EC_ADD_4\");\n PERF_STOP_MAPPING.put(PM.TRAP_EC_ADD_5, \"TRAP_EC_ADD_5\");\n PERF_STOP_MAPPING.put(PM.TRAP_EC_ADD_COMPLETE, \"TRAP_EC_ADD_COMPLETE\");\n\n PERF_STOP_MAPPING.put(PM.TRAP_BN_STR_1, \"TRAP_BN_STR_1\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_STR_2, \"TRAP_BN_STR_2\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_STR_3, \"TRAP_BN_STR_3\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_STR_COMPLETE, \"TRAP_BN_STR_COMPLETE\");\n\n PERF_STOP_MAPPING.put(PM.TRAP_BN_ADD_1, \"TRAP_BN_ADD_1\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_ADD_2, \"TRAP_BN_ADD_2\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_ADD_3, \"TRAP_BN_ADD_3\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_ADD_4, \"TRAP_BN_ADD_4\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_ADD_5, \"TRAP_BN_ADD_5\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_ADD_6, \"TRAP_BN_ADD_6\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_ADD_7, \"TRAP_BN_ADD_7\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_ADD_COMPLETE, \"TRAP_BN_ADD_COMPLETE\");\n\n PERF_STOP_MAPPING.put(PM.TRAP_BN_SUB_1, \"TRAP_BN_SUB_1\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_SUB_2, \"TRAP_BN_SUB_2\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_SUB_3, \"TRAP_BN_SUB_3\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_SUB_4, \"TRAP_BN_SUB_4\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_SUB_5, \"TRAP_BN_SUB_5\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_SUB_6, \"TRAP_BN_SUB_6\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_SUB_7, \"TRAP_BN_SUB_7\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_SUB_COMPLETE, \"TRAP_BN_SUB_COMPLETE\");\n\n PERF_STOP_MAPPING.put(PM.TRAP_BN_MUL_1, \"TRAP_BN_MUL_1\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_MUL_2, \"TRAP_BN_MUL_2\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_MUL_3, \"TRAP_BN_MUL_3\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_MUL_4, \"TRAP_BN_MUL_4\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_MUL_5, \"TRAP_BN_MUL_5\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_MUL_6, \"TRAP_BN_MUL_6\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_MUL_COMPLETE, \"TRAP_BN_MUL_COMPLETE\");\n\n PERF_STOP_MAPPING.put(PM.TRAP_BN_EXP_1, \"TRAP_BN_EXP_1\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_EXP_2, \"TRAP_BN_EXP_2\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_EXP_3, \"TRAP_BN_EXP_3\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_EXP_4, \"TRAP_BN_EXP_4\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_EXP_5, \"TRAP_BN_EXP_5\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_EXP_6, \"TRAP_BN_EXP_6\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_EXP_COMPLETE, \"TRAP_BN_EXP_COMPLETE\");\n\n PERF_STOP_MAPPING.put(PM.TRAP_BN_MOD_1, \"TRAP_BN_MOD_1\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_MOD_2, \"TRAP_BN_MOD_2\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_MOD_3, \"TRAP_BN_MOD_3\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_MOD_4, \"TRAP_BN_MOD_4\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_MOD_5, \"TRAP_BN_MOD_5\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_MOD_COMPLETE, \"TRAP_BN_MOD_COMPLETE\");\n\n PERF_STOP_MAPPING.put(PM.TRAP_BN_ADD_MOD_1, \"TRAP_BN_ADD_MOD_1\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_ADD_MOD_2, \"TRAP_BN_ADD_MOD_2\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_ADD_MOD_3, \"TRAP_BN_ADD_MOD_3\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_ADD_MOD_4, \"TRAP_BN_ADD_MOD_4\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_ADD_MOD_5, \"TRAP_BN_ADD_MOD_5\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_ADD_MOD_6, \"TRAP_BN_ADD_MOD_6\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_ADD_MOD_7, \"TRAP_BN_ADD_MOD_7\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_ADD_MOD_COMPLETE, \"TRAP_BN_ADD_MOD_COMPLETE\");\n\n PERF_STOP_MAPPING.put(PM.TRAP_BN_SUB_MOD_1, \"TRAP_BN_SUB_MOD_1\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_SUB_MOD_2, \"TRAP_BN_SUB_MOD_2\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_SUB_MOD_3, \"TRAP_BN_SUB_MOD_3\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_SUB_MOD_4, \"TRAP_BN_SUB_MOD_4\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_SUB_MOD_5, \"TRAP_BN_SUB_MOD_5\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_SUB_MOD_6, \"TRAP_BN_SUB_MOD_6\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_SUB_MOD_COMPLETE, \"TRAP_BN_SUB_MOD_COMPLETE\");\n\n PERF_STOP_MAPPING.put(PM.TRAP_BN_MUL_MOD_1, \"TRAP_BN_MUL_MOD_1\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_MUL_MOD_2, \"TRAP_BN_MUL_MOD_2\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_MUL_MOD_3, \"TRAP_BN_MUL_MOD_3\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_MUL_MOD_4, \"TRAP_BN_MUL_MOD_4\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_MUL_MOD_5, \"TRAP_BN_MUL_MOD_5\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_MUL_MOD_6, \"TRAP_BN_MUL_MOD_6\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_MUL_MOD_COMPLETE, \"TRAP_BN_MUL_MOD_COMPLETE\");\n\n PERF_STOP_MAPPING.put(PM.TRAP_BN_EXP_MOD_1, \"TRAP_BN_EXP_MOD_1\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_EXP_MOD_2, \"TRAP_BN_EXP_MOD_2\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_EXP_MOD_3, \"TRAP_BN_EXP_MOD_3\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_EXP_MOD_4, \"TRAP_BN_EXP_MOD_4\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_EXP_MOD_5, \"TRAP_BN_EXP_MOD_5\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_EXP_MOD_6, \"TRAP_BN_EXP_MOD_6\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_EXP_MOD_COMPLETE, \"TRAP_BN_EXP_MOD_COMPLETE\");\n\n PERF_STOP_MAPPING.put(PM.TRAP_BN_INV_MOD_1, \"TRAP_BN_INV_MOD_1\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_INV_MOD_2, \"TRAP_BN_INV_MOD_2\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_INV_MOD_3, \"TRAP_BN_INV_MOD_3\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_INV_MOD_4, \"TRAP_BN_INV_MOD_4\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_INV_MOD_5, \"TRAP_BN_INV_MOD_5\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_INV_MOD_COMPLETE, \"TRAP_BN_INV_MOD_COMPLETE\");\n\n PERF_STOP_MAPPING.put(PM.TRAP_INT_STR_1, \"TRAP_INT_STR_1\");\n PERF_STOP_MAPPING.put(PM.TRAP_INT_STR_2, \"TRAP_INT_STR_2\");\n PERF_STOP_MAPPING.put(PM.TRAP_INT_STR_COMPLETE, \"TRAP_INT_STR_COMPLETE\");\n\n PERF_STOP_MAPPING.put(PM.TRAP_INT_ADD_1, \"TRAP_INT_ADD_1\");\n PERF_STOP_MAPPING.put(PM.TRAP_INT_ADD_2, \"TRAP_INT_ADD_2\");\n PERF_STOP_MAPPING.put(PM.TRAP_INT_ADD_3, \"TRAP_INT_ADD_3\");\n PERF_STOP_MAPPING.put(PM.TRAP_INT_ADD_4, \"TRAP_INT_ADD_4\");\n PERF_STOP_MAPPING.put(PM.TRAP_INT_ADD_COMPLETE, \"TRAP_INT_ADD_COMPLETE\");\n\n PERF_STOP_MAPPING.put(PM.TRAP_INT_SUB_1, \"TRAP_INT_SUB_1\");\n PERF_STOP_MAPPING.put(PM.TRAP_INT_SUB_2, \"TRAP_INT_SUB_2\");\n PERF_STOP_MAPPING.put(PM.TRAP_INT_SUB_3, \"TRAP_INT_SUB_3\");\n PERF_STOP_MAPPING.put(PM.TRAP_INT_SUB_4, \"TRAP_INT_SUB_4\");\n PERF_STOP_MAPPING.put(PM.TRAP_INT_SUB_COMPLETE, \"TRAP_INT_SUB_COMPLETE\");\n\n PERF_STOP_MAPPING.put(PM.TRAP_INT_MUL_1, \"TRAP_INT_MUL_1\");\n PERF_STOP_MAPPING.put(PM.TRAP_INT_MUL_2, \"TRAP_INT_MUL_2\");\n PERF_STOP_MAPPING.put(PM.TRAP_INT_MUL_3, \"TRAP_INT_MUL_3\");\n PERF_STOP_MAPPING.put(PM.TRAP_INT_MUL_4, \"TRAP_INT_MUL_4\");\n PERF_STOP_MAPPING.put(PM.TRAP_INT_MUL_COMPLETE, \"TRAP_INT_MUL_COMPLETE\");\n\n PERF_STOP_MAPPING.put(PM.TRAP_INT_DIV_1, \"TRAP_INT_DIV_1\");\n PERF_STOP_MAPPING.put(PM.TRAP_INT_DIV_2, \"TRAP_INT_DIV_2\");\n PERF_STOP_MAPPING.put(PM.TRAP_INT_DIV_3, \"TRAP_INT_DIV_3\");\n PERF_STOP_MAPPING.put(PM.TRAP_INT_DIV_4, \"TRAP_INT_DIV_4\");\n PERF_STOP_MAPPING.put(PM.TRAP_INT_DIV_COMPLETE, \"TRAP_INT_DIV_COMPLETE\");\n\n PERF_STOP_MAPPING.put(PM.TRAP_INT_EXP_1, \"TRAP_INT_EXP_1\");\n PERF_STOP_MAPPING.put(PM.TRAP_INT_EXP_2, \"TRAP_INT_EXP_2\");\n PERF_STOP_MAPPING.put(PM.TRAP_INT_EXP_3, \"TRAP_INT_EXP_3\");\n PERF_STOP_MAPPING.put(PM.TRAP_INT_EXP_4, \"TRAP_INT_EXP_4\");\n PERF_STOP_MAPPING.put(PM.TRAP_INT_EXP_COMPLETE, \"TRAP_INT_EXP_COMPLETE\");\n\n PERF_STOP_MAPPING.put(PM.TRAP_INT_MOD_1, \"TRAP_INT_MOD_1\");\n PERF_STOP_MAPPING.put(PM.TRAP_INT_MOD_2, \"TRAP_INT_MOD_2\");\n PERF_STOP_MAPPING.put(PM.TRAP_INT_MOD_3, \"TRAP_INT_MOD_3\");\n PERF_STOP_MAPPING.put(PM.TRAP_INT_MOD_4, \"TRAP_INT_MOD_4\");\n PERF_STOP_MAPPING.put(PM.TRAP_INT_MOD_COMPLETE, \"TRAP_INT_MOD_COMPLETE\");\n\n PERF_STOP_MAPPING.put(PM.TRAP_BN_POW2_MOD_1, \"TRAP_BN_POW2_MOD_1\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_POW2_MOD_2, \"TRAP_BN_POW2_MOD_2\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_POW2_MOD_3, \"TRAP_BN_POW2_MOD_3\");\n PERF_STOP_MAPPING.put(PM.TRAP_BN_POW2_COMPLETE, \"TRAP_BN_POW2_COMPLETE\");\n\n PERF_STOP_MAPPING.put(PM.TRAP_ECCURVE_NEWKEYPAIR_1, \"TRAP_ECCURVE_NEWKEYPAIR_1\");\n PERF_STOP_MAPPING.put(PM.TRAP_ECCURVE_NEWKEYPAIR_2, \"TRAP_ECCURVE_NEWKEYPAIR_2\");\n PERF_STOP_MAPPING.put(PM.TRAP_ECCURVE_NEWKEYPAIR_3, \"TRAP_ECCURVE_NEWKEYPAIR_3\");\n PERF_STOP_MAPPING.put(PM.TRAP_ECCURVE_NEWKEYPAIR_4, \"TRAP_ECCURVE_NEWKEYPAIR_4\");\n PERF_STOP_MAPPING.put(PM.TRAP_ECCURVE_NEWKEYPAIR_5, \"TRAP_ECCURVE_NEWKEYPAIR_5\");\n PERF_STOP_MAPPING.put(PM.TRAP_ECCURVE_NEWKEYPAIR_6, \"TRAP_ECCURVE_NEWKEYPAIR_6\");\n PERF_STOP_MAPPING.put(PM.TRAP_ECCURVE_NEWKEYPAIR_7, \"TRAP_ECCURVE_NEWKEYPAIR_7\");\n PERF_STOP_MAPPING.put(PM.TRAP_ECCURVE_NEWKEYPAIR_COMPLETE, \"TRAP_ECCURVE_NEWKEYPAIR_COMPLETE\");\n\n PERF_STOP_MAPPING.put(PM.TRAP_ECPOINT_ADD_1, \"TRAP_ECPOINT_ADD_1\");\n PERF_STOP_MAPPING.put(PM.TRAP_ECPOINT_ADD_2, \"TRAP_ECPOINT_ADD_2\");\n PERF_STOP_MAPPING.put(PM.TRAP_ECPOINT_ADD_3, \"TRAP_ECPOINT_ADD_3\");\n PERF_STOP_MAPPING.put(PM.TRAP_ECPOINT_ADD_4, \"TRAP_ECPOINT_ADD_4\");\n PERF_STOP_MAPPING.put(PM.TRAP_ECPOINT_ADD_5, \"TRAP_ECPOINT_ADD_5\");\n PERF_STOP_MAPPING.put(PM.TRAP_ECPOINT_ADD_6, \"TRAP_ECPOINT_ADD_6\");\n PERF_STOP_MAPPING.put(PM.TRAP_ECPOINT_ADD_7, \"TRAP_ECPOINT_ADD_7\");\n PERF_STOP_MAPPING.put(PM.TRAP_ECPOINT_ADD_8, \"TRAP_ECPOINT_ADD_8\");\n PERF_STOP_MAPPING.put(PM.TRAP_ECPOINT_ADD_9, \"TRAP_ECPOINT_ADD_9\");\n PERF_STOP_MAPPING.put(PM.TRAP_ECPOINT_ADD_10, \"TRAP_ECPOINT_ADD_10\");\n PERF_STOP_MAPPING.put(PM.TRAP_ECPOINT_ADD_11, \"TRAP_ECPOINT_ADD_11\");\n PERF_STOP_MAPPING.put(PM.TRAP_ECPOINT_ADD_12, \"TRAP_ECPOINT_ADD_12\");\n PERF_STOP_MAPPING.put(PM.TRAP_ECPOINT_ADD_13, \"TRAP_ECPOINT_ADD_13\");\n PERF_STOP_MAPPING.put(PM.TRAP_ECPOINT_ADD_COMPLETE, \"TRAP_ECPOINT_ADD_COMPLETE\");\n\n PERF_STOP_MAPPING.put(PM.TRAP_ECPOINT_MULT_1, \"TRAP_ECPOINT_MULT_1\");\n PERF_STOP_MAPPING.put(PM.TRAP_ECPOINT_MULT_2, \"TRAP_ECPOINT_MULT_2\");\n PERF_STOP_MAPPING.put(PM.TRAP_ECPOINT_MULT_3, \"TRAP_ECPOINT_MULT_3\");\n PERF_STOP_MAPPING.put(PM.TRAP_ECPOINT_MULT_4, \"TRAP_ECPOINT_MULT_4\");\n PERF_STOP_MAPPING.put(PM.TRAP_ECPOINT_MULT_5, \"TRAP_ECPOINT_MULT_5\");\n PERF_STOP_MAPPING.put(PM.TRAP_ECPOINT_MULT_6, \"TRAP_ECPOINT_MULT_6\");\n PERF_STOP_MAPPING.put(PM.TRAP_ECPOINT_MULT_7, \"TRAP_ECPOINT_MULT_7\");\n PERF_STOP_MAPPING.put(PM.TRAP_ECPOINT_MULT_8, \"TRAP_ECPOINT_MULT_8\");\n PERF_STOP_MAPPING.put(PM.TRAP_ECPOINT_MULT_9, \"TRAP_ECPOINT_MULT_9\");\n PERF_STOP_MAPPING.put(PM.TRAP_ECPOINT_MULT_10, \"TRAP_ECPOINT_MULT_10\");\n PERF_STOP_MAPPING.put(PM.TRAP_ECPOINT_MULT_11, \"TRAP_ECPOINT_MULT_11\");\n PERF_STOP_MAPPING.put(PM.TRAP_ECPOINT_MULT_12, \"TRAP_ECPOINT_MULT_12\");\n PERF_STOP_MAPPING.put(PM.TRAP_ECPOINT_MULT_COMPLETE, \"TRAP_ECPOINT_MULT_COMPLETE\");\n\n PERF_STOP_MAPPING.put(PM.TRAP_ECPOINT_MULT_X_1, \"TRAP_ECPOINT_MULT_X_1\");\n PERF_STOP_MAPPING.put(PM.TRAP_ECPOINT_MULT_X_2, \"TRAP_ECPOINT_MULT_X_2\");\n PERF_STOP_MAPPING.put(PM.TRAP_ECPOINT_MULT_X_3, \"TRAP_ECPOINT_MULT_X_3\");\n PERF_STOP_MAPPING.put(PM.TRAP_ECPOINT_MULT_X_4, \"TRAP_ECPOINT_MULT_X_4\");\n PERF_STOP_MAPPING.put(PM.TRAP_ECPOINT_MULT_X_5, \"TRAP_ECPOINT_MULT_X_5\");\n PERF_STOP_MAPPING.put(PM.TRAP_ECPOINT_MULT_X_COMPLETE, \"TRAP_ECPOINT_MULT_X_COMPLETE\");\n\n PERF_STOP_MAPPING.put(PM.TRAP_ECPOINT_NEGATE_1, \"TRAP_ECPOINT_NEGATE_1\");\n PERF_STOP_MAPPING.put(PM.TRAP_ECPOINT_NEGATE_2, \"TRAP_ECPOINT_NEGATE_2\");\n PERF_STOP_MAPPING.put(PM.TRAP_ECPOINT_NEGATE_3, \"TRAP_ECPOINT_NEGATE_3\");\n PERF_STOP_MAPPING.put(PM.TRAP_ECPOINT_NEGATE_4, \"TRAP_ECPOINT_NEGATE_4\");\n PERF_STOP_MAPPING.put(PM.TRAP_ECPOINT_NEGATE_5, \"TRAP_ECPOINT_NEGATE_5\");\n PERF_STOP_MAPPING.put(PM.TRAP_ECPOINT_NEGATE_COMPLETE, \"TRAP_ECPOINT_NEGATE_COMPLETE\");\n\n PERF_STOP_MAPPING.put(PM.TRAP_BIGNAT_SQRT_1, \"TRAP_BIGNAT_SQRT_1\");\n PERF_STOP_MAPPING.put(PM.TRAP_BIGNAT_SQRT_2, \"TRAP_BIGNAT_SQRT_2\");\n PERF_STOP_MAPPING.put(PM.TRAP_BIGNAT_SQRT_3, \"TRAP_BIGNAT_SQRT_3\");\n PERF_STOP_MAPPING.put(PM.TRAP_BIGNAT_SQRT_4, \"TRAP_BIGNAT_SQRT_4\");\n PERF_STOP_MAPPING.put(PM.TRAP_BIGNAT_SQRT_5, \"TRAP_BIGNAT_SQRT_5\");\n PERF_STOP_MAPPING.put(PM.TRAP_BIGNAT_SQRT_6, \"TRAP_BIGNAT_SQRT_6\");\n PERF_STOP_MAPPING.put(PM.TRAP_BIGNAT_SQRT_7, \"TRAP_BIGNAT_SQRT_7\");\n PERF_STOP_MAPPING.put(PM.TRAP_BIGNAT_SQRT_8, \"TRAP_BIGNAT_SQRT_8\");\n PERF_STOP_MAPPING.put(PM.TRAP_BIGNAT_SQRT_9, \"TRAP_BIGNAT_SQRT_9\");\n PERF_STOP_MAPPING.put(PM.TRAP_BIGNAT_SQRT_10, \"TRAP_BIGNAT_SQRT_10\");\n PERF_STOP_MAPPING.put(PM.TRAP_BIGNAT_SQRT_11, \"TRAP_BIGNAT_SQRT_11\");\n PERF_STOP_MAPPING.put(PM.TRAP_BIGNAT_SQRT_12, \"TRAP_BIGNAT_SQRT_12\");\n PERF_STOP_MAPPING.put(PM.TRAP_BIGNAT_SQRT_13, \"TRAP_BIGNAT_SQRT_13\");\n PERF_STOP_MAPPING.put(PM.TRAP_BIGNAT_SQRT_14, \"TRAP_BIGNAT_SQRT_14\");\n PERF_STOP_MAPPING.put(PM.TRAP_BIGNAT_SQRT_15, \"TRAP_BIGNAT_SQRT_15\");\n PERF_STOP_MAPPING.put(PM.TRAP_BIGNAT_SQRT_COMPLETE, \"TRAP_BIGNAT_SQRT_COMPLETE\");\n\n PERF_STOP_MAPPING.put(PM.TRAP_EC_SETCURVE_1, \"TRAP_EC_SETCURVE_1\");\n PERF_STOP_MAPPING.put(PM.TRAP_EC_SETCURVE_2, \"TRAP_EC_SETCURVE_2\");\n PERF_STOP_MAPPING.put(PM.TRAP_EC_SETCURVE_COMPLETE, \"TRAP_EC_SETCURVE_COMPLETE\");\n }\n\n public static String getPerfStopName(short stopID) {\n if (PERF_STOP_MAPPING.containsKey(stopID)) {\n return PERF_STOP_MAPPING.get(stopID);\n } else {\n assert (false);\n return \"PERF_UNDEFINED\";\n }\n }\n\n public static short getPerfStopFromName(String stopName) {\n for (Short stopID : PERF_STOP_MAPPING.keySet()) {\n if (PERF_STOP_MAPPING.get(stopID).equalsIgnoreCase(stopName)) {\n return stopID;\n }\n }\n assert (false);\n return PM.TRAP_UNDEFINED;\n }\n \n\n}",
"public class RunConfig {\n int targetReaderIndex = 0;\n public boolean bTestBN = true;\n public boolean bTestINT = true;\n public boolean bTestEC = true;\n public boolean bTestECPoint = true;\n public boolean bMeasureOnlyTargetOp = false;\n public int numRepeats = 1;\n public int bnBaseTestLength = 256;\n public ArrayList<String> failedTestsList = new ArrayList<>();\n public Class appletToSimulate;\n \n public enum CARD_TYPE {\n PHYSICAL, JCOPSIM, JCARDSIMLOCAL, JCARDSIMREMOTE\n }\n public CARD_TYPE testCardType = CARD_TYPE.PHYSICAL;\n \n public static RunConfig getDefaultConfig() {\n RunConfig runCfg = new RunConfig();\n runCfg.targetReaderIndex = 0;\n runCfg.testCardType = CARD_TYPE.PHYSICAL;\n runCfg.appletToSimulate = OCUnitTests.class;\n \n return runCfg;\n }\n public static RunConfig getConfigSimulator() {\n RunConfig runCfg = new RunConfig();\n runCfg.targetReaderIndex = 0;\n runCfg.testCardType = CARD_TYPE.JCARDSIMLOCAL;\n runCfg.bTestBN = false;\n runCfg.bTestINT = false;\n runCfg.bTestEC = false;\n runCfg.appletToSimulate = OCUnitTests.class;\n return runCfg;\n }\n public static RunConfig getConfig(boolean bTestBN, boolean bTestINT, boolean bTestEC, int numRepeats, CARD_TYPE cardType) {\n RunConfig runCfg = new RunConfig();\n runCfg.targetReaderIndex = 0;\n runCfg.testCardType = cardType;\n runCfg.bTestBN = bTestBN;\n runCfg.bTestINT = bTestINT;\n runCfg.bTestEC = bTestEC;\n runCfg.numRepeats = numRepeats;\n runCfg.appletToSimulate = OCUnitTests.class;\n return runCfg;\n }\n}",
"public class Util {\n\n public static String toHex(byte[] bytes) {\n return toHex(bytes, 0, bytes.length);\n }\n\n public static String toHex(byte[] bytes, int offset, int len) {\n // StringBuilder buff = new StringBuilder();\n String result = \"\";\n\n for (int i = offset; i < offset + len; i++) {\n result += String.format(\"%02X\", bytes[i]);\n }\n\n return result;\n }\n\n public static String bytesToHex(byte[] bytes) {\n char[] hexArray = \"0123456789ABCDEF\".toCharArray();\n char[] hexChars = new char[bytes.length * 2];\n for (int j = 0; j < bytes.length; j++) {\n int v = bytes[j] & 0xFF;\n hexChars[j * 2] = hexArray[v >>> 4];\n hexChars[j * 2 + 1] = hexArray[v & 0x0F];\n }\n return new String(hexChars);\n }\n \n \n /* Utils */\n public static short getShort(byte[] buffer, int offset) {\n return ByteBuffer.wrap(buffer, offset, 2).order(ByteOrder.BIG_ENDIAN).getShort();\n }\n\n public static short readShort(byte[] data, int offset) {\n return (short) (((data[offset] << 8)) | ((data[offset + 1] & 0xff)));\n }\n\n public static byte[] shortToByteArray(int s) {\n return new byte[]{(byte) ((s & 0xFF00) >> 8), (byte) (s & 0x00FF)};\n }\n \n \n public static byte[] joinArray(byte[]... arrays) {\n int length = 0;\n for (byte[] array : arrays) {\n length += array.length;\n }\n\n final byte[] result = new byte[length];\n\n int offset = 0;\n for (byte[] array : arrays) {\n System.arraycopy(array, 0, result, offset, array.length);\n offset += array.length;\n }\n\n return result;\n }\n\n public static byte[] trimLeadingZeroes(byte[] array) {\n short startOffset = 0;\n for (int i = 0; i < array.length; i++) {\n if (array[i] != 0) {\n break;\n } else {\n // still zero\n startOffset++;\n }\n }\n\n byte[] result = new byte[array.length - startOffset];\n System.arraycopy(array, startOffset, result, 0, array.length - startOffset);\n return result;\n }\n\n public static byte[] concat(byte[] a, byte[] b) {\n int aLen = a.length;\n int bLen = b.length;\n byte[] c = new byte[aLen + bLen];\n System.arraycopy(a, 0, c, 0, aLen);\n System.arraycopy(b, 0, c, aLen, bLen);\n return c;\n }\n\n public static byte[] concat(byte[] a, byte[] b, byte[] c) {\n byte[] tmp_conc = concat(a, b);\n return concat(tmp_conc, c);\n\n }\n \n \n public static ECPoint randECPoint() throws Exception {\n Security.addProvider(new BouncyCastleProvider());\n\n ECParameterSpec ecSpec_named = ECNamedCurveTable.getParameterSpec(\"secp256r1\"); // NIST P-256\n KeyPairGenerator kpg = KeyPairGenerator.getInstance(\"ECDSA\", \"BC\");\n kpg.initialize(ecSpec_named);\n KeyPair apair = kpg.generateKeyPair();\n ECPublicKey apub = (ECPublicKey) apair.getPublic();\n return apub.getQ();\n } \n \n public static byte[] IntToBytes(int val) {\n byte[] data = new byte[5];\n if (val < 0) {\n data[0] = 0x01;\n } else {\n data[0] = 0x00;\n }\n\n int unsigned = Math.abs(val);\n data[1] = (byte) (unsigned >>> 24);\n data[2] = (byte) (unsigned >>> 16);\n data[3] = (byte) (unsigned >>> 8);\n data[4] = (byte) unsigned;\n\n return data;\n }\n\n public static int BytesToInt(byte[] data) {\n int val = (data[1] << 24)\n | ((data[2] & 0xFF) << 16)\n | ((data[3] & 0xFF) << 8)\n | (data[4] & 0xFF);\n\n if (data[0] == 0x01) {\n val = val * -1;\n }\n\n return val;\n } \n \n private static boolean checkSW(ResponseAPDU response) {\n if (response.getSW() != (ISO7816.SW_NO_ERROR & 0xffff)) {\n System.err.printf(\"Received error status: %02X.\\n\",\n response.getSW());\n return false;\n }\n return true;\n }\n\n public static byte[] hexStringToByteArray(String s) {\n String sanitized = s.replace(\" \", \"\");\n byte[] b = new byte[sanitized.length() / 2];\n for (int i = 0; i < b.length; i++) {\n int index = i * 2;\n int v = Integer.parseInt(sanitized.substring(index, index + 2), 16);\n b[i] = (byte) v;\n }\n return b;\n }\n \n \n /**\n * *Math Stuff**\n */\n public static BigInteger randomBigNat(int maxNumBitLength) {\n Random rnd = new Random();\n BigInteger aRandomBigInt;\n while (true) {\n do {\n aRandomBigInt = new BigInteger(maxNumBitLength, rnd);\n\n } while (aRandomBigInt.compareTo(new BigInteger(\"1\")) < 1);\n\n if ((Util.trimLeadingZeroes(aRandomBigInt.toByteArray()).length != maxNumBitLength / 8) || (aRandomBigInt.toByteArray()).length != maxNumBitLength / 8) {\n // After serialization, number is longer or shorter - generate new one \n } else {\n // We have proper number\n return aRandomBigInt;\n }\n }\n }\n\n public static byte[] SerializeBigInteger(BigInteger BigInt) {\n\n int bnlen = BigInt.bitLength() / 8;\n\n byte[] large_int_b = new byte[bnlen];\n Arrays.fill(large_int_b, (byte) 0);\n int int_len = BigInt.toByteArray().length;\n if (int_len == bnlen) {\n large_int_b = BigInt.toByteArray();\n } else if (int_len > bnlen) {\n large_int_b = Arrays.copyOfRange(BigInt.toByteArray(), int_len\n - bnlen, int_len);\n } else if (int_len < bnlen) {\n System.arraycopy(BigInt.toByteArray(), 0, large_int_b,\n large_int_b.length - int_len, int_len);\n }\n\n return large_int_b;\n }\n\n public static long pow_mod(long x, long n, long p) {\n if (n == 0) {\n return 1;\n }\n if ((n & 1) == 1) {\n return (pow_mod(x, n - 1, p) * x) % p;\n }\n x = pow_mod(x, n / 2, p);\n return (x * x) % p;\n }\n\n /* Takes as input an odd prime p and n < p and returns r\n * such that r * r = n [mod p]. */\n public static BigInteger tonelli_shanks(BigInteger n, BigInteger p) {\n\n //1. By factoring out powers of 2, find Q and S such that p-1=Q2^S p-1=Q*2^S and Q is odd\n BigInteger p_1 = p.subtract(BigInteger.ONE);\n BigInteger S = BigInteger.ZERO;\n BigInteger Q = p_1;\n\n BigInteger two = BigInteger.valueOf(2);\n\n while (Q.mod(two).compareTo(BigInteger.ONE) != 0) { //while Q is not odd\n Q = Q.divide(two);\n //Q = p_1.divide(two.modPow(S, p));\n S = S.add(BigInteger.ONE);\n }\n\n //2. Find the first quadratic non-residue z by brute-force search\n BigInteger z = BigInteger.ONE;\n while (z.modPow(p_1.divide(BigInteger.valueOf(2)), p).compareTo(p_1) != 0) {\n z = z.add(BigInteger.ONE);\n }\n\n System.out.println(\"n (y^2) : \" + Util.bytesToHex(n.toByteArray()));\n System.out.println(\"Q : \" + Util.bytesToHex(Q.toByteArray()));\n System.out.println(\"S : \" + Util.bytesToHex(S.toByteArray()));\n\n BigInteger R = n.modPow(Q.add(BigInteger.ONE).divide(BigInteger.valueOf(2)), p);\n BigInteger c = z.modPow(Q, p);\n BigInteger t = n.modPow(Q, p);\n BigInteger M = S;\n\n while (t.compareTo(BigInteger.ONE) != 0) {\n BigInteger tt = t;\n BigInteger i = BigInteger.ZERO;\n while (tt.compareTo(BigInteger.ONE) != 0) {\n System.out.println(\"t : \" + tt.toString());\n tt = tt.multiply(tt).mod(p);\n i = i.add(BigInteger.ONE);\n //if (i.compareTo(m)==0) return BigInteger.ZERO;\n }\n\n BigInteger M_i_1 = M.subtract(i).subtract(BigInteger.ONE);\n System.out.println(\"M : \" + M.toString());\n System.out.println(\"i : \" + i.toString());\n System.out.println(\"M_i_1: \" + M_i_1.toString());\n System.out.println(\"===================\");\n BigInteger b = c.modPow(two.modPow(M_i_1, p_1), p);\n BigInteger b2 = b.multiply(b).mod(p);\n\n R = R.multiply(b).mod(p);\n c = b2;\n t = t.multiply(b2).mod(p);\n M = i;\n }\n\n if (R.multiply(R).mod(p).compareTo(n) == 0) {\n return R;\n } else {\n return BigInteger.ZERO;\n }\n }\n\n /* Takes as input an odd prime p and n < p and returns r\n * such that r * r = n [mod p]. */\n public static BigInteger tonellishanks(BigInteger n, BigInteger p) {\n //1. By factoring out powers of 2, find Q and S such that p-1=Q2^S p-1=Q*2^S and Q is odd\n BigInteger p_1 = p.subtract(BigInteger.ONE);\n BigInteger S = BigInteger.ZERO;\n BigInteger Q = p_1;\n\n BigInteger two = BigInteger.valueOf(2);\n\n System.out.println(\"p : \" + Util.bytesToHex(p.toByteArray()));\n System.out.println(\"p is prime: \" + p.isProbablePrime(10));\n System.out.println(\"n : \" + Util.bytesToHex(n.toByteArray()));\n System.out.println(\"Q : \" + Util.bytesToHex(Q.toByteArray()));\n System.out.println(\"S : \" + Util.bytesToHex(S.toByteArray()));\n\n while (Q.mod(two).compareTo(BigInteger.ONE) != 0) { //while Q is not odd\n Q = p_1.divide(two.modPow(S, p));\n S = S.add(BigInteger.ONE);\n\n \t//System.out.println(\"Iter n: \" + bytesToHex(n.toByteArray()));\n //System.out.println(\"Iter Q: \" + bytesToHex(Q.toByteArray()));\n //System.out.println(\"Iter S: \" + bytesToHex(S.toByteArray()));\n }\n\n \t//System.out.println(\"n: \" + bytesToHex(n.toByteArray()));\n //System.out.println(\"Q: \" + bytesToHex(Q.toByteArray()));\n //System.out.println(\"S: \" + bytesToHex(S.toByteArray()));\n return n;\n }\n \n private static ECPoint ECPointDeSerialization(byte[] serialized_point,\n int offset, int pointLength, ECCurve curve) {\n\n byte[] x_b = new byte[pointLength / 2];\n byte[] y_b = new byte[pointLength / 2];\n\n // System.out.println(\"Serialized Point: \" + toHex(serialized_point));\n // src -- This is the source array.\n // srcPos -- This is the starting position in the source array.\n // dest -- This is the destination array.\n // destPos -- This is the starting position in the destination data.\n // length -- This is the number of array elements to be copied.\n System.arraycopy(serialized_point, offset + 1, x_b, 0, pointLength / 2);\n BigInteger x = new BigInteger(bytesToHex(x_b), 16);\n // System.out.println(\"X:\" + toHex(x_b));\n System.arraycopy(serialized_point, offset + (pointLength / 2 + 1), y_b, 0, pointLength / 2);\n BigInteger y = new BigInteger(bytesToHex(y_b), 16);\n // System.out.println(\"Y:\" + toHex(y_b));\n\n ECPoint point = curve.createPoint(x, y);\n\n return point;\n } \n \n}",
"public static byte[] hexStringToByteArray(String s) {\n String sanitized = s.replace(\" \", \"\");\n byte[] b = new byte[sanitized.length() / 2];\n for (int i = 0; i < b.length; i++) {\n int index = i * 2;\n int v = Integer.parseInt(sanitized.substring(index, index + 2), 16);\n b[i] = (byte) v;\n }\n return b;\n}",
"public class TestClient {\n public static boolean _FAIL_ON_ASSERT = false;\n public static int NUM_OP_REPEATS = 1;\n \n // Base length of test inputs (in bits) which corresponds to same length of ECC \n // E.g., if you like to test 256b ECC, operations with 256b Bignat numbers are performed \n // Important: applet is compiled with MAX_BIGNAT_SIZE constant which must be large enough to hold intermediate computations. \n // MAX_BIGNAT_SIZE constant must be at least 2*(ECC_BASE_TEST_LENGTH / 8) + 1.\n public final static int BIGNAT_BASE_TEST_LENGTH = 256; \n \n public static boolean _TEST_BN = true;\n public static boolean _TEST_INT = false;\n public static boolean _TEST_EC = true;\n \n public static boolean _MEASURE_PERF = false;\n public static boolean _MEASURE_PERF_ONLY_TARGET = false;\n \n\n\n static ArrayList<Entry<String, Long>> m_perfResults = new ArrayList<>();\n\n public static String format = \"%-40s:%s%n\\n-------------------------------------------------------------------------------\\n\";\n\n public static byte[] OPENCRYPTO_UNITTEST_APPLET_AID = {0x55, 0x6e, 0x69, 0x74, 0x54, 0x65, 0x73, 0x74, 0x73};\n public static byte[] APDU_CLEANUP = {OCUnitTests.CLA_OC_UT, OCUnitTests.INS_CLEANUP, (byte) 0x00, (byte) 0x00, (byte) 0x00};\n public static byte[] APDU_GET_PROFILE_LOCKS = {OCUnitTests.CLA_OC_UT, OCUnitTests.INS_GET_PROFILE_LOCKS, (byte) 0x00, (byte) 0x00, (byte) 0x00};\n\n\n public static void main(String[] args) throws Exception {\n \ttry {\n Integer targetReader = 0;\n if (args.length > 0) {\n targetReader = Integer.getInteger(args[0]);\n }\n\n PerfTests perfTests = new PerfTests();\n if (_MEASURE_PERF) {\n RunConfig runCfg = RunConfig.getConfig(_TEST_BN, _TEST_INT, _TEST_EC, NUM_OP_REPEATS, RunConfig.CARD_TYPE.PHYSICAL);\n runCfg.numRepeats = 1;\n runCfg.targetReaderIndex = targetReader;\n perfTests.RunPerformanceTests(runCfg);\n }\n else if (_MEASURE_PERF_ONLY_TARGET) {\n RunConfig runCfg = RunConfig.getConfig(_TEST_BN, _TEST_INT, _TEST_EC, NUM_OP_REPEATS, RunConfig.CARD_TYPE.PHYSICAL);\n runCfg.targetReaderIndex = targetReader;\n runCfg.bMeasureOnlyTargetOp = true;\n perfTests.RunPerformanceTests(runCfg);\n }\n else {\n RunConfig runCfg = RunConfig.getConfig(_TEST_BN, _TEST_INT, _TEST_EC, NUM_OP_REPEATS, RunConfig.CARD_TYPE.JCARDSIMLOCAL);\n runCfg.targetReaderIndex = targetReader;\n \n // First run debug operations on simulator and real card (if any)\n/* OpenCryptoFunctionalTests_debug(runCfg);\n runCfg.failedTestsList.clear();\n runCfg.testCardType = RunConfig.CARD_TYPE.PHYSICAL;\n OpenCryptoFunctionalTests_debug(runCfg);\n runCfg.failedTestsList.clear();\n*/ \n // Run standard tests on simulator then real card (if any)\n //runCfg.testCardType = RunConfig.CARD_TYPE.JCARDSIMLOCAL;\n //OpenCryptoFunctionalTests(runCfg);\n //runCfg.failedTestsList.clear();\n //runCfg.testCardType = RunConfig.CARD_TYPE.PHYSICAL;\n OpenCryptoFunctionalTests(runCfg);\n runCfg.failedTestsList.clear();\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n public static boolean OpenCryptoFunctionalTests(RunConfig runCfg) throws Exception {\n try {\n CardManager cardMngr = new CardManager(true, OPENCRYPTO_UNITTEST_APPLET_AID);\n\n System.out.print(\"Connecting to card...\");\n if (!cardMngr.Connect(runCfg)) {\n return false;\n }\n System.out.println(\" Done.\");\n\n System.out.println(\"\\n--------------Unit Tests--------------\");\n\n CommandAPDU cmd;\n ResponseAPDU response;\n String operationName = \"\";\n boolean bResult = false;\n\n m_perfResults.clear();\n String logFileName = String.format(\"OC_PERF_log_%d.csv\", System.currentTimeMillis());\n FileOutputStream perfFile = new FileOutputStream(logFileName);\n\n cardMngr.transmit(new CommandAPDU(PerfTests.PERF_COMMAND_NONE));\n cardMngr.transmit(new CommandAPDU(APDU_CLEANUP)); \n\n // Obtain allocated bytes in RAM and EEPROM\n byte[] bogusArray = new byte[1]; // Bogus array with single zero byte - NXP J3H145G P60 fails when no data are provided\n cmd = new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_GET_ALLOCATOR_STATS, 0, 0, bogusArray); \n response = cardMngr.transmit(cmd);\n byte[] data = response.getData();\n System.out.println(String.format(\"Data allocator: RAM = %d, EEPROM = %d\", Util.getShort(data, (short) 0), Util.getShort(data, (short) 2)));\n // Print memory snapshots from allocation\n for (int offset = 4; offset < data.length; offset += 6) {\n System.out.println(String.format(\"Tag '%d': RAM = %d, EEPROM = %d\", Util.getShort(data, offset), Util.getShort(data, (short) (offset + 2)), Util.getShort(data, (short) (offset + 4))));\n }\n\n if (runCfg.bTestBN) {\n operationName = \"BigNatural Storage: \";\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n System.out.println(String.format(\"%s (%d)\", operationName, repeat));\n BigInteger num = Util.randomBigNat(BIGNAT_BASE_TEST_LENGTH);//Generate Int\n cmd = new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_BN_STR, 0, 0, num.toByteArray());\n performCommand(operationName, cardMngr, cmd, num, perfFile, runCfg.failedTestsList);\n }\n\n operationName = \"BigNatural Addition: \";\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n System.out.println(String.format(\"%s (%d)\", operationName, repeat));\n BigInteger num1 = Util.randomBigNat(BIGNAT_BASE_TEST_LENGTH - 1);//Generate Int1\n BigInteger num2 = Util.randomBigNat(BIGNAT_BASE_TEST_LENGTH - 1);//Generate Int2\n BigInteger result = num1.add(num2); \n cmd = new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_BN_ADD, num1.toByteArray().length, 0, Util.concat(num1.toByteArray(), num2.toByteArray()));\n performCommand(operationName, cardMngr, cmd, result, perfFile, runCfg.failedTestsList);\n }\n\n operationName = \"BigNatural Subtraction: \";\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n System.out.println(String.format(\"%s (%d)\", operationName, repeat));\n BigInteger num1 = Util.randomBigNat(BIGNAT_BASE_TEST_LENGTH - 1);//Generate Int1\n BigInteger num2 = Util.randomBigNat(BIGNAT_BASE_TEST_LENGTH - 1);//Generate Int2\n BigInteger result = num1.subtract(num2); \n cmd = new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_BN_SUB, num1.toByteArray().length, 0, Util.concat(num1.toByteArray(), num2.toByteArray()));\n performCommand(operationName, cardMngr, cmd, result, perfFile, runCfg.failedTestsList);\n }\n\n operationName = \"BigNatural Multiplication: \";\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n System.out.println(String.format(\"%s (%d)\", operationName, repeat));\n BigInteger num1 = Util.randomBigNat(BIGNAT_BASE_TEST_LENGTH);//Generate Int1\n BigInteger num2 = Util.randomBigNat(BIGNAT_BASE_TEST_LENGTH);//Generate Int2\n BigInteger result = num1.multiply(num2); \n cmd = new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_BN_MUL, num1.toByteArray().length, 0, Util.concat(num1.toByteArray(), num2.toByteArray()));\n performCommand(operationName, cardMngr, cmd, result, perfFile, runCfg.failedTestsList);\n }\n\n operationName = \"BigNatural Multiplication schoolbook: \";\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n System.out.println(String.format(\"%s (%d)\", operationName, repeat));\n BigInteger num1 = Util.randomBigNat(BIGNAT_BASE_TEST_LENGTH);//Generate Int1\n BigInteger num2 = Util.randomBigNat(BIGNAT_BASE_TEST_LENGTH);//Generate Int2\n BigInteger result = num1.multiply(num2);\n cmd = new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_BN_MUL_SCHOOL, num1.toByteArray().length, 0, Util.concat(num1.toByteArray(), num2.toByteArray()));\n performCommand(operationName, cardMngr, cmd, result, perfFile, runCfg.failedTestsList);\n }\n\n operationName = \"BigNatural Exponentiation: \";\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n System.out.println(String.format(\"%s (%d)\", operationName, repeat));\n BigInteger num1 = Util.randomBigNat(BIGNAT_BASE_TEST_LENGTH / 4); //Generate Int1\t\t\n BigInteger num2 = BigInteger.valueOf(3); //Generate Int2\n BigInteger result = num1.pow(3); \n cmd = new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_BN_EXP, num1.toByteArray().length, result.toByteArray().length, Util.concat(num1.toByteArray(), num2.toByteArray()));\n performCommand(operationName, cardMngr, cmd, result, perfFile, runCfg.failedTestsList);\n }\n\n operationName = \"BigNatural Modulo: \";\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n System.out.println(String.format(\"%s (%d)\", operationName, repeat));\n BigInteger num1 = Util.randomBigNat(BIGNAT_BASE_TEST_LENGTH);//Generate Int1\n BigInteger num2 = Util.randomBigNat(BIGNAT_BASE_TEST_LENGTH - 1);//Generate Int2\n BigInteger result = num1.mod(num2); \n cmd = new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_BN_MOD, (num1.toByteArray()).length, 0, Util.concat((num1.toByteArray()), (num2.toByteArray())));\n performCommand(operationName, cardMngr, cmd, result, perfFile, runCfg.failedTestsList, true);\n }\n/* \n operationName = \"BigNatural sqrt_FP: \";\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n System.out.println(String.format(\"%s (%d)\", operationName, repeat));\n BigInteger num1 = Util.randomBigNat(256);//Generate Int1\n BigInteger resSqrt = tonelli_shanks(num1, new BigInteger(1, SecP256r1.p));\n cmd = new CommandAPDU(Configuration.CLA_MPC, Configuration.INS_BN_SQRT, (num1.toByteArray()).length, 0,num1.toByteArray());\n performCommand(operationName, cardMngr, cmd, resSqrt, perfFile, true);\n } \n/**/\n operationName = \"BigNatural Addition (Modulo): \";\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n System.out.println(String.format(\"%s (%d)\", operationName, repeat));\n BigInteger num1 = Util.randomBigNat(BIGNAT_BASE_TEST_LENGTH);//Generate Int1\n BigInteger num2 = Util.randomBigNat(BIGNAT_BASE_TEST_LENGTH);//Generate Int2\n BigInteger num3 = Util.randomBigNat(BIGNAT_BASE_TEST_LENGTH / 8);//Generate Int3\n BigInteger result = (num1.add(num2)).mod(num3);\n cmd = new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_BN_ADD_MOD, (num1.toByteArray()).length, (num2.toByteArray()).length, Util.concat((num1.toByteArray()), (num2.toByteArray()), (num3.toByteArray())));\n performCommand(operationName, cardMngr, cmd, result, perfFile, runCfg.failedTestsList, true);\n }\n\n operationName = \"BigNatural Subtraction (Modulo): \";\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n System.out.println(String.format(\"%s (%d)\", operationName, repeat));\n BigInteger num1 = Util.randomBigNat(BIGNAT_BASE_TEST_LENGTH);//Generate Int1\n BigInteger num2 = Util.randomBigNat(BIGNAT_BASE_TEST_LENGTH);//Generate Int2\n BigInteger num3 = Util.randomBigNat(BIGNAT_BASE_TEST_LENGTH / 8);//Generate Int3\n BigInteger result = (num1.subtract(num2)).mod(num3);\n cmd = new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_BN_SUB_MOD, (num1.toByteArray()).length, (num2.toByteArray()).length, Util.concat((num1.toByteArray()), (num2.toByteArray()), (num3.toByteArray())));\n performCommand(operationName, cardMngr, cmd, result, perfFile, runCfg.failedTestsList, true);\n }\n\n operationName = \"BigNatural Multiplication (Modulo): \";\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n System.out.println(String.format(\"%s (%d)\", operationName, repeat));\n BigInteger num1 = Util.randomBigNat(BIGNAT_BASE_TEST_LENGTH);//Generate Int1\n BigInteger num2 = Util.randomBigNat(BIGNAT_BASE_TEST_LENGTH);//Generate Int2\n BigInteger num3 = Util.randomBigNat(BIGNAT_BASE_TEST_LENGTH / 8);//Generate Int3\n BigInteger result = (num1.multiply(num2)).mod(num3);\n cmd = new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_BN_MUL_MOD, (num1.toByteArray()).length, (num2.toByteArray()).length, Util.concat((num1.toByteArray()), (num2.toByteArray()), (num3.toByteArray())));\n performCommand(operationName, cardMngr, cmd, result, perfFile, runCfg.failedTestsList, true);\n }\n\n operationName = \"BigNatural Exponentiation (Modulo): \";\n int power = 2;\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n System.out.println(String.format(\"%s (%d)\", operationName, repeat));\n BigInteger num1 = Util.randomBigNat(BIGNAT_BASE_TEST_LENGTH); //Generate Int1 (base)\n BigInteger num2 = BigInteger.valueOf(power); //Generate Int2 (exp)\n BigInteger num3 = Util.randomBigNat(BIGNAT_BASE_TEST_LENGTH);//Generate Int3 (mod)\n BigInteger result = (num1.modPow(num2, num3));\n System.out.println(String.format(\"num1: %s\", num1.toString(16)));\n System.out.println(String.format(\"num2: %s\", num2.toString(16)));\n System.out.println(String.format(\"num3: %s\", num3.toString(16)));\n\n cmd = new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_BN_EXP_MOD, Util.trimLeadingZeroes(num1.toByteArray()).length, Util.trimLeadingZeroes(num2.toByteArray()).length, Util.concat(Util.trimLeadingZeroes(num1.toByteArray()), Util.trimLeadingZeroes(num2.toByteArray()), Util.trimLeadingZeroes(num3.toByteArray())));\n performCommand(operationName, cardMngr, cmd, result, perfFile, runCfg.failedTestsList, true);\n }\n \n operationName = \"BigNatural Power2 (Modulo): \";\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n System.out.println(String.format(\"%s (%d)\", operationName, repeat));\n BigInteger num1 = Util.randomBigNat(BIGNAT_BASE_TEST_LENGTH); //Generate Int1 (base)\n BigInteger mod = Util.randomBigNat(BIGNAT_BASE_TEST_LENGTH);//Generate Int3 (mod)\n BigInteger result = (num1.modPow(BigInteger.valueOf(2), mod));\n\n cmd = new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_BN_POW2_MOD, Util.trimLeadingZeroes(num1.toByteArray()).length, Util.trimLeadingZeroes(mod.toByteArray()).length, Util.concat(Util.trimLeadingZeroes(num1.toByteArray()), Util.trimLeadingZeroes(mod.toByteArray())));\n performCommand(operationName, cardMngr, cmd, result, perfFile, runCfg.failedTestsList, true);\n }\n\n operationName = \"BigNatural Inversion (Modulo): \";\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n System.out.println(String.format(\"%s (%d)\", operationName, repeat));\n BigInteger num1 = Util.randomBigNat(BIGNAT_BASE_TEST_LENGTH + BIGNAT_BASE_TEST_LENGTH / 2); //Generate base\n BigInteger num2 = new BigInteger(1,SecP256r1.p);//Generate mod\n BigInteger num3 = Util.randomBigNat(BIGNAT_BASE_TEST_LENGTH);//Generate Int3 (mod)\n System.out.println(String.format(\"num1: %s\", num1.toString(16)));\n System.out.println(String.format(\"num2: %s\", num2.toString(16)));\n System.out.println(String.format(\"num3: %s\", num3.toString(16)));\n BigInteger result = num1.modInverse(num2).multiply(num1).mod(num3);\n cmd = new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_BN_INV_MOD, Util.trimLeadingZeroes(num1.toByteArray()).length, 0, Util.concat(Util.trimLeadingZeroes(num1.toByteArray()), Util.trimLeadingZeroes(num2.toByteArray())));\n response = cardMngr.transmit(cmd);\n if (response.getSW() == (ISO7816.SW_NO_ERROR & 0xffff)) {\n BigInteger respInt = new BigInteger(1, response.getData()).multiply(num1).mod(num3);\n bResult = result.compareTo(respInt) == 0;\n\n if (!bResult) {\n System.out.println(String.format(\"Expected: %s\", result.toString(16)));\n System.out.println(String.format(\"Obtained: %s\", respInt.toString(16)));\n }\n } else {\n bResult = false;\n System.out.println(String.format(\"fail (0x%x)\", response.getSW()));\n }\n logResponse(operationName, bResult, cardMngr.m_lastTransmitTime, perfFile, runCfg.failedTestsList);\n if (!bResult) {\n String failedAPDU = formatFailedAPDUCmd(cmd);\n runCfg.failedTestsList.add(failedAPDU);\n }\n\n cardMngr.transmit(new CommandAPDU(APDU_CLEANUP)); \n }\n }\n\n if (runCfg.bTestINT) {\n operationName = \"Integer Storage: \";\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n System.out.println(String.format(\"%s (%d)\", operationName, repeat));\n int num = ThreadLocalRandom.current().nextInt(Integer.MIN_VALUE, Integer.MAX_VALUE);\n cmd = new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_INT_STR, 0, 0, Util.IntToBytes(num));\n response = cardMngr.transmit(cmd);\n verifyAndLogResponse(operationName, response, cardMngr.m_lastTransmitTime, num, perfFile, runCfg.failedTestsList);\n cardMngr.transmit(new CommandAPDU(APDU_CLEANUP)); \n }\n\n operationName = \"Integer Addition: \";\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n System.out.println(String.format(\"%s (%d)\", operationName, repeat));\n int num_add_1 = ThreadLocalRandom.current().nextInt(Integer.MIN_VALUE, Integer.MAX_VALUE);\n int num_add_2 = ThreadLocalRandom.current().nextInt(Integer.MIN_VALUE, Integer.MAX_VALUE);\n //num_add_1 = Integer.MAX_VALUE;\n //num_add_2 = Integer.MAX_VALUE;\n int num_add = num_add_1 + num_add_2;\n\n //System.out.println(\"op1 : \" + bytesToHex(Util.IntToBytes(num_add_1)));\n //System.out.println(\"op2 : \" + bytesToHex(Util.IntToBytes(num_add_2)));\n //System.out.println(\"result: \" + bytesToHex(Util.IntToBytes(num_add)));\n cmd = new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_INT_ADD, Util.IntToBytes(num_add_1).length, 0, Util.concat(Util.IntToBytes(num_add_1), Util.IntToBytes(num_add_2)));\n response = cardMngr.transmit(cmd);\n verifyAndLogResponse(operationName, response, cardMngr.m_lastTransmitTime, num_add, perfFile, runCfg.failedTestsList);\n cardMngr.transmit(new CommandAPDU(APDU_CLEANUP)); \n }\n\n operationName = \"Integer Subtraction: \";\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n System.out.println(String.format(\"%s (%d)\", operationName, repeat));\n int num_sub_1 = ThreadLocalRandom.current().nextInt(Integer.MIN_VALUE, Integer.MAX_VALUE);\n int num_sub_2 = ThreadLocalRandom.current().nextInt(Integer.MIN_VALUE, Integer.MAX_VALUE);\n //num_sub_1 = Integer.MAX_VALUE-1;\n //num_sub_2 = Integer.MAX_VALUE;\n int num_sub = num_sub_1 - num_sub_2;\n cmd = new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_INT_SUB, Util.IntToBytes(num_sub_1).length, 0, Util.concat(Util.IntToBytes(num_sub_1), Util.IntToBytes(num_sub_2)));\n response = cardMngr.transmit(cmd);\n verifyAndLogResponse(operationName, response, cardMngr.m_lastTransmitTime, num_sub, perfFile, runCfg.failedTestsList);\n cardMngr.transmit(new CommandAPDU(APDU_CLEANUP)); \n }\n\n operationName = \"Integer Multiplication: \";\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n System.out.println(String.format(\"%s (%d)\", operationName, repeat));\n int num_mul_1 = ThreadLocalRandom.current().nextInt((int) (Math.sqrt(Integer.MIN_VALUE)), (int) (Math.sqrt(Integer.MAX_VALUE)));\n int num_mul_2 = ThreadLocalRandom.current().nextInt((int) (Math.sqrt(Integer.MIN_VALUE)), (int) (Math.sqrt(Integer.MAX_VALUE)));\n\n //Avoid overflows\n int num_mul = 0; //(java int may overflow!!)\n while (num_mul == 0) {\n try {\n num_mul = Math.multiplyExact(num_mul_1, num_mul_2);\n //num_mul = 6;\n } catch (Exception e) { // or your specific exception\n }\n\n }\n cmd = new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_INT_MUL, Util.IntToBytes(num_mul_1).length, 0, Util.concat(Util.IntToBytes(num_mul_1), Util.IntToBytes(num_mul_2)));\n response = cardMngr.transmit(cmd);\n verifyAndLogResponse(operationName, response, cardMngr.m_lastTransmitTime, num_mul, perfFile, runCfg.failedTestsList);\n cardMngr.transmit(new CommandAPDU(APDU_CLEANUP)); \n }\n\n\n operationName = \"Integer Division: \";\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n System.out.println(String.format(\"%s (%d)\", operationName, repeat));\n int num_div_1 = ThreadLocalRandom.current().nextInt(Integer.MIN_VALUE, Integer.MAX_VALUE);\n int num_div_2 = ThreadLocalRandom.current().nextInt(Integer.MIN_VALUE, Integer.MAX_VALUE);\n int num_div = num_div_1 / num_div_2;\n cmd = new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_INT_DIV, Util.IntToBytes(num_div_1).length, 0, Util.concat(Util.IntToBytes(num_div_1), Util.IntToBytes(num_div_2)));\n response = cardMngr.transmit(cmd);\n verifyAndLogResponse(operationName, response, cardMngr.m_lastTransmitTime, num_div, perfFile, runCfg.failedTestsList);\n cardMngr.transmit(new CommandAPDU(APDU_CLEANUP)); \n }\n\n /*\n //14^8 is quite/very close to the max integer value\n System.out.print(\"Integer Exponentiation: \");\n int base = ThreadLocalRandom.current().nextInt(-14, 14);\n int exp = ThreadLocalRandom.current().nextInt(-8, 8);\n int num_exp = Math.pow(base, exp);\n cmd = new CommandAPDU(Configuration.CLA_MPC, Configuration.INS_INT_DIV, Util.IntToBytes(num_div_1).length, 0, Util.concat(Util.IntToBytes(num_div_1), Util.IntToBytes(num_div_2)));\n response = transmit(cmd);\n System.out.println(BytesToInt(response.getData())==num_div);\t\t\t}\n */\n\n operationName = \"Integer Modulo: \";\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n System.out.println(String.format(\"%s (%d)\", operationName, repeat));\n int num_mod_1 = ThreadLocalRandom.current().nextInt(Integer.MIN_VALUE, Integer.MAX_VALUE);\n int num_mod_2 = ThreadLocalRandom.current().nextInt(Integer.MIN_VALUE, Integer.MAX_VALUE);\n int num_mod = num_mod_1 % num_mod_2;\n cmd = new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_INT_MOD, Util.IntToBytes(num_mod_1).length, 0, Util.concat(Util.IntToBytes(num_mod_1), Util.IntToBytes(num_mod_2)));\n response = cardMngr.transmit(cmd);\n verifyAndLogResponse(operationName, response, cardMngr.m_lastTransmitTime, num_mod, perfFile, runCfg.failedTestsList);\n cardMngr.transmit(new CommandAPDU(APDU_CLEANUP)); \n }\n }\n\n if (runCfg.bTestEC) {\n operationName = \"EC Point Generation: \";\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n System.out.println(String.format(\"%s (%d)\", operationName, repeat));\n cmd = new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_EC_GEN, 0, 0, bogusArray);\n response = cardMngr.transmit(cmd);\n PerfTests.writePerfLog(operationName, response.getSW() == (ISO7816.SW_NO_ERROR & 0xffff), cardMngr.m_lastTransmitTime, m_perfResults, perfFile);\n cardMngr.transmit(new CommandAPDU(APDU_CLEANUP)); \n }\n\n operationName = \"EC Point Add: \";\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n System.out.println(String.format(\"%s (%d)\", operationName, repeat));\n ECPoint pnt_1 = Util.randECPoint();\n ECPoint pnt_2 = Util.randECPoint();\n ECPoint pnt_sum = pnt_1.add(pnt_2);\n cmd = new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_EC_ADD, 0, 0, Util.concat(pnt_1.getEncoded(false), pnt_2.getEncoded(false)));\n response = cardMngr.transmit(cmd);\n\n if (response.getSW() == (ISO7816.SW_NO_ERROR & 0xffff)) {\n bResult = Arrays.equals(pnt_sum.getEncoded(false), response.getData());\n\n if (!bResult) {\n System.out.println(String.format(\"Expected: %s\", Util.toHex(pnt_sum.getEncoded(false))));\n System.out.println(String.format(\"Obtained: %s\", Util.toHex(response.getData())));\n }\n } else {\n bResult = false;\n System.out.println(String.format(\"fail (0x%x)\", response.getSW()));\n }\n\n logResponse(operationName, bResult, cardMngr.m_lastTransmitTime, perfFile, runCfg.failedTestsList);\n if (!bResult) {\n String failedAPDU = formatFailedAPDUCmd(cmd);\n runCfg.failedTestsList.add(failedAPDU);\n }\n cardMngr.transmit(new CommandAPDU(APDU_CLEANUP)); \n }\n\n operationName = \"ECPoint Negation: \";\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n System.out.println(String.format(\"%s (%d)\", operationName, repeat));\n ECPoint pnt = Util.randECPoint();\n ECPoint negPnt = pnt.negate();\n cmd = new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_EC_NEG, pnt.getEncoded(false).length, 0, pnt.getEncoded(false));\n response = cardMngr.transmit(cmd);\n bResult = verifyAndLogResponse(operationName, response, cardMngr.m_lastTransmitTime, negPnt, perfFile, runCfg.failedTestsList);\n if (!bResult) {\n String failedAPDU = formatFailedAPDUCmd(cmd);\n runCfg.failedTestsList.add(failedAPDU);\n }\n cardMngr.transmit(new CommandAPDU(APDU_CLEANUP));\n }\n\n operationName = \"EC scalar_Point Multiplication: \";\n Security.addProvider(new BouncyCastleProvider());\n ECParameterSpec ecSpec2 = ECNamedCurveTable.getParameterSpec(\"secp256r1\");\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n System.out.println(String.format(\"%s (%d)\", operationName, repeat));\n // NOTE: we will keep G same (standard), just keep changing the scalar. \n // If you want to test different G, INS_EC_SETCURVE_G must be called before same as for EC Point Double. \n ECPoint base = ecSpec2.getG();\n BigInteger priv1 = Util.randomBigNat(256);\n ECPoint pub = base.multiply(priv1);\n cmd = new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_EC_MUL, priv1.toByteArray().length, 0, Util.concat(priv1.toByteArray(), base.getEncoded(false)));\n response = cardMngr.transmit(cmd);\n if (response.getSW() == (ISO7816.SW_NO_ERROR & 0xffff)) {\n bResult = Arrays.equals(pub.getEncoded(false), response.getData());\n if (!bResult) {\n System.out.println(String.format(\"Expected: %s\", Util.toHex(pub.getEncoded(false))));\n System.out.println(String.format(\"Obtained: %s\", Util.toHex(response.getData())));\n }\n } else {\n bResult = false;\n System.out.println(String.format(\"fail (0x%x)\", response.getSW()));\n }\n logResponse(operationName, bResult, cardMngr.m_lastTransmitTime, perfFile, runCfg.failedTestsList);\n if (!bResult) {\n String failedAPDU = formatFailedAPDUCmd(cmd);\n runCfg.failedTestsList.add(failedAPDU);\n }\n cardMngr.transmit(new CommandAPDU(APDU_CLEANUP)); \n }\n\n operationName = \"EC isEqual: \";\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n System.out.println(String.format(\"%s (%d)\", operationName, repeat));\n ECPoint pnt_1 = Util.randECPoint();\n ECPoint pnt_2 = Util.randECPoint();\n cmd = new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_EC_COMPARE, pnt_1.getEncoded(false).length, pnt_2.getEncoded(false).length, Util.concat(pnt_1.getEncoded(false), pnt_2.getEncoded(false)));\n response = cardMngr.transmit(cmd);\n bResult = verifyAndLogResponse(operationName, response, cardMngr.m_lastTransmitTime, 0, perfFile, runCfg.failedTestsList);\n if (!bResult) {\n String failedAPDU = formatFailedAPDUCmd(cmd);\n runCfg.failedTestsList.add(failedAPDU);\n }\n cardMngr.transmit(new CommandAPDU(APDU_CLEANUP));\n }\n \n operationName = \"EC Point Double: \";\n Security.addProvider(new BouncyCastleProvider());\n //ECParameterSpec ecSpec2 = ECNamedCurveTable.getParameterSpec(\"secp256r1\");\n boolean bSetRandomG = true;\n boolean bReallocateWholeCurve = false;\n for (int repeat = 0; repeat < runCfg.numRepeats; repeat++) {\n System.out.println(String.format(\"%s (%d)\", operationName, repeat));\n ECPoint pnt;\n if (bSetRandomG) {\n pnt = Util.randECPoint();\n System.out.println(String.format(\"Random ECPoint == G: %s\", Util.toHex(pnt.getEncoded(false))));\n // Set modified parameter G of the curve (our random point) \n cardMngr.transmit(new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_EC_SETCURVE_G, pnt.getEncoded(false).length, bReallocateWholeCurve ? (byte) 1 : (byte) 0, pnt.getEncoded(false)));\n } else {\n pnt = ecSpec2.getG();\n }\n\n ECPoint doubled = pnt.add(pnt); // expected results\n // Perform EC double operation \n cmd = new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_EC_DBL, 0, 0, pnt.getEncoded(false));\n try {\n response = cardMngr.transmit(cmd);\n if (response.getSW() == (ISO7816.SW_NO_ERROR & 0xffff)) {\n bResult = Arrays.equals(doubled.getEncoded(false), response.getData());\n if (!bResult) {\n System.out.println(String.format(\"Expected: %s\", Util.toHex(doubled.getEncoded(false))));\n System.out.println(String.format(\"Obtained: %s\", Util.toHex(response.getData())));\n }\n } else {\n bResult = false;\n System.out.println(String.format(\"fail (0x%x)\", response.getSW()));\n }\n } catch (Exception e) {\n bResult = false;\n e.printStackTrace();\n }\n logResponse(operationName, bResult, cardMngr.m_lastTransmitTime, perfFile, runCfg.failedTestsList);\n if (!bResult) {\n String failedAPDU = formatFailedAPDUCmd(cmd);\n runCfg.failedTestsList.add(failedAPDU);\n }\n cardMngr.transmit(new CommandAPDU(APDU_CLEANUP)); \n } \n }\n\n System.out.println(\"\\n--------------Unit Tests--------------\\n\\n\");\n\n cardMngr.transmit(new CommandAPDU(APDU_GET_PROFILE_LOCKS));\n \n \n System.out.print(\"Disconnecting from card...\");\n cardMngr.Disconnect(true);\n System.out.println(\" Done.\");\n\n if (runCfg.failedTestsList.size() > 0) {\n System.out.println(\"#########################\");\n System.out.println(\"!!! SOME TESTS FAILED !!!\");\n System.out.println(\"#########################\");\n for (String test : runCfg.failedTestsList) {\n System.out.println(test);\n }\n\n printFailedTestStats(runCfg);\n\n }\n else {\n System.out.println(\"##########################\");\n System.out.println(\"ALL TESTS PASSED CORRECTLY\");\n System.out.println(\"##########################\"); \n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n return true;\n }\n \n \n static void OpenCryptoFunctionalTests_debug(RunConfig runCfg) throws Exception {\n try {\n CardManager cardMngr = new CardManager(true, OPENCRYPTO_UNITTEST_APPLET_AID);\n System.out.print(\"Connecting to card...\");\n cardMngr.Connect(runCfg);\n System.out.println(\" Done.\");\n\n m_perfResults.clear();\n\n cardMngr.transmit(new CommandAPDU(PerfTests.PERF_COMMAND_NONE));\n cardMngr.transmit(new CommandAPDU(APDU_CLEANUP));\n\n String logFileName = String.format(\"OC_PERF_log_%d.csv\", System.currentTimeMillis());\n FileOutputStream perfFile = new FileOutputStream(logFileName);\n\n CommandAPDU cmd;\n ResponseAPDU response;\n String operationName = \"\";\n boolean bResult = false;\n \n\n System.out.println(\"\\n-------------- Problematic inputs tests --------------\");\n/*\n // TODO: add code for debugging\n operationName = \"BigNatural Multiplication schoolbook: \";\n for (int repeat = 0; repeat < 10; repeat++) {\n System.out.println(String.format(\"%s (%d)\", operationName, repeat));\n BigInteger num1 = Util.randomBigNat(BIGNAT_BASE_TEST_LENGTH);//Generate Int1\n BigInteger num2 = Util.randomBigNat(BIGNAT_BASE_TEST_LENGTH);//Generate Int2\n BigInteger result = num1.multiply(num2);\n cmd = new CommandAPDU(OCUnitTests.CLA_OC_UT, OCUnitTests.INS_BN_MUL, num1.toByteArray().length, 0, Util.concat(num1.toByteArray(), num2.toByteArray()));\n performCommand(operationName, cardMngr, cmd, result, perfFile, runCfg.failedTestsList);\n }\n int a=0;\n/* \n operationName = \"EC Point Add: \";\n for (int repeat = 0; repeat < 1000000; repeat++) {\n System.out.println(String.format(\"%s (%d)\", operationName, repeat));\n ECPoint pnt_1 = Util.randECPoint();\n ECPoint pnt_2 = Util.randECPoint();\n ECPoint pnt_sum = pnt_1.add(pnt_2);\n cmd = new CommandAPDU(Consts.CLA_OC_UT, Consts.INS_EC_ADD, 0, 0, Util.concat(pnt_1.getEncoded(false), pnt_2.getEncoded(false)));\n response = cardMngr.transmit(cmd);\n\n if (response.getSW() == (ISO7816.SW_NO_ERROR & 0xffff)) {\n byte[] x = pnt_sum.getXCoord().getEncoded();\n byte[] y = pnt_sum.getYCoord().getEncoded();\n x = pnt_sum.getEncoded(false);\n bResult = Arrays.equals(pnt_sum.getEncoded(false), response.getData());\n\n if (!bResult) {\n System.out.println(String.format(\"Expected: %s\", Util.toHex(pnt_sum.getEncoded(false))));\n System.out.println(String.format(\"Obtained: %s\", Util.toHex(response.getData())));\n }\n } else {\n bResult = false;\n System.out.println(String.format(\"fail (0x%x)\", response.getSW()));\n } \n }\n*/ \n \n System.out.println(\"\\n-------------- Problematic inputs tests --------------\\n\\n\");\n\n System.out.print(\"Disconnecting from card...\");\n cardMngr.Disconnect(true);\n System.out.println(\" Done.\");\n\n if (runCfg.failedTestsList.size() > 0) {\n System.out.println(\"#########################\");\n System.out.println(\"!!! SOME TESTS FAILED !!!\");\n System.out.println(\"#########################\");\n for (String test : runCfg.failedTestsList) {\n System.out.println(test);\n }\n\n printFailedTestStats(runCfg);\n } else {\n System.out.println(\"##########################\");\n System.out.println(\"ALL TESTS PASSED CORRECTLY\");\n System.out.println(\"##########################\");\n }\n }\n catch (Exception e) {\n e.printStackTrace();\n }\n } \n \n static HashMap<String, Integer> printFailedTestStats(RunConfig runCfg) {\n // Parse failed tests, output statistics\n HashMap<String, Integer> numFailsTest = new HashMap<>();\n for (String test : runCfg.failedTestsList) {\n if (!test.contains(\"failedCommand\")) { // ignore output of apdu\n if (numFailsTest.containsKey(test)) {\n Integer count = numFailsTest.get(test);\n count++;\n numFailsTest.replace(test, count);\n } else {\n numFailsTest.put(test, 1);\n }\n }\n }\n\n System.out.println(\"\\n***FAILED TESTS STATS***\");\n for (String test : numFailsTest.keySet()) {\n System.out.println(String.format(\"%40s: %d / %d\", test, numFailsTest.get(test), runCfg.numRepeats));\n } \n System.out.println(\"************************\\n\");\n \n return numFailsTest;\n }\n\n \n interface CmdResultsComparator {\n public boolean compare(ResponseAPDU response); \n }\n \n class ArrayMatchComparator implements CmdResultsComparator {\n ECPoint m_expected = null;\n ArrayMatchComparator(ECPoint expected) {\n this.m_expected = expected;\n }\n public boolean compare(ResponseAPDU response) {\n boolean bResult = false;\n if (response.getSW() == (ISO7816.SW_NO_ERROR & 0xffff)) {\n bResult = Arrays.equals(m_expected.getEncoded(false), response.getData());\n } else {\n bResult = false;\n System.out.println(String.format(\"fail (0x%x)\", response.getSW()));\n }\n return bResult;\n }\n }\n \n static String formatFailedAPDUCmd(CommandAPDU failedCommand) {\n // If command corectness verification failed, then output for easy resend during debugging later\n byte[] failedcmd = failedCommand.getBytes();\n String failedAPDU = String.format(\"\\tcardMngr.transmit(new CommandAPDU(hexStringToByteArray(\\\"%s\\\")));\", Util.bytesToHex(failedcmd));\n failedAPDU += \"\\n\\tstatic byte[] failedCommand = {\";\n for (int i = 0; i < failedcmd.length; i++) {\n failedAPDU += String.format(\"(byte) 0x%x\", failedcmd[i]);\n if (i != failedcmd.length - 1) {\n failedAPDU += \", \";\n }\n }\n failedAPDU += \"};\";\n failedAPDU += \"\\n\\t\";\n \n return failedAPDU;\n }\n static void performCommand(String operationName, CardManager cardManager, CommandAPDU command, BigInteger expectedResult, FileOutputStream perfFile, ArrayList<String> failedTestsList) throws CardException, IOException {\n performCommand(operationName, cardManager, command, expectedResult, perfFile, failedTestsList, false);\n }\n\n static void performCommand(String operationName, CardManager cardManager, CommandAPDU command, BigInteger expectedResult, FileOutputStream perfFile, ArrayList<String> failedTestsList, boolean bSigNum) throws CardException, IOException {\n ResponseAPDU response = cardManager.transmit(command);\n boolean bSuccess = false;\n \n if (response.getSW() == (ISO7816.SW_NO_ERROR & 0xffff)) {\n byte[] data = response.getData();\n BigInteger respInt;\n if (bSigNum) { respInt = new BigInteger(1, data); } \n else { respInt = new BigInteger(data); }\n\n bSuccess = expectedResult.compareTo(respInt) == 0;\n\n if (!bSuccess) {\n System.out.println(String.format(\"Expected: %s\", expectedResult.toString(16)));\n System.out.println(String.format(\"Obtained: %s\", respInt.toString(16)));\n }\n } else {\n System.out.println(String.format(\"fail (0x%x)\", response.getSW()));\n }\n\n logResponse(operationName, bSuccess, cardManager.m_lastTransmitTime, perfFile, failedTestsList);\n\n if (!bSuccess) {\n String failedAPDU = formatFailedAPDUCmd(command);\n failedTestsList.add(failedAPDU);\n }\n\n cardManager.transmit(new CommandAPDU(APDU_CLEANUP)); \n }\n \n static boolean verifyAndLogResponse(String operationName, ResponseAPDU response, Long lastTransmitTime, int expected, FileOutputStream perfFile, ArrayList<String> failedTestsList) throws IOException {\n boolean bResult = false;\n if (response.getSW () == (ISO7816.SW_NO_ERROR & 0xffff)) {\n bResult = Util.BytesToInt(response.getData()) == expected;\n }\n else {\n System.out.println(String.format(\"fail (0x%x)\", response.getSW()));\n }\n logResponse(operationName, bResult, lastTransmitTime, perfFile, failedTestsList);\n return bResult;\n }\n static boolean verifyAndLogResponse(String operationName, ResponseAPDU response, Long lastTransmitTime, ECPoint expected, FileOutputStream perfFile, ArrayList<String> failedTestsList) throws IOException {\n boolean bResult = false;\n if (response.getSW() == (ISO7816.SW_NO_ERROR & 0xffff)) {\n bResult = Arrays.equals(expected.getEncoded(false), response.getData());\n if (!bResult) {\n System.out.println(String.format(\"Expected: %s\", Util.toHex(expected.getEncoded(false))));\n System.out.println(String.format(\"Obtained: %s\", Util.toHex(response.getData())));\n }\n } else {\n bResult = false;\n System.out.println(String.format(\"fail (0x%x)\", response.getSW()));\n }\n logResponse(operationName, bResult, lastTransmitTime, perfFile, failedTestsList);\n return bResult;\n } \n \n static void logResponse(String operationName, boolean bResult, Long lastTransmitTime, FileOutputStream perfFile, ArrayList<String> failedTestsList) throws IOException {\n System.out.println(String.format(\"%s [%d ms]\", bResult, lastTransmitTime));\n if (bResult == false && _FAIL_ON_ASSERT) {\n assert (bResult);\n }\n if (bResult == false) {\n // Add name of failed operation \n failedTestsList.add(operationName);\n }\n PerfTests.writePerfLog(operationName, bResult, lastTransmitTime, m_perfResults, perfFile);\n }\n \n}",
"public static byte[] APDU_CLEANUP = {OCUnitTests.CLA_OC_UT, OCUnitTests.INS_CLEANUP, (byte) 0x00, (byte) 0x00, (byte) 0x00};",
"public static byte[] OPENCRYPTO_UNITTEST_APPLET_AID = {0x55, 0x6e, 0x69, 0x74, 0x54, 0x65, 0x73, 0x74, 0x73};"
] | import javacard.framework.ISO7816;
import javax.smartcardio.CommandAPDU;
import javax.smartcardio.ResponseAPDU;
import opencrypto.jcmathlib.ECExample;
import opencrypto.test.CardManager;
import opencrypto.test.PerfTests;
import opencrypto.test.RunConfig;
import opencrypto.test.Util;
import static opencrypto.test.Util.hexStringToByteArray;
import opencrypto.test.TestClient;
import static opencrypto.test.TestClient.APDU_CLEANUP;
import static opencrypto.test.TestClient.OPENCRYPTO_UNITTEST_APPLET_AID;
import static org.testng.Assert.*;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test; |
/**
*
* @author Petr Svenda
*/
public class JCMathLibTests {
static final int SMALLTEST_NUM_REPEATS = 10;
static final int LARGETEST_NUM_REPEATS = 1000;
public JCMathLibTests() {
}
@Test
public void openCrypto_smallTest_simulator() throws Exception {
bignat_tests(SMALLTEST_NUM_REPEATS, RunConfig.CARD_TYPE.JCARDSIMLOCAL);
integer_tests(SMALLTEST_NUM_REPEATS, RunConfig.CARD_TYPE.JCARDSIMLOCAL);
ecc_tests(SMALLTEST_NUM_REPEATS, RunConfig.CARD_TYPE.JCARDSIMLOCAL);
}
@Test
public void openCrypto_largeTest_simulator() throws Exception {
bignat_tests(LARGETEST_NUM_REPEATS, RunConfig.CARD_TYPE.JCARDSIMLOCAL);
integer_tests(LARGETEST_NUM_REPEATS, RunConfig.CARD_TYPE.JCARDSIMLOCAL);
ecc_tests(LARGETEST_NUM_REPEATS, RunConfig.CARD_TYPE.JCARDSIMLOCAL);
}
@Test
public void openCrypto_smallTest_realCard() throws Exception {
bignat_tests(SMALLTEST_NUM_REPEATS, RunConfig.CARD_TYPE.PHYSICAL);
integer_tests(SMALLTEST_NUM_REPEATS, RunConfig.CARD_TYPE.PHYSICAL);
ecc_tests(SMALLTEST_NUM_REPEATS, RunConfig.CARD_TYPE.PHYSICAL);
}
@Test
public void openCrypto_problemInputs_simulator() throws Exception {
bignat_problemInputs(RunConfig.CARD_TYPE.JCARDSIMLOCAL);
ecc_problemInputs(RunConfig.CARD_TYPE.JCARDSIMLOCAL);
}
@Test
public void openCrypto_problemInputs_realCard() throws Exception {
bignat_problemInputs(RunConfig.CARD_TYPE.PHYSICAL);
ecc_problemInputs(RunConfig.CARD_TYPE.PHYSICAL);
}
public void bignat_tests(int numRepeats, RunConfig.CARD_TYPE cardType) throws Exception {
TestClient testClient = new TestClient();
RunConfig runCfg = RunConfig.getConfig(true, false, false, numRepeats, cardType);
assertTrue(testClient.OpenCryptoFunctionalTests(runCfg));
assertTrue(runCfg.failedTestsList.isEmpty());
}
public void integer_tests(int numRepeats, RunConfig.CARD_TYPE cardType) throws Exception {
TestClient testClient = new TestClient();
RunConfig runCfg = RunConfig.getConfig(false, true, false, numRepeats, cardType);
assertTrue(testClient.OpenCryptoFunctionalTests(runCfg));
assertTrue(runCfg.failedTestsList.isEmpty());
}
public void ecc_tests(int numRepeats, RunConfig.CARD_TYPE cardType) throws Exception {
TestClient testClient = new TestClient();
RunConfig runCfg = RunConfig.getConfig(false, false, true, numRepeats, cardType);
assertTrue(testClient.OpenCryptoFunctionalTests(runCfg));
assertTrue(runCfg.failedTestsList.isEmpty());
}
void testAPDU(CardManager cardMngr, String input, String expectedOutput) {
try {
ResponseAPDU response = cardMngr.transmit(new CommandAPDU(hexStringToByteArray(input)));
if (response.getSW() == (ISO7816.SW_NO_ERROR & 0xffff)) {
if (!expectedOutput.isEmpty()) {
byte[] data = response.getData();
String output = Util.bytesToHex(data);
assertTrue(expectedOutput.equalsIgnoreCase(output), "Result provided by card mismatch expected");
}
}
else {
assertTrue(false, String.format("Card failed with 0x%x", response.getSW()));
}
}
catch (Exception e) {
e.printStackTrace();
assertTrue(false, "Card transmit failed with execption");
}
}
public void ecc_problemInputs(RunConfig.CARD_TYPE cardType) {
try {
// Prepare card
RunConfig runCfg = RunConfig.getConfig(false, false, false, 1, cardType); | CardManager cardMngr = new CardManager(true, OPENCRYPTO_UNITTEST_APPLET_AID); | 8 |
thomasjungblut/tjungblut-graph | test/de/jungblut/graph/sort/TopologicalSortTest.java | [
"public final class AdjacencyList<VERTEX_ID, VERTEX_VALUE, EDGE_VALUE>\n implements Graph<VERTEX_ID, VERTEX_VALUE, EDGE_VALUE> {\n\n private final HashSet<Vertex<VERTEX_ID, VERTEX_VALUE>> vertexSet = new HashSet<>();\n private final HashMap<VERTEX_ID, Vertex<VERTEX_ID, VERTEX_VALUE>> vertexMap = new HashMap<>();\n private final HashMultimap<VERTEX_ID, VERTEX_ID> adjacencyMultiMap = HashMultimap\n .create();\n private final HashMultimap<VERTEX_ID, Edge<VERTEX_ID, EDGE_VALUE>> edgeMultiMap = HashMultimap\n .create();\n\n @Override\n public Set<Vertex<VERTEX_ID, VERTEX_VALUE>> getAdjacentVertices(\n VERTEX_ID vertexId) {\n Set<VERTEX_ID> set = adjacencyMultiMap.get(vertexId);\n Set<Vertex<VERTEX_ID, VERTEX_VALUE>> toReturn = Sets.newHashSet();\n for (VERTEX_ID id : set) {\n toReturn.add(getVertex(id));\n }\n return toReturn;\n }\n\n @Override\n public Set<Vertex<VERTEX_ID, VERTEX_VALUE>> getAdjacentVertices(\n Vertex<VERTEX_ID, VERTEX_VALUE> vertex) {\n return getAdjacentVertices(vertex.getVertexId());\n }\n\n @Override\n public Set<Vertex<VERTEX_ID, VERTEX_VALUE>> getVertexSet() {\n return vertexSet;\n }\n\n @Override\n public Set<VERTEX_ID> getVertexIDSet() {\n return vertexMap.keySet();\n }\n\n @Override\n public void addVertex(Vertex<VERTEX_ID, VERTEX_VALUE> vertex,\n @SuppressWarnings(\"unchecked\") Edge<VERTEX_ID, EDGE_VALUE>... adjacents) {\n for (Edge<VERTEX_ID, EDGE_VALUE> edge : adjacents) {\n addVertex(vertex, edge);\n }\n }\n\n @Override\n public void addVertex(Vertex<VERTEX_ID, VERTEX_VALUE> vertex) {\n vertexSet.add(vertex);\n vertexMap.put(vertex.getVertexId(), vertex);\n }\n\n @Override\n public void addVertex(Vertex<VERTEX_ID, VERTEX_VALUE> vertex,\n Edge<VERTEX_ID, EDGE_VALUE> adjacent) {\n addVertex(vertex);\n addEdge(vertex.getVertexId(), adjacent);\n }\n\n @Override\n public void addEdge(VERTEX_ID vertexId, Edge<VERTEX_ID, EDGE_VALUE> edge) {\n edgeMultiMap.put(vertexId, edge);\n adjacencyMultiMap.put(vertexId, edge.getDestinationVertexID());\n }\n\n @Override\n public Set<Edge<VERTEX_ID, EDGE_VALUE>> getEdges(VERTEX_ID vertexId) {\n return edgeMultiMap.get(vertexId);\n }\n\n @Override\n public Edge<VERTEX_ID, EDGE_VALUE> getEdge(VERTEX_ID source, VERTEX_ID dest) {\n Set<Edge<VERTEX_ID, EDGE_VALUE>> set = edgeMultiMap.get(source);\n for (Edge<VERTEX_ID, EDGE_VALUE> e : set) {\n if (e.getDestinationVertexID().equals(dest))\n return e;\n }\n return null;\n }\n\n @Override\n public Vertex<VERTEX_ID, VERTEX_VALUE> getVertex(VERTEX_ID vertexId) {\n return vertexMap.get(vertexId);\n }\n\n @Override\n public int getNumVertices() {\n return vertexSet.size();\n }\n\n @Override\n public int getNumEdges() {\n return adjacencyMultiMap.size();\n }\n\n @Override\n public Graph<VERTEX_ID, VERTEX_VALUE, EDGE_VALUE> transpose() {\n Graph<VERTEX_ID, VERTEX_VALUE, EDGE_VALUE> g = new AdjacencyList<>();\n\n for (Vertex<VERTEX_ID, VERTEX_VALUE> v : getVertexSet()) {\n g.addVertex(new VertexImpl<>(v.getVertexId(), v.getVertexValue()));\n }\n\n for (Map.Entry<VERTEX_ID, Edge<VERTEX_ID, EDGE_VALUE>> entry : edgeMultiMap.entries()) {\n g.addEdge(entry.getValue().getDestinationVertexID(), new Edge<>(entry.getKey(), entry.getValue().getValue()));\n }\n\n return g;\n }\n\n @Override\n public String toString() {\n return \"AdjacencyList [getNumVertices()=\" + this.getNumVertices()\n + \", getNumEdges()=\" + this.getNumEdges() + \"]\";\n }\n\n}",
"public interface Graph<VERTEX_ID, VERTEX_VALUE, EDGE_VALUE> {\n\n /**\n * Adds a vertex with a single adjacent to it.\n */\n void addVertex(Vertex<VERTEX_ID, VERTEX_VALUE> vertex,\n Edge<VERTEX_ID, EDGE_VALUE> adjacent);\n\n /**\n * Adds a vertex with a no adjacents to it.\n */\n void addVertex(Vertex<VERTEX_ID, VERTEX_VALUE> vertex);\n\n /**\n * Adds a vertex with a list of adjacents to it.\n */\n void addVertex(Vertex<VERTEX_ID, VERTEX_VALUE> vertex,\n @SuppressWarnings(\"unchecked\") Edge<VERTEX_ID, EDGE_VALUE>... adjacents);\n\n /**\n * Gets a set of adjacent vertices from a given vertex id.\n */\n Set<Vertex<VERTEX_ID, VERTEX_VALUE>> getAdjacentVertices(VERTEX_ID vertexId);\n\n /**\n * Get the vertex by its id.\n */\n Vertex<VERTEX_ID, VERTEX_VALUE> getVertex(VERTEX_ID vertexId);\n\n /**\n * Gets a set of adjacent vertices from a given vertex.\n */\n Set<Vertex<VERTEX_ID, VERTEX_VALUE>> getAdjacentVertices(Vertex<VERTEX_ID, VERTEX_VALUE> vertex);\n\n /**\n * Gets all vertices associated with this graph.\n */\n Set<Vertex<VERTEX_ID, VERTEX_VALUE>> getVertexSet();\n\n /**\n * Gets all verte IDs associated with this graph.\n */\n Set<VERTEX_ID> getVertexIDSet();\n\n /**\n * Adds an edge to a vertex.\n */\n void addEdge(VERTEX_ID vertexId, Edge<VERTEX_ID, EDGE_VALUE> edge);\n\n /**\n * Get's a set of edges outbound from the given vertex id.\n *\n * @param vertexId the id of the vertex to get out edges.\n * @return a set of edges.\n */\n Set<Edge<VERTEX_ID, EDGE_VALUE>> getEdges(VERTEX_ID vertexId);\n\n\n /**\n * Finds an edge between the source and destination vertex.\n *\n * @return null if nothing found, else the edge between those twos.\n */\n Edge<VERTEX_ID, EDGE_VALUE> getEdge(VERTEX_ID source, VERTEX_ID dest);\n\n /**\n * @return how many vertices are present in this graph.\n */\n int getNumVertices();\n\n /**\n * @return how many edges are present in this graph.\n */\n int getNumEdges();\n\n /**\n * @return the transpose of this graph, meaning that it will reverse all edges.\n * So if there was an edge from A->B, the returned graph will contain one for B->A instead.\n */\n Graph<VERTEX_ID, VERTEX_VALUE, EDGE_VALUE> transpose();\n\n}",
"public class TestGraphProvider {\n\n /**\n * from {@link https://de.wikipedia.org/wiki/Dijkstra-Algorithmus#Beispiel}\n */\n @SuppressWarnings({\"unchecked\"})\n public static Graph<Integer, String, Integer> getWikipediaExampleGraph() {\n Graph<Integer, String, Integer> graph = new AdjacencyList<>();\n\n ArrayList<VertexImpl<Integer, String>> cities = new ArrayList<>();\n\n cities.add(new VertexImpl<>(0, \"Frankfurt\"));\n cities.add(new VertexImpl<>(1, \"Mannheim\"));\n cities.add(new VertexImpl<>(2, \"Wuerzburg\"));\n cities.add(new VertexImpl<>(3, \"Stuttgart\"));\n cities.add(new VertexImpl<>(4, \"Kassel\"));\n cities.add(new VertexImpl<>(5, \"Karlsruhe\"));\n cities.add(new VertexImpl<>(6, \"Erfurt\"));\n cities.add(new VertexImpl<>(7, \"Nuernberg\"));\n cities.add(new VertexImpl<>(8, \"Augsburg\"));\n cities.add(new VertexImpl<>(9, \"Muenchen\"));\n\n // frankfurt -> mannheim, kassel, wuerzburg\n graph.addVertex(cities.get(0),\n new Edge<>(cities.get(1).getVertexId(), 85),\n new Edge<>(cities.get(4).getVertexId(), 173),\n new Edge<>(cities.get(2).getVertexId(), 217));\n\n // mannheim -> frankfurt, karlsruhe\n graph.addVertex(cities.get(1),\n new Edge<>(cities.get(0).getVertexId(), 85),\n new Edge<>(cities.get(5).getVertexId(), 80));\n\n // wuerzburg -> frankfurt, erfurt, nuernberg\n graph.addVertex(cities.get(2),\n new Edge<>(cities.get(0).getVertexId(), 217),\n new Edge<>(cities.get(6).getVertexId(), 186),\n new Edge<>(cities.get(7).getVertexId(), 103));\n\n // stuttgart -> nuernberg\n graph.addVertex(cities.get(3), new Edge<>(cities.get(7).getVertexId(), 183));\n\n // kassel -> muenchen, frankfurt\n graph.addVertex(cities.get(4),\n new Edge<>(cities.get(9).getVertexId(), 502),\n new Edge<>(cities.get(0).getVertexId(), 173));\n\n // karlsruhe -> mannheim, augsburg\n graph.addVertex(cities.get(5),\n new Edge<>(cities.get(1).getVertexId(), 80),\n new Edge<>(cities.get(8).getVertexId(), 250));\n\n // erfurt -> wuerzburg\n graph.addVertex(cities.get(6), new Edge<>(cities.get(2).getVertexId(), 186));\n\n // nuernberg -> stuttgart, muenchen, wuerzburg\n graph.addVertex(cities.get(7),\n new Edge<>(cities.get(3).getVertexId(), 183),\n new Edge<>(cities.get(9).getVertexId(), 167),\n new Edge<>(cities.get(2).getVertexId(), 103));\n\n // augsburg -> karlsruhe, muenchen\n graph.addVertex(cities.get(8),\n new Edge<>(cities.get(5).getVertexId(), 250),\n new Edge<>(cities.get(9).getVertexId(), 84));\n\n // muenchen -> nuernberg, kassel, augsburg\n graph.addVertex(cities.get(9),\n new Edge<>(cities.get(7).getVertexId(), 167),\n new Edge<>(cities.get(4).getVertexId(), 502),\n new Edge<>(cities.get(8).getVertexId(), 84));\n\n return graph;\n }\n\n /**\n * from {@link https://en.wikipedia.org/wiki/Topological_sorting}\n */\n @SuppressWarnings(\"unchecked\")\n public static Graph<Integer, String, Integer> getTopologicalSortWikipediaExampleGraph() {\n Graph<Integer, String, Integer> graph = new AdjacencyList<>();\n\n ArrayList<VertexImpl<Integer, String>> cities = new ArrayList<>();\n\n // 7, 5, 3, 11, 8, 2, 9, 10\n cities.add(new VertexImpl<>(7, \"\")); // 0\n cities.add(new VertexImpl<>(5, \"\")); // 1\n cities.add(new VertexImpl<>(3, \"\")); // 2\n cities.add(new VertexImpl<>(11, \"\")); // 3\n cities.add(new VertexImpl<>(8, \"\")); // 4\n cities.add(new VertexImpl<>(2, \"\")); // 5\n cities.add(new VertexImpl<>(9, \"\")); // 6\n cities.add(new VertexImpl<>(10, \"\")); // 7\n\n // 7 -> 11, 8\n graph.addVertex(cities.get(0),\n new Edge<>(cities.get(3).getVertexId(), null),\n new Edge<>(cities.get(4).getVertexId(), null));\n // 5 -> 11\n graph.addVertex(cities.get(1), new Edge<>(cities.get(3).getVertexId(), null));\n // 3 -> 8,10\n graph.addVertex(cities.get(2),\n new Edge<>(cities.get(4).getVertexId(), null),\n new Edge<>(cities.get(7).getVertexId(), null));\n // 11 -> 2,9,10\n graph.addVertex(cities.get(3),\n new Edge<>(cities.get(2).getVertexId(), null),\n new Edge<>(cities.get(6).getVertexId(), null),\n new Edge<>(cities.get(7).getVertexId(), null));\n // 8 -> 9\n graph.addVertex(cities.get(4), new Edge<>(cities.get(6).getVertexId(), null));\n // 2 -> nowhere\n graph.addVertex(cities.get(5));\n // 9 -> nowhere\n graph.addVertex(cities.get(6));\n // 10 -> nowhere\n graph.addVertex(cities.get(7));\n\n return graph;\n }\n\n}",
"public final class Edge<VERTEX_ID, EDGE_VALUE> {\n\n private final VERTEX_ID destinationVertexID;\n private final EDGE_VALUE cost;\n\n public Edge(VERTEX_ID destinationVertexID, EDGE_VALUE cost) {\n this.destinationVertexID = destinationVertexID;\n this.cost = cost;\n }\n\n public VERTEX_ID getDestinationVertexID() {\n return destinationVertexID;\n }\n\n public EDGE_VALUE getValue() {\n return cost;\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime\n * result\n + ((this.destinationVertexID == null) ? 0 : this.destinationVertexID\n .hashCode());\n return result;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n if (obj == null)\n return false;\n if (getClass() != obj.getClass())\n return false;\n @SuppressWarnings(\"rawtypes\")\n Edge other = (Edge) obj;\n if (this.destinationVertexID == null) {\n if (other.destinationVertexID != null)\n return false;\n } else if (!this.destinationVertexID.equals(other.destinationVertexID))\n return false;\n return true;\n }\n\n @Override\n public String toString() {\n return this.destinationVertexID + \":\" + this.getValue();\n }\n\n}",
"public interface Vertex<VERTEX_ID, VERTEX_VALUE> {\n\n /**\n * @return the id of this vertex.\n */\n VERTEX_ID getVertexId();\n\n /**\n * @return the value of this vertex.\n */\n VERTEX_VALUE getVertexValue();\n\n}",
"public final class VertexImpl<VERTEX_ID, VERTEX_VALUE> implements\n Vertex<VERTEX_ID, VERTEX_VALUE> {\n\n private final VERTEX_ID id;\n private final VERTEX_VALUE value;\n\n public VertexImpl(VERTEX_ID id, VERTEX_VALUE value) {\n super();\n this.id = id;\n this.value = value;\n }\n\n @Override\n public VERTEX_ID getVertexId() {\n return id;\n }\n\n @Override\n public VERTEX_VALUE getVertexValue() {\n return value;\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + ((this.id == null) ? 0 : this.id.hashCode());\n return result;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n if (obj == null)\n return false;\n if (getClass() != obj.getClass())\n return false;\n @SuppressWarnings(\"rawtypes\")\n VertexImpl other = (VertexImpl) obj;\n if (this.id == null) {\n if (other.id != null)\n return false;\n } else if (!this.id.equals(other.id))\n return false;\n return true;\n }\n\n @Override\n public String toString() {\n return \"VertexImpl [id=\" + this.id + \", value=\" + this.value + \"]\";\n }\n\n}"
] | import de.jungblut.graph.AdjacencyList;
import de.jungblut.graph.Graph;
import de.jungblut.graph.TestGraphProvider;
import de.jungblut.graph.model.Edge;
import de.jungblut.graph.model.Vertex;
import de.jungblut.graph.model.VertexImpl;
import org.junit.Assert;
import org.junit.Test;
import java.util.List; | package de.jungblut.graph.sort;
public class TopologicalSortTest {
@Test
public void testTopologicalSort() {
Graph<Integer, String, Integer> g = TestGraphProvider
.getTopologicalSortWikipediaExampleGraph(); | List<Vertex<Integer, String>> sort = new TopologicalSort().sort(g); | 4 |
EthanCo/Halo-Turbo | sample/src/main/java/com/ethanco/sample/MinaTcpServerActivity.java | [
"public class Halo extends AbstractHalo {\n private ISocket haloImpl;\n\n public Halo() {\n this(new Builder());\n }\n\n public Halo(Builder builder) {\n this.haloImpl = SocketFactory.create(builder);\n }\n\n @Override\n public boolean start() {\n return this.haloImpl.start();\n }\n\n @Override\n public void stop() {\n if (haloImpl != null) {\n haloImpl.stop();\n }\n }\n\n @Override\n public List<IHandler> getHandlers() {\n return this.haloImpl.getHandlers();\n }\n\n @Override\n public void addHandler(IHandler handler) {\n this.haloImpl.addHandler(handler);\n }\n\n @Override\n public boolean removeHandler(IHandler handler) {\n return this.haloImpl.removeHandler(handler);\n }\n\n @Override\n public boolean isRunning() {\n return haloImpl.isRunning();\n }\n\n public static class Builder extends Config {\n\n public Builder() {\n this.mode = Mode.MINA_NIO_TCP_CLIENT;\n this.targetIP = \"192.168.1.1\";\n this.targetPort = 19600;\n //this.sourceIP = \"192.168.1.1\";\n this.sourcePort = 19700;\n this.bufferSize = 1024;\n this.handlers = new ArrayList<>();\n this.convertors = new ArrayList<>();\n //需要的自行进行初始化\n //this.threadPool = Executors.newCachedThreadPool();\n }\n\n public Builder setMode(Mode mode) {\n this.mode = mode;\n return this;\n }\n\n public Builder setTargetIP(String targetIP) {\n this.targetIP = targetIP;\n return this;\n }\n\n public Builder setTargetPort(int targetPort) {\n this.targetPort = targetPort;\n return this;\n }\n\n /*public Builder setSourceIP(String sourceIP) {\n this.sourceIP = sourceIP;\n return this;\n }*/\n\n public Builder setSourcePort(int sourcePort) {\n this.sourcePort = sourcePort;\n return this;\n }\n\n public Builder setBufferSize(int bufferSize) {\n this.bufferSize = bufferSize;\n return this;\n }\n\n public Builder setThreadPool(ExecutorService threadPool) {\n this.threadPool = threadPool;\n return this;\n }\n\n public Builder addHandler(IHandler handler) {\n if (!this.handlers.contains(handler)) {\n this.handlers.add(handler);\n }\n return this;\n }\n\n //添加转换器\n public Builder addConvert(IConvertor convertor) {\n if (!convertors.contains(convertor)) {\n this.convertors.add(convertor);\n }\n return this;\n }\n\n //这是自定义的转换器列表\n public Builder setConverts(List<IConvertor> convertors) {\n this.convertors = convertors;\n return this;\n }\n\n //设置ProtocolCodecFactory,现仅对Mina有效\n public Builder setCodec(Object codec) {\n this.codec = codec;\n return this;\n }\n\n public Builder setContext(Context context) {\n this.context = context;\n return this;\n }\n\n //设置心跳\n public Builder setKeepAlive(KeepAlive keepAlive) {\n this.keepAlive = keepAlive;\n return this;\n }\n\n public Halo build() {\n return new Halo(this);\n }\n }\n}",
"public abstract class IHandlerAdapter implements IHandler {\n\n @Override\n public void sessionCreated(ISession session) {\n\n }\n\n @Override\n public void sessionOpened(ISession session) {\n\n }\n\n @Override\n public void sessionClosed(ISession session) {\n\n }\n\n @Override\n public void messageReceived(ISession session, Object message) {\n\n }\n\n @Override\n public void messageSent(ISession session, Object message) {\n\n }\n}",
"public interface ISession {\n void write(Object message);\n\n void close();\n}",
"public class StringLogHandler extends BaseLogHandler {\n\n public StringLogHandler() {\n }\n\n public StringLogHandler(String tag) {\n super(tag);\n }\n\n @Override\n public void messageReceived(ISession session, Object message) {\n String receive = convertToString(message);\n printLog(\"messageReceived:\" + receive);\n }\n\n @Override\n public void messageSent(ISession session, Object message) {\n String sendData = convertToString(message);\n printLog(\"messageSent:\" + sendData);\n }\n\n @Override\n protected String convertToString(Object message) {\n if (message == null) {\n return \"message is null\";\n }\n\n String receive;\n if (message instanceof byte[]) {\n receive = new String((byte[]) message);\n } else if (message instanceof String) {\n receive = (String) message;\n } else {\n receive = message.toString();\n }\n return receive.trim();\n }\n}",
"public enum Mode {\n MINA_NIO_TCP_CLIENT,\n MINA_NIO_TCP_SERVER,\n MINA_NIO_UDP_CLIENT,\n MINA_NIO_UDP_SERVER,\n MULTICAST,\n UDP_CLIENT,\n}"
] | import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;
import com.ethanco.halo.turbo.Halo;
import com.ethanco.halo.turbo.ads.IHandlerAdapter;
import com.ethanco.halo.turbo.ads.ISession;
import com.ethanco.halo.turbo.impl.handler.StringLogHandler;
import com.ethanco.halo.turbo.type.Mode;
import com.ethanco.sample.databinding.ActivityMinaTcpServerBinding;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory; | package com.ethanco.sample;
public class MinaTcpServerActivity extends AppCompatActivity {
private static final String TAG = "Z-MinaTcpServerActivity";
private ActivityMinaTcpServerBinding binding;
private ScrollBottomTextWatcher watcher;
private Halo halo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_mina_tcp_server);
halo = new Halo.Builder() | .setMode(Mode.MINA_NIO_TCP_SERVER) | 4 |
MCBans/MCBans | src/main/java/com/mcbans/plugin/request/PreviousNames.java | [
"public class ActionLog {\n private final Logger logger = Logger.getLogger(\"Minecraft\");\n private final String logPrefix = \"[MCBans] \";\n\n private final MCBans plugin;\n private static ActionLog instance;\n\n public ActionLog(final MCBans plugin){\n instance = this;\n this.plugin = plugin;\n }\n\n public void log(final Level level, final String message, final boolean logToFile){\n logger.log(level, logPrefix + message);\n if (logToFile && plugin.getConfigs() != null && plugin.getConfigs().isEnableLog()) {\n writeLog(message);\n }\n }\n\n public void log(final Level level, final String message){\n log (level, message, true);\n }\n\n public void fine(final String message){\n log(Level.FINE, message);\n }\n public void info(final String message){\n log(Level.INFO, message);\n }\n public void warning(final String message){\n log(Level.WARNING, message);\n }\n public void severe(final String message){\n log(Level.SEVERE, message);\n }\n\n /**\n * Write message to mcbans log file\n * @param message message to write\n */\n private void writeLog(final String message){\n try {\n appendLine(plugin.getConfigs().getLogFile(),\n \"[\" + new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss\").format(new Date()) + \"] \" + message);\n } catch (IOException ex) {\n logger.warning(logPrefix + \"Could not write log file! \" + ex.getMessage());\n }\n }\n\n /**\n * Append line to file\n * @param file target file\n * @param line message to append line\n * @throws IOException IOException\n */\n private void appendLine(final String file, final String line) throws IOException {\n PrintWriter outputStream = null;\n try {\n outputStream = new PrintWriter(new FileWriter(file, true));\n outputStream.println(line);\n } finally {\n if(outputStream != null) {\n outputStream.close();\n }\n }\n }\n\n public static ActionLog getInstance(){\n return instance;\n }\n}",
"public class MCBans extends JavaPlugin {\n public final String apiRequestSuffix = \"4.4.3\";\n private static MCBans instance;\n\n private OfflineBanList offlineBanList;\n public int taskID = 0;\n public HashMap<String, Integer> connectionData = new HashMap<String, Integer>();\n public HashMap<String, BanResponse> playerCache = new HashMap<>();\n public HashMap<String, Long> resetTime = new HashMap<String, Long>();\n public Properties lastSyncs = new Properties();\n public ArrayList<String> mcbStaff = new ArrayList<String>();\n public long last_req = 0;\n public long timeRecieved = 0;\n public Thread callbackThread = null;\n public BanSync bansync = null;\n public Thread syncBan = null;\n public PendingActions pendingActions = null;\n public long lastID = -1;\n public File syncIni = null;\n public long lastSync = 0;\n public String lastType = \"\";\n public boolean syncRunning = false;\n public long lastCallBack = 0;\n public long lastPendingActions = 0;\n public static boolean AnnounceAll = false;\n public String apiServer = null;\n\n private ActionLog log = null;\n private RollbackHandler rbHandler = null;\n private boolean ncpEnabled = false;\n private boolean acEnabled = false;\n private ConfigurationManager config;\n private MCBansCommandHandler commandHandler;\n\n\n @Override\n public void onDisable() {\n if (callbackThread != null) {\n if (callbackThread.isAlive()) {\n callbackThread.interrupt();\n }\n }\n if (syncBan != null) {\n if (syncBan.isAlive()) {\n syncBan.interrupt();\n }\n }\n\n getServer().getScheduler().cancelTasks(this);\n instance = null;\n\n final PluginDescriptionFile pdfFile = this.getDescription();\n log.info(pdfFile.getName() + \" version \" + pdfFile.getVersion() + \" is disabled!\");\n }\n\n @Override\n public void onEnable() {\n\n try {\n offlineBanList = new OfflineBanList(this);\n } catch (IOException e) {\n e.printStackTrace();\n } catch (ClassNotFoundException e) {\n e.printStackTrace();\n }\n instance = this;\n PluginManager pm = getServer().getPluginManager();\n log = new ActionLog(this); // setup logger\n\n // check online-mode, Do NOT remove this check!\n /*if (!this.getServer().getOnlineMode()) {\n log.severe(\"This server is not in online mode!\");\n pm.disablePlugin(this);\n return;\n }*/\n //load sync configuration\n syncIni = new File(this.getDataFolder(), \"sync.ini\");\n if (syncIni.exists()) {\n try {\n lastSyncs.load(new FileInputStream(syncIni));\n lastID = Long.valueOf(lastSyncs.getProperty(\"lastId\"));\n lastType = lastSyncs.getProperty(\"lastType\");\n } catch (Exception e) {\n }\n } else {\n lastType = \"bans\";\n lastID = -1;\n }\n\n // load configuration\n config = new ConfigurationManager(this);\n try {\n config.loadConfig(true);\n } catch (Exception ex) {\n log.warning(\"An error occurred while trying to load the config file.\");\n ex.printStackTrace();\n }\n if (!pm.isPluginEnabled(this)) {\n return;\n }\n\n // load language\n log.info(\"Loading language file: \" + config.getLanguage());\n I18n.init(config.getLanguage());\n\n pm.registerEvents(new PlayerListener(this), this);\n\n // setup permissions\n Perms.setupPermissionHandler();\n\n // regist commands\n commandHandler = new MCBansCommandHandler(this);\n registerCommands();\n\n MainCallBack thisThread = new MainCallBack(this);\n thisThread.start();\n\n // ban sync\n bansync = new BanSync(this);\n bansync.start();\n\n pendingActions = new PendingActions(this);\n pendingActions.start();\n\n ServerChoose serverChooser = new ServerChoose(this);\n (new Thread(serverChooser)).start();\n\n // rollback handler\n rbHandler = new RollbackHandler(this);\n rbHandler.setupHandler();\n\n // hookup integration plugin\n //checkPlugin(true);\n //if (ncpEnabled) log.info(\"NoCheatPlus plugin found! Enabled this integration!\");\n //if (acEnabled) log.info(\"AntiCheat plugin found! Enabled this integration!\");\n\n final PluginDescriptionFile pdfFile = this.getDescription();\n log.info(pdfFile.getName() + \" version \" + pdfFile.getVersion() + \" is enabled!\");\n }\n\n @Override\n public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] args) {\n return commandHandler.onCommand(sender, command, label, args);\n }\n\n @Override\n public List<String> onTabComplete(final CommandSender sender, final Command command, final String alias, final String[] args) {\n return commandHandler.onTabComplete(sender, command, alias, args);\n }\n\n private void registerCommands() {\n List<BaseCommand> cmds = new ArrayList<BaseCommand>();\n // Banning Commands\n cmds.add(new CommandBan());\n cmds.add(new CommandGlobalban());\n cmds.add(new CommandTempban());\n cmds.add(new CommandRban());\n\n // IP Banning Commands\n cmds.add(new CommandBanip());\n\n // Other action commands\n cmds.add(new CommandUnban());\n cmds.add(new CommandKick());\n\n // Other commands\n cmds.add(new CommandLookup());\n cmds.add(new CommandBanlookup());\n cmds.add(new CommandAltlookup());\n cmds.add(new CommandMCBans());\n cmds.add(new CommandPrevious());\n\n cmds.add(new CommandMCBansSettings());\n\n for (final BaseCommand cmd : cmds) {\n commandHandler.registerCommand(cmd);\n }\n }\n\n public void debug(final String message) {\n if (getConfigs().isDebug()) {\n getLog().info(message);\n }\n }\n\n /*public void checkPlugin(final boolean startup){\n // Check NoCheatPlus\n //Plugin checkNCP = getServer().getPluginManager().getPlugin(\"NoCheatPlus\");\n this.ncpEnabled = (checkNCP != null && checkNCP instanceof NoCheatPlus);\n // Check AntiCheat\n //Plugin checkAC = getServer().getPluginManager().getPlugin(\"AntiCheat\");\n this.acEnabled = (checkAC != null && checkAC instanceof Anticheat);\n\n if (!startup){\n if (ncpEnabled) ncpEnabled = (checkNCP.isEnabled());\n if (acEnabled) acEnabled = (checkAC.isEnabled());\n }\n }*/\n\n public boolean isEnabledNCP() {\n return this.ncpEnabled;\n }\n\n public boolean isEnabledAC() {\n return this.acEnabled;\n }\n\n public RollbackHandler getRbHandler() {\n return this.rbHandler;\n }\n\n public MCBansAPI getAPI(final Plugin plugin) {\n return MCBansAPI.getHandle(this, plugin);\n }\n\n\n public static UUID fromString(String uuid){\n return UUID.fromString(uuid.replaceAll(\"(?ism)([a-z0-9]{8})([a-z0-9]{4})([a-z0-9]{4})([a-z0-9]{4})([a-z0-9]{12})\", \"$1-$2-$3-$4-$5\"));\n }\n\n public static Player getPlayer(Plugin plugin, UUID uuid) {\n return plugin.getServer().getPlayer(uuid);\n }\n\n public static Player getPlayer(Plugin plugin, String target) {\n return plugin.getServer().getPlayerExact(target);\n }\n\n /*public void act(String act, String uuid){\n uuid = uuid.replaceAll(\"(?ism)([a-z0-9]{8})([a-z0-9]{4})([a-z0-9]{4})([a-z0-9]{4})([a-z0-9]{12})\", \"$1-$2-$3-$4-$5\");\n if(uuid.matches(\"([a-z0-9]{8})-([a-z0-9]{4})-([a-z0-9]{4})-([a-z0-9]{4})-([a-z0-9]{12})\")){\n OfflinePlayer d = getServer().getOfflinePlayer(UUID.fromString(uuid));\n if (d != null){\n if(d.isBanned()){\n if(act.equals(\"unban\")){\n d.setBanned(false);\n }\n }else{\n if(act.equals(\"ban\")){\n d.setBanned(true);\n }\n }\n }\n }\n }*/\n public ConfigurationManager getConfigs() {\n return this.config;\n }\n\n public ActionLog getLog() {\n return this.log;\n }\n\n public static String getPrefix() {\n return instance.config.getPrefix();\n }\n\n public static MCBans getInstance() {\n return instance;\n }\n\n public OfflineBanList getOfflineBanList() {\n return offlineBanList;\n }\n}",
"public class PreviousCallback extends BaseCallback{\n\n\tpublic PreviousCallback(MCBans plugin, CommandSender sender) {\n\t\tsuper(plugin, sender);\n\t\t\n\t}\n\t\n\t@Override\n\tpublic void success(String identifier, String playerlist ) {\n\t\tif(!playerlist.equals(\"\")){\n\t\t\tUtil.message(sender, ChatColor.RED +localize(\"previousNamesHas\", I18n.PLAYER, identifier, I18n.PLAYERS, playerlist));\n\t\t}else{\n\t\t\tUtil.message(sender, ChatColor.AQUA +localize(\"previousNamesNone\", I18n.PLAYER, identifier));\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic void success() {\n\t\tthrow new IllegalArgumentException(\"Wrong Usage!\");\n\t}\n\n\t@Override\n\tpublic void error(String error) {\n\t\tif (error != null && sender != null){\n Util.message(sender, ChatColor.RED + error);\n }\n\t}\n\n}",
"public class JSONException extends Exception {\n private static final long serialVersionUID = 0;\n private Throwable cause;\n\n /**\n * Constructs a JSONException with an explanatory message.\n * @param message Detail about the reason for the exception.\n */\n public JSONException(String message) {\n super(message);\n }\n\n public JSONException(Throwable cause) {\n super(cause.getMessage());\n this.cause = cause;\n }\n\n @Override\n public Throwable getCause() {\n return this.cause;\n }\n}",
"@SuppressWarnings({ \"rawtypes\", \"unchecked\" })\npublic class JSONObject {\n\n /**\n * JSONObject.NULL is equivalent to the value that JavaScript calls null,\n * whilst Java's null is equivalent to the value that JavaScript calls\n * undefined.\n */\n private static final class Null {\n\n /**\n * There is only intended to be a single instance of the NULL object,\n * so the clone method returns itself.\n * @return NULL.\n */\n @Override\n protected final Object clone() {\n return this;\n }\n\n /**\n * A Null object is equal to the null value and to itself.\n * @param object An object to test for nullness.\n * @return true if the object parameter is the JSONObject.NULL object\n * or null.\n */\n @Override\n public boolean equals(Object object) {\n return object == null || object == this;\n }\n\n /**\n * Get the \"null\" string value.\n * @return The string \"null\".\n */\n @Override\n public String toString() {\n return \"null\";\n }\n }\n\n\n /**\n * The map where the JSONObject's properties are kept.\n */\n private Map map;\n\n\n /**\n * It is sometimes more convenient and less ambiguous to have a\n * <code>NULL</code> object than to use Java's <code>null</code> value.\n * <code>JSONObject.NULL.equals(null)</code> returns <code>true</code>.\n * <code>JSONObject.NULL.toString()</code> returns <code>\"null\"</code>.\n */\n public static final Object NULL = new Null();\n\n\n /**\n * Construct an empty JSONObject.\n */\n public JSONObject() {\n this.map = new HashMap();\n }\n\n\n /**\n * Construct a JSONObject from a subset of another JSONObject.\n * An array of strings is used to identify the keys that should be copied.\n * Missing keys are ignored.\n * @param jo A JSONObject.\n * @param names An array of strings.\n * @throws JSONException \n * @exception JSONException If a value is a non-finite number or if a name is duplicated.\n */\n public JSONObject(JSONObject jo, String[] names) {\n this();\n for (int i = 0; i < names.length; i += 1) {\n try {\n putOnce(names[i], jo.opt(names[i]));\n } catch (Exception ignore) {\n }\n }\n }\n\n\n /**\n * Construct a JSONObject from a JSONTokener.\n * @param x A JSONTokener object containing the source string.\n * @throws JSONException If there is a syntax error in the source string\n * or a duplicated key.\n */\n public JSONObject(JSONTokener x) throws JSONException {\n this();\n char c;\n String key;\n\n if (x.nextClean() != '{') {\n throw x.syntaxError(\"A JSONObject text must begin with '{'\");\n }\n for (;;) {\n c = x.nextClean();\n switch (c) {\n case 0:\n throw x.syntaxError(\"A JSONObject text must end with '}'\");\n case '}':\n return;\n default:\n x.back();\n key = x.nextValue().toString();\n }\n\n // The key is followed by ':'. We will also tolerate '=' or '=>'.\n\n c = x.nextClean();\n if (c == '=') {\n if (x.next() != '>') {\n x.back();\n }\n } else if (c != ':') {\n throw x.syntaxError(\"Expected a ':' after a key\");\n }\n putOnce(key, x.nextValue());\n\n // Pairs are separated by ','. We will also tolerate ';'.\n\n switch (x.nextClean()) {\n case ';':\n case ',':\n if (x.nextClean() == '}') {\n return;\n }\n x.back();\n break;\n case '}':\n return;\n default:\n throw x.syntaxError(\"Expected a ',' or '}'\");\n }\n }\n }\n\n\n /**\n * Construct a JSONObject from a Map.\n *\n * @param map A map object that can be used to initialize the contents of\n * the JSONObject.\n * @throws JSONException \n */\n public JSONObject(Map map) {\n this.map = new HashMap();\n if (map != null) {\n Iterator i = map.entrySet().iterator();\n while (i.hasNext()) {\n Map.Entry e = (Map.Entry)i.next();\n Object value = e.getValue();\n if (value != null) {\n this.map.put(e.getKey(), wrap(value));\n }\n }\n }\n }\n\n\n /**\n * Construct a JSONObject from an Object using bean getters.\n * It reflects on all of the public methods of the object.\n * For each of the methods with no parameters and a name starting\n * with <code>\"get\"</code> or <code>\"is\"</code> followed by an uppercase letter,\n * the method is invoked, and a key and the value returned from the getter method\n * are put into the new JSONObject.\n *\n * The key is formed by removing the <code>\"get\"</code> or <code>\"is\"</code> prefix.\n * If the second remaining character is not upper case, then the first\n * character is converted to lower case.\n *\n * For example, if an object has a method named <code>\"getName\"</code>, and\n * if the result of calling <code>object.getName()</code> is <code>\"Larry Fine\"</code>,\n * then the JSONObject will contain <code>\"name\": \"Larry Fine\"</code>.\n *\n * @param bean An object that has getter methods that should be used\n * to make a JSONObject.\n */\n public JSONObject(Object bean) {\n this();\n populateMap(bean);\n }\n\n\n /**\n * Construct a JSONObject from an Object, using reflection to find the\n * public members. The resulting JSONObject's keys will be the strings\n * from the names array, and the values will be the field values associated\n * with those keys in the object. If a key is not found or not visible,\n * then it will not be copied into the new JSONObject.\n * @param object An object that has fields that should be used to make a\n * JSONObject.\n * @param names An array of strings, the names of the fields to be obtained\n * from the object.\n */\n public JSONObject(Object object, String names[]) {\n this();\n Class c = object.getClass();\n for (int i = 0; i < names.length; i += 1) {\n String name = names[i];\n try {\n putOpt(name, c.getField(name).get(object));\n } catch (Exception ignore) {\n }\n }\n }\n\n\n /**\n * Construct a JSONObject from a source JSON text string.\n * This is the most commonly used JSONObject constructor.\n * @param source A string beginning\n * with <code>{</code> <small>(left brace)</small> and ending\n * with <code>}</code> <small>(right brace)</small>.\n * @exception JSONException If there is a syntax error in the source\n * string or a duplicated key.\n */\n public JSONObject(String source) throws JSONException {\n this(new JSONTokener(source));\n }\n\n\n /**\n * Construct a JSONObject from a ResourceBundle.\n * @param baseName The ResourceBundle base name.\n * @param locale The Locale to load the ResourceBundle for.\n * @throws JSONException If any JSONExceptions are detected.\n */\n public JSONObject(String baseName, Locale locale) throws JSONException {\n this();\n ResourceBundle r = ResourceBundle.getBundle(baseName, locale, \n Thread.currentThread().getContextClassLoader());\n\n // Iterate through the keys in the bundle.\n\n Enumeration keys = r.getKeys();\n while (keys.hasMoreElements()) {\n Object key = keys.nextElement();\n if (key instanceof String) {\n\n // Go through the path, ensuring that there is a nested JSONObject for each \n // segment except the last. Add the value using the last segment's name into\n // the deepest nested JSONObject.\n\n String[] path = ((String)key).split(\"\\\\.\");\n int last = path.length - 1;\n JSONObject target = this;\n for (int i = 0; i < last; i += 1) {\n String segment = path[i];\n JSONObject nextTarget = target.optJSONObject(segment);\n if (nextTarget == null) {\n nextTarget = new JSONObject();\n target.put(segment, nextTarget);\n }\n target = nextTarget;\n }\n target.put(path[last], r.getString((String)key));\n }\n }\n }\n\n\n /**\n * Accumulate values under a key. It is similar to the put method except\n * that if there is already an object stored under the key then a\n * JSONArray is stored under the key to hold all of the accumulated values.\n * If there is already a JSONArray, then the new value is appended to it.\n * In contrast, the put method replaces the previous value.\n * @param key A key string.\n * @param value An object to be accumulated under the key.\n * @return this.\n * @throws JSONException If the value is an invalid number\n * or if the key is null.\n */\n public JSONObject accumulate(String key, Object value)\n throws JSONException {\n testValidity(value);\n Object object = opt(key);\n if (object == null) {\n put(key, value instanceof JSONArray ?\n new JSONArray().put(value) : value);\n } else if (object instanceof JSONArray) {\n ((JSONArray)object).put(value);\n } else {\n put(key, new JSONArray().put(object).put(value));\n }\n return this;\n }\n\n\n /**\n * Append values to the array under a key. If the key does not exist in the\n * JSONObject, then the key is put in the JSONObject with its value being a\n * JSONArray containing the value parameter. If the key was already\n * associated with a JSONArray, then the value parameter is appended to it.\n * @param key A key string.\n * @param value An object to be accumulated under the key.\n * @return this.\n * @throws JSONException If the key is null or if the current value\n * associated with the key is not a JSONArray.\n */\n public JSONObject append(String key, Object value) throws JSONException {\n testValidity(value);\n Object object = opt(key);\n if (object == null) {\n put(key, new JSONArray().put(value));\n } else if (object instanceof JSONArray) {\n put(key, ((JSONArray)object).put(value));\n } else {\n throw new JSONException(\"JSONObject[\" + key +\n \"] is not a JSONArray.\");\n }\n return this;\n }\n\n\n /**\n * Produce a string from a double. The string \"null\" will be returned if\n * the number is not finite.\n * @param d A double.\n * @return A String.\n */\n public static String doubleToString(double d) {\n if (Double.isInfinite(d) || Double.isNaN(d)) {\n return \"null\";\n }\n\n // Shave off trailing zeros and decimal point, if possible.\n\n String string = Double.toString(d);\n if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && \n string.indexOf('E') < 0) {\n while (string.endsWith(\"0\")) {\n string = string.substring(0, string.length() - 1);\n }\n if (string.endsWith(\"\")) {\n string = string.substring(0, string.length() - 1);\n }\n }\n return string;\n }\n\n\n /**\n * Get the value object associated with a key.\n *\n * @param key A key string.\n * @return The object associated with the key.\n * @throws JSONException if the key is not found.\n */\n public Object get(String key) throws JSONException {\n if (key == null) {\n throw new JSONException(\"Null key.\");\n }\n Object object = opt(key);\n if (object == null) {\n throw new JSONException(\"JSONObject[\" + quote(key) +\n \"] not found.\");\n }\n return object;\n }\n\n\n /**\n * Get the boolean value associated with a key.\n *\n * @param key A key string.\n * @return The truth.\n * @throws JSONException\n * if the value is not a Boolean or the String \"true\" or \"false\".\n */\n public boolean getBoolean(String key) throws JSONException {\n Object object = get(key);\n if (object.equals(Boolean.FALSE) ||\n (object instanceof String &&\n ((String)object).equalsIgnoreCase(\"false\"))) {\n return false;\n } else if (object.equals(Boolean.TRUE) ||\n (object instanceof String &&\n ((String)object).equalsIgnoreCase(\"true\"))) {\n return true;\n }\n throw new JSONException(\"JSONObject[\" + quote(key) +\n \"] is not a Boolean.\");\n }\n\n\n /**\n * Get the double value associated with a key.\n * @param key A key string.\n * @return The numeric value.\n * @throws JSONException if the key is not found or\n * if the value is not a Number object and cannot be converted to a number.\n */\n public double getDouble(String key) throws JSONException {\n Object object = get(key);\n try {\n return object instanceof Number ?\n ((Number)object).doubleValue() :\n Double.parseDouble((String)object);\n } catch (Exception e) {\n throw new JSONException(\"JSONObject[\" + quote(key) +\n \"] is not a number.\");\n }\n }\n\n\n /**\n * Get the int value associated with a key. \n *\n * @param key A key string.\n * @return The integer value.\n * @throws JSONException if the key is not found or if the value cannot\n * be converted to an integer.\n */\n public int getInt(String key) throws JSONException {\n Object object = get(key);\n try {\n return object instanceof Number ?\n ((Number)object).intValue() :\n Integer.parseInt((String)object);\n } catch (Exception e) {\n throw new JSONException(\"JSONObject[\" + quote(key) +\n \"] is not an int.\");\n }\n }\n\n\n /**\n * Get the JSONArray value associated with a key.\n *\n * @param key A key string.\n * @return A JSONArray which is the value.\n * @throws JSONException if the key is not found or\n * if the value is not a JSONArray.\n */\n public JSONArray getJSONArray(String key) throws JSONException {\n Object object = get(key);\n if (object instanceof JSONArray) {\n return (JSONArray)object;\n }\n throw new JSONException(\"JSONObject[\" + quote(key) +\n \"] is not a JSONArray.\");\n }\n\n\n /**\n * Get the JSONObject value associated with a key.\n *\n * @param key A key string.\n * @return A JSONObject which is the value.\n * @throws JSONException if the key is not found or\n * if the value is not a JSONObject.\n */\n public JSONObject getJSONObject(String key) throws JSONException {\n Object object = get(key);\n if (object instanceof JSONObject) {\n return (JSONObject)object;\n }\n throw new JSONException(\"JSONObject[\" + quote(key) +\n \"] is not a JSONObject.\");\n }\n\n\n /**\n * Get the long value associated with a key. \n *\n * @param key A key string.\n * @return The long value.\n * @throws JSONException if the key is not found or if the value cannot\n * be converted to a long.\n */\n public long getLong(String key) throws JSONException {\n Object object = get(key);\n try {\n return object instanceof Number ?\n ((Number)object).longValue() :\n Long.parseLong((String)object);\n } catch (Exception e) {\n throw new JSONException(\"JSONObject[\" + quote(key) +\n \"] is not a long.\");\n }\n }\n\n\n /**\n * Get an array of field names from a JSONObject.\n *\n * @return An array of field names, or null if there are no names.\n */\n public static String[] getNames(JSONObject jo) {\n int length = jo.length();\n if (length == 0) {\n return null;\n }\n Iterator iterator = jo.keys();\n String[] names = new String[length];\n int i = 0;\n while (iterator.hasNext()) {\n names[i] = (String)iterator.next();\n i += 1;\n }\n return names;\n }\n\n\n /**\n * Get an array of field names from an Object.\n *\n * @return An array of field names, or null if there are no names.\n */\n public static String[] getNames(Object object) {\n if (object == null) {\n return null;\n }\n Class klass = object.getClass();\n Field[] fields = klass.getFields();\n int length = fields.length;\n if (length == 0) {\n return null;\n }\n String[] names = new String[length];\n for (int i = 0; i < length; i += 1) {\n names[i] = fields[i].getName();\n }\n return names;\n }\n\n\n /**\n * Get the string associated with a key.\n *\n * @param key A key string.\n * @return A string which is the value.\n * @throws JSONException if the key is not found.\n */\n public String getString(String key) throws JSONException {\n Object object = get(key);\n return object == NULL ? null : object.toString();\n }\n\n\n /**\n * Determine if the JSONObject contains a specific key.\n * @param key A key string.\n * @return true if the key exists in the JSONObject.\n */\n public boolean has(String key) {\n return this.map.containsKey(key);\n }\n\n\n /**\n * Increment a property of a JSONObject. If there is no such property,\n * create one with a value of 1. If there is such a property, and if\n * it is an Integer, Long, Double, or Float, then add one to it.\n * @param key A key string.\n * @return this.\n * @throws JSONException If there is already a property with this name\n * that is not an Integer, Long, Double, or Float.\n */\n public JSONObject increment(String key) throws JSONException {\n Object value = opt(key);\n if (value == null) {\n put(key, 1);\n } else if (value instanceof Integer) {\n put(key, ((Integer)value).intValue() + 1);\n } else if (value instanceof Long) {\n put(key, ((Long)value).longValue() + 1); \n } else if (value instanceof Double) {\n put(key, ((Double)value).doubleValue() + 1); \n } else if (value instanceof Float) {\n put(key, ((Float)value).floatValue() + 1); \n } else {\n throw new JSONException(\"Unable to increment [\" + quote(key) + \"].\");\n }\n return this;\n }\n\n\n /**\n * Determine if the value associated with the key is null or if there is\n * no value.\n * @param key A key string.\n * @return true if there is no value associated with the key or if\n * the value is the JSONObject.NULL object.\n */\n public boolean isNull(String key) {\n return JSONObject.NULL.equals(opt(key));\n }\n\n\n /**\n * Get an enumeration of the keys of the JSONObject.\n *\n * @return An iterator of the keys.\n */\n public Iterator keys() {\n return this.map.keySet().iterator();\n }\n\n\n /**\n * Get the number of keys stored in the JSONObject.\n *\n * @return The number of keys in the JSONObject.\n */\n public int length() {\n return this.map.size();\n }\n\n\n /**\n * Produce a JSONArray containing the names of the elements of this\n * JSONObject.\n * @return A JSONArray containing the key strings, or null if the JSONObject\n * is empty.\n */\n public JSONArray names() {\n JSONArray ja = new JSONArray();\n Iterator keys = keys();\n while (keys.hasNext()) {\n ja.put(keys.next());\n }\n return ja.length() == 0 ? null : ja;\n }\n\n /**\n * Produce a string from a Number.\n * @param number A Number\n * @return A String.\n * @throws JSONException If n is a non-finite number.\n */\n public static String numberToString(Number number)\n throws JSONException {\n if (number == null) {\n throw new JSONException(\"Null pointer\");\n }\n testValidity(number);\n\n // Shave off trailing zeros and decimal point, if possible.\n\n String string = number.toString();\n if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && \n string.indexOf('E') < 0) {\n while (string.endsWith(\"0\")) {\n string = string.substring(0, string.length() - 1);\n }\n if (string.endsWith(\"\")) {\n string = string.substring(0, string.length() - 1);\n }\n }\n return string;\n }\n\n\n /**\n * Get an optional value associated with a key.\n * @param key A key string.\n * @return An object which is the value, or null if there is no value.\n */\n public Object opt(String key) {\n return key == null ? null : this.map.get(key);\n }\n\n\n /**\n * Get an optional boolean associated with a key.\n * It returns false if there is no such key, or if the value is not\n * Boolean.TRUE or the String \"true\".\n *\n * @param key A key string.\n * @return The truth.\n */\n public boolean optBoolean(String key) {\n return optBoolean(key, false);\n }\n\n\n /**\n * Get an optional boolean associated with a key.\n * It returns the defaultValue if there is no such key, or if it is not\n * a Boolean or the String \"true\" or \"false\" (case insensitive).\n *\n * @param key A key string.\n * @param defaultValue The default.\n * @return The truth.\n */\n public boolean optBoolean(String key, boolean defaultValue) {\n try {\n return getBoolean(key);\n } catch (Exception e) {\n return defaultValue;\n }\n }\n\n\n /**\n * Get an optional double associated with a key,\n * or NaN if there is no such key or if its value is not a number.\n * If the value is a string, an attempt will be made to evaluate it as\n * a number.\n *\n * @param key A string which is the key.\n * @return An object which is the value.\n */\n public double optDouble(String key) {\n return optDouble(key, Double.NaN);\n }\n\n\n /**\n * Get an optional double associated with a key, or the\n * defaultValue if there is no such key or if its value is not a number.\n * If the value is a string, an attempt will be made to evaluate it as\n * a number.\n *\n * @param key A key string.\n * @param defaultValue The default.\n * @return An object which is the value.\n */\n public double optDouble(String key, double defaultValue) {\n try {\n return getDouble(key);\n } catch (Exception e) {\n return defaultValue;\n }\n }\n\n\n /**\n * Get an optional int value associated with a key,\n * or zero if there is no such key or if the value is not a number.\n * If the value is a string, an attempt will be made to evaluate it as\n * a number.\n *\n * @param key A key string.\n * @return An object which is the value.\n */\n public int optInt(String key) {\n return optInt(key, 0);\n }\n\n\n /**\n * Get an optional int value associated with a key,\n * or the default if there is no such key or if the value is not a number.\n * If the value is a string, an attempt will be made to evaluate it as\n * a number.\n *\n * @param key A key string.\n * @param defaultValue The default.\n * @return An object which is the value.\n */\n public int optInt(String key, int defaultValue) {\n try {\n return getInt(key);\n } catch (Exception e) {\n return defaultValue;\n }\n }\n\n\n /**\n * Get an optional JSONArray associated with a key.\n * It returns null if there is no such key, or if its value is not a\n * JSONArray.\n *\n * @param key A key string.\n * @return A JSONArray which is the value.\n */\n public JSONArray optJSONArray(String key) {\n Object o = opt(key);\n return o instanceof JSONArray ? (JSONArray)o : null;\n }\n\n\n /**\n * Get an optional JSONObject associated with a key.\n * It returns null if there is no such key, or if its value is not a\n * JSONObject.\n *\n * @param key A key string.\n * @return A JSONObject which is the value.\n */\n public JSONObject optJSONObject(String key) {\n Object object = opt(key);\n return object instanceof JSONObject ? (JSONObject)object : null;\n }\n\n\n /**\n * Get an optional long value associated with a key,\n * or zero if there is no such key or if the value is not a number.\n * If the value is a string, an attempt will be made to evaluate it as\n * a number.\n *\n * @param key A key string.\n * @return An object which is the value.\n */\n public long optLong(String key) {\n return optLong(key, 0);\n }\n\n\n /**\n * Get an optional long value associated with a key,\n * or the default if there is no such key or if the value is not a number.\n * If the value is a string, an attempt will be made to evaluate it as\n * a number.\n *\n * @param key A key string.\n * @param defaultValue The default.\n * @return An object which is the value.\n */\n public long optLong(String key, long defaultValue) {\n try {\n return getLong(key);\n } catch (Exception e) {\n return defaultValue;\n }\n }\n\n\n /**\n * Get an optional string associated with a key.\n * It returns an empty string if there is no such key. If the value is not\n * a string and is not null, then it is converted to a string.\n *\n * @param key A key string.\n * @return A string which is the value.\n */\n public String optString(String key) {\n return optString(key, \"\");\n }\n\n\n /**\n * Get an optional string associated with a key.\n * It returns the defaultValue if there is no such key.\n *\n * @param key A key string.\n * @param defaultValue The default.\n * @return A string which is the value.\n */\n public String optString(String key, String defaultValue) {\n Object object = opt(key);\n return NULL.equals(object) ? defaultValue : object.toString(); \n }\n\n private void populateMap(Object bean) {\n Class klass = bean.getClass();\n\n // If klass is a System class then set includeSuperClass to false. \n\n boolean includeSuperClass = klass.getClassLoader() != null;\n\n Method[] methods = (includeSuperClass) ?\n klass.getMethods() : klass.getDeclaredMethods();\n for (int i = 0; i < methods.length; i += 1) {\n try {\n Method method = methods[i];\n if (Modifier.isPublic(method.getModifiers())) {\n String name = method.getName();\n String key = \"\";\n if (name.startsWith(\"get\")) {\n if (name.equals(\"getClass\") || \n name.equals(\"getDeclaringClass\")) {\n key = \"\";\n } else {\n key = name.substring(3);\n }\n } else if (name.startsWith(\"is\")) {\n key = name.substring(2);\n }\n if (key.length() > 0 &&\n Character.isUpperCase(key.charAt(0)) &&\n method.getParameterTypes().length == 0) {\n if (key.length() == 1) {\n key = key.toLowerCase();\n } else if (!Character.isUpperCase(key.charAt(1))) {\n key = key.substring(0, 1).toLowerCase() +\n key.substring(1);\n }\n\n Object result = method.invoke(bean, (Object[])null);\n if (result != null) {\n map.put(key, wrap(result));\n }\n }\n }\n } catch (Exception ignore) {\n }\n }\n }\n\n\n /**\n * Put a key/boolean pair in the JSONObject.\n *\n * @param key A key string.\n * @param value A boolean which is the value.\n * @return this.\n * @throws JSONException If the key is null.\n */\n public JSONObject put(String key, boolean value) throws JSONException {\n put(key, value ? Boolean.TRUE : Boolean.FALSE);\n return this;\n }\n\n\n /**\n * Put a key/value pair in the JSONObject, where the value will be a\n * JSONArray which is produced from a Collection.\n * @param key A key string.\n * @param value A Collection value.\n * @return this.\n * @throws JSONException\n */\n public JSONObject put(String key, Collection value) throws JSONException {\n put(key, new JSONArray(value));\n return this;\n }\n\n\n /**\n * Put a key/double pair in the JSONObject.\n *\n * @param key A key string.\n * @param value A double which is the value.\n * @return this.\n * @throws JSONException If the key is null or if the number is invalid.\n */\n public JSONObject put(String key, double value) throws JSONException {\n put(key, new Double(value));\n return this;\n }\n\n\n /**\n * Put a key/int pair in the JSONObject.\n *\n * @param key A key string.\n * @param value An int which is the value.\n * @return this.\n * @throws JSONException If the key is null.\n */\n public JSONObject put(String key, int value) throws JSONException {\n put(key, new Integer(value));\n return this;\n }\n\n\n /**\n * Put a key/long pair in the JSONObject.\n *\n * @param key A key string.\n * @param value A long which is the value.\n * @return this.\n * @throws JSONException If the key is null.\n */\n public JSONObject put(String key, long value) throws JSONException {\n put(key, new Long(value));\n return this;\n }\n\n\n /**\n * Put a key/value pair in the JSONObject, where the value will be a\n * JSONObject which is produced from a Map.\n * @param key A key string.\n * @param value A Map value.\n * @return this.\n * @throws JSONException\n */\n public JSONObject put(String key, Map value) throws JSONException {\n put(key, new JSONObject(value));\n return this;\n }\n\n\n /**\n * Put a key/value pair in the JSONObject. If the value is null,\n * then the key will be removed from the JSONObject if it is present.\n * @param key A key string.\n * @param value An object which is the value. It should be of one of these\n * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String,\n * or the JSONObject.NULL object.\n * @return this.\n * @throws JSONException If the value is non-finite number\n * or if the key is null.\n */\n public JSONObject put(String key, Object value) throws JSONException {\n if (key == null) {\n throw new JSONException(\"Null key.\");\n }\n if (value != null) {\n testValidity(value);\n this.map.put(key, value);\n } else {\n remove(key);\n }\n return this;\n }\n\n\n /**\n * Put a key/value pair in the JSONObject, but only if the key and the\n * value are both non-null, and only if there is not already a member\n * with that name.\n * @param key\n * @param value\n * @return his.\n * @throws JSONException if the key is a duplicate\n */\n public JSONObject putOnce(String key, Object value) throws JSONException {\n if (key != null && value != null) {\n if (opt(key) != null) {\n throw new JSONException(\"Duplicate key \\\"\" + key + \"\\\"\");\n }\n put(key, value);\n }\n return this;\n }\n\n\n /**\n * Put a key/value pair in the JSONObject, but only if the\n * key and the value are both non-null.\n * @param key A key string.\n * @param value An object which is the value. It should be of one of these\n * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, String,\n * or the JSONObject.NULL object.\n * @return this.\n * @throws JSONException If the value is a non-finite number.\n */\n public JSONObject putOpt(String key, Object value) throws JSONException {\n if (key != null && value != null) {\n put(key, value);\n }\n return this;\n }\n\n\n /**\n * Produce a string in double quotes with backslash sequences in all the\n * right places. A backslash will be inserted within </, producing <\\/,\n * allowing JSON text to be delivered in HTML. In JSON text, a string \n * cannot contain a control character or an unescaped quote or backslash.\n * @param string A String\n * @return A String correctly formatted for insertion in a JSON text.\n */\n public static String quote(String string) {\n if (string == null || string.length() == 0) {\n return \"\\\"\\\"\";\n }\n\n char b;\n char c = 0;\n String hhhh;\n int i;\n int len = string.length();\n StringBuffer sb = new StringBuffer(len + 4);\n\n sb.append('\"');\n for (i = 0; i < len; i += 1) {\n b = c;\n c = string.charAt(i);\n switch (c) {\n case '\\\\':\n case '\"':\n sb.append('\\\\');\n sb.append(c);\n break;\n case '/':\n if (b == '<') {\n sb.append('\\\\');\n }\n sb.append(c);\n break;\n case '\\b':\n sb.append(\"\\\\b\");\n break;\n case '\\t':\n sb.append(\"\\\\t\");\n break;\n case '\\n':\n sb.append(\"\\\\n\");\n break;\n case '\\f':\n sb.append(\"\\\\f\");\n break;\n case '\\r':\n sb.append(\"\\\\r\");\n break;\n default:\n if (c < ' ' || (c >= '\\u0080' && c < '\\u00a0') ||\n (c >= '\\u2000' && c < '\\u2100')) {\n hhhh = \"000\" + Integer.toHexString(c);\n sb.append(\"\\\\u\" + hhhh.substring(hhhh.length() - 4));\n } else {\n sb.append(c);\n }\n }\n }\n sb.append('\"');\n return sb.toString();\n }\n\n /**\n * Remove a name and its value, if present.\n * @param key The name to be removed.\n * @return The value that was associated with the name,\n * or null if there was no value.\n */\n public Object remove(String key) {\n return this.map.remove(key);\n }\n\n /**\n * Get an enumeration of the keys of the JSONObject.\n * The keys will be sorted alphabetically.\n *\n * @return An iterator of the keys.\n */\n public Iterator sortedKeys() {\n return new TreeSet(this.map.keySet()).iterator();\n }\n\n /**\n * Try to convert a string into a number, boolean, or null. If the string\n * can't be converted, return the string.\n * @param string A String.\n * @return A simple JSON value.\n */\n public static Object stringToValue(String string) {\n if (string.equals(\"\")) {\n return string;\n }\n if (string.equalsIgnoreCase(\"true\")) {\n return Boolean.TRUE;\n }\n if (string.equalsIgnoreCase(\"false\")) {\n return Boolean.FALSE;\n }\n if (string.equalsIgnoreCase(\"null\")) {\n return JSONObject.NULL;\n }\n\n /*\n * If it might be a number, try converting it. \n * We support the non-standard 0x- convention. \n * If a number cannot be produced, then the value will just\n * be a string. Note that the 0x-, plus, and implied string\n * conventions are non-standard. A JSON parser may accept\n * non-JSON forms as long as it accepts all correct JSON forms.\n */\n\n char b = string.charAt(0);\n if ((b >= '0' && b <= '9') || b == '.' || b == '-' || b == '+') {\n if (b == '0' && string.length() > 2 &&\n (string.charAt(1) == 'x' || string.charAt(1) == 'X')) {\n try {\n return new Integer(Integer.parseInt(string.substring(2), 16));\n } catch (Exception ignore) {\n }\n }\n try {\n if (string.indexOf('.') > -1 || \n string.indexOf('e') > -1 || string.indexOf('E') > -1) {\n return Double.valueOf(string);\n } else {\n Long myLong = new Long(string);\n if (myLong.longValue() == myLong.intValue()) {\n return new Integer(myLong.intValue());\n } else {\n return myLong;\n }\n }\n } catch (Exception ignore) {\n }\n }\n return string;\n }\n\n\n /**\n * Throw an exception if the object is a NaN or infinite number.\n * @param o The object to test.\n * @throws JSONException If o is a non-finite number.\n */\n public static void testValidity(Object o) throws JSONException {\n if (o != null) {\n if (o instanceof Double) {\n if (((Double)o).isInfinite() || ((Double)o).isNaN()) {\n throw new JSONException(\n \"JSON does not allow non-finite numbers.\");\n }\n } else if (o instanceof Float) {\n if (((Float)o).isInfinite() || ((Float)o).isNaN()) {\n throw new JSONException(\n \"JSON does not allow non-finite numbers.\");\n }\n }\n }\n }\n\n\n /**\n * Produce a JSONArray containing the values of the members of this\n * JSONObject.\n * @param names A JSONArray containing a list of key strings. This\n * determines the sequence of the values in the result.\n * @return A JSONArray of values.\n * @throws JSONException If any of the values are non-finite numbers.\n */\n public JSONArray toJSONArray(JSONArray names) throws JSONException {\n if (names == null || names.length() == 0) {\n return null;\n }\n JSONArray ja = new JSONArray();\n for (int i = 0; i < names.length(); i += 1) {\n ja.put(this.opt(names.getString(i)));\n }\n return ja;\n }\n\n /**\n * Make a JSON text of this JSONObject. For compactness, no whitespace\n * is added. If this would not result in a syntactically correct JSON text,\n * then null will be returned instead.\n * <p>\n * Warning: This method assumes that the data structure is acyclical.\n *\n * @return a printable, displayable, portable, transmittable\n * representation of the object, beginning\n * with <code>{</code> <small>(left brace)</small> and ending\n * with <code>}</code> <small>(right brace)</small>.\n */\n @Override\n public String toString() {\n try {\n Iterator keys = keys();\n StringBuffer sb = new StringBuffer(\"{\");\n\n while (keys.hasNext()) {\n if (sb.length() > 1) {\n sb.append(',');\n }\n Object o = keys.next();\n sb.append(quote(o.toString()));\n sb.append(':');\n sb.append(valueToString(this.map.get(o)));\n }\n sb.append('}');\n return sb.toString();\n } catch (Exception e) {\n return null;\n }\n }\n\n\n /**\n * Make a prettyprinted JSON text of this JSONObject.\n * <p>\n * Warning: This method assumes that the data structure is acyclical.\n * @param indentFactor The number of spaces to add to each level of\n * indentation.\n * @return a printable, displayable, portable, transmittable\n * representation of the object, beginning\n * with <code>{</code> <small>(left brace)</small> and ending\n * with <code>}</code> <small>(right brace)</small>.\n * @throws JSONException If the object contains an invalid number.\n */\n public String toString(int indentFactor) throws JSONException {\n return toString(indentFactor, 0);\n }\n\n\n /**\n * Make a prettyprinted JSON text of this JSONObject.\n * <p>\n * Warning: This method assumes that the data structure is acyclical.\n * @param indentFactor The number of spaces to add to each level of\n * indentation.\n * @param indent The indentation of the top level.\n * @return a printable, displayable, transmittable\n * representation of the object, beginning\n * with <code>{</code> <small>(left brace)</small> and ending\n * with <code>}</code> <small>(right brace)</small>.\n * @throws JSONException If the object contains an invalid number.\n */\n String toString(int indentFactor, int indent) throws JSONException {\n int i;\n int length = this.length();\n if (length == 0) {\n return \"{}\";\n }\n Iterator keys = sortedKeys();\n int newindent = indent + indentFactor;\n Object object;\n StringBuffer sb = new StringBuffer(\"{\");\n if (length == 1) {\n object = keys.next();\n sb.append(quote(object.toString()));\n sb.append(\": \");\n sb.append(valueToString(this.map.get(object), indentFactor,\n indent));\n } else {\n while (keys.hasNext()) {\n object = keys.next();\n if (sb.length() > 1) {\n sb.append(\",\\n\");\n } else {\n sb.append('\\n');\n }\n for (i = 0; i < newindent; i += 1) {\n sb.append(' ');\n }\n sb.append(quote(object.toString()));\n sb.append(\": \");\n sb.append(valueToString(this.map.get(object), indentFactor,\n newindent));\n }\n if (sb.length() > 1) {\n sb.append('\\n');\n for (i = 0; i < indent; i += 1) {\n sb.append(' ');\n }\n }\n }\n sb.append('}');\n return sb.toString();\n }\n\n\n /**\n * Make a JSON text of an Object value. If the object has an\n * value.toJSONString() method, then that method will be used to produce\n * the JSON text. The method is required to produce a strictly\n * conforming text. If the object does not contain a toJSONString\n * method (which is the most common case), then a text will be\n * produced by other means. If the value is an array or Collection,\n * then a JSONArray will be made from it and its toJSONString method\n * will be called. If the value is a MAP, then a JSONObject will be made\n * from it and its toJSONString method will be called. Otherwise, the\n * value's toString method will be called, and the result will be quoted.\n *\n * <p>\n * Warning: This method assumes that the data structure is acyclical.\n * @param value The value to be serialized.\n * @return a printable, displayable, transmittable\n * representation of the object, beginning\n * with <code>{</code> <small>(left brace)</small> and ending\n * with <code>}</code> <small>(right brace)</small>.\n * @throws JSONException If the value is or contains an invalid number.\n */\n public static String valueToString(Object value) throws JSONException {\n if (value == null || value.equals(null)) {\n return \"null\";\n }\n if (value instanceof JSONString) {\n Object object;\n try {\n object = ((JSONString)value).toJSONString();\n } catch (Exception e) {\n throw new JSONException(e);\n }\n if (object instanceof String) {\n return (String)object;\n }\n throw new JSONException(\"Bad value from toJSONString: \" + object);\n }\n if (value instanceof Number) {\n return numberToString((Number) value);\n }\n if (value instanceof Boolean || value instanceof JSONObject ||\n value instanceof JSONArray) {\n return value.toString();\n }\n if (value instanceof Map) {\n return new JSONObject((Map)value).toString();\n }\n if (value instanceof Collection) {\n return new JSONArray((Collection)value).toString();\n }\n if (value.getClass().isArray()) {\n return new JSONArray(value).toString();\n }\n return quote(value.toString());\n }\n\n\n /**\n * Make a prettyprinted JSON text of an object value.\n * <p>\n * Warning: This method assumes that the data structure is acyclical.\n * @param value The value to be serialized.\n * @param indentFactor The number of spaces to add to each level of\n * indentation.\n * @param indent The indentation of the top level.\n * @return a printable, displayable, transmittable\n * representation of the object, beginning\n * with <code>{</code> <small>(left brace)</small> and ending\n * with <code>}</code> <small>(right brace)</small>.\n * @throws JSONException If the object contains an invalid number.\n */\n static String valueToString(Object value, int indentFactor, int indent)\n throws JSONException {\n if (value == null || value.equals(null)) {\n return \"null\";\n }\n try {\n if (value instanceof JSONString) {\n Object o = ((JSONString)value).toJSONString();\n if (o instanceof String) {\n return (String)o;\n }\n }\n } catch (Exception ignore) {\n }\n if (value instanceof Number) {\n return numberToString((Number) value);\n }\n if (value instanceof Boolean) {\n return value.toString();\n }\n if (value instanceof JSONObject) {\n return ((JSONObject)value).toString(indentFactor, indent);\n }\n if (value instanceof JSONArray) {\n return ((JSONArray)value).toString(indentFactor, indent);\n }\n if (value instanceof Map) {\n return new JSONObject((Map)value).toString(indentFactor, indent);\n }\n if (value instanceof Collection) {\n return new JSONArray((Collection)value).toString(indentFactor, indent);\n }\n if (value.getClass().isArray()) {\n return new JSONArray(value).toString(indentFactor, indent);\n }\n return quote(value.toString());\n }\n\n\n /**\n * Wrap an object, if necessary. If the object is null, return the NULL \n * object. If it is an array or collection, wrap it in a JSONArray. If \n * it is a map, wrap it in a JSONObject. If it is a standard property \n * (Double, String, et al) then it is already wrapped. Otherwise, if it \n * comes from one of the java packages, turn it into a string. And if \n * it doesn't, try to wrap it in a JSONObject. If the wrapping fails,\n * then null is returned.\n *\n * @param object The object to wrap\n * @return The wrapped value\n */\n public static Object wrap(Object object) {\n try {\n if (object == null) {\n return NULL;\n }\n if (object instanceof JSONObject || object instanceof JSONArray || \n NULL.equals(object) || object instanceof JSONString || \n object instanceof Byte || object instanceof Character ||\n object instanceof Short || object instanceof Integer ||\n object instanceof Long || object instanceof Boolean || \n object instanceof Float || object instanceof Double ||\n object instanceof String) {\n return object;\n }\n\n if (object instanceof Collection) {\n return new JSONArray((Collection)object);\n }\n if (object.getClass().isArray()) {\n return new JSONArray(object);\n }\n if (object instanceof Map) {\n return new JSONObject((Map)object);\n }\n Package objectPackage = object.getClass().getPackage();\n String objectPackageName = ( objectPackage != null ? objectPackage.getName() : \"\" );\n if (objectPackageName.startsWith(\"java.\") ||\n objectPackageName.startsWith(\"javax.\") ||\n object.getClass().getClassLoader() == null) {\n return object.toString();\n }\n return new JSONObject(object);\n } catch(Exception exception) {\n return null;\n }\n }\n\n\n /**\n * Write the contents of the JSONObject as JSON text to a writer.\n * For compactness, no whitespace is added.\n * <p>\n * Warning: This method assumes that the data structure is acyclical.\n *\n * @return The writer.\n * @throws JSONException\n */\n public Writer write(Writer writer) throws JSONException {\n try {\n boolean commanate = false;\n Iterator keys = keys();\n writer.write('{');\n\n while (keys.hasNext()) {\n if (commanate) {\n writer.write(',');\n }\n Object key = keys.next();\n writer.write(quote(key.toString()));\n writer.write(':');\n Object value = this.map.get(key);\n if (value instanceof JSONObject) {\n ((JSONObject)value).write(writer);\n } else if (value instanceof JSONArray) {\n ((JSONArray)value).write(writer);\n } else {\n writer.write(valueToString(value));\n }\n commanate = true;\n }\n writer.write('}');\n return writer;\n } catch (IOException exception) {\n throw new JSONException(exception);\n }\n }\n}"
] | import org.bukkit.ChatColor;
import com.mcbans.plugin.ActionLog;
import com.mcbans.plugin.MCBans;
import com.mcbans.plugin.callBacks.PreviousCallback;
import com.mcbans.plugin.org.json.JSONException;
import com.mcbans.plugin.org.json.JSONObject; | package com.mcbans.plugin.request;
public class PreviousNames extends BaseRequest<PreviousCallback>{
public String target = "";
public PreviousNames(MCBans plugin, PreviousCallback callback, String target, String targetUUID, String sender) {
super(plugin, callback);
this.items.put("player", target);
this.items.put("player_uuid", targetUUID);
this.items.put("admin", sender);
this.items.put("exec", "uuidLookup");
this.target = (!target.equals(""))?target:targetUUID;
}
@Override
protected void execute() {
// TODO Auto-generated method stub
if (callback.getSender() != null){
log.info(callback.getSender().getName() + " performed a player history lookup for " + target + "!");
}
JSONObject result = this.request_JOBJ();
try{
callback.success(result.getString("player"), result.getString("players"));
} | catch (JSONException ex) { | 3 |
srinathwarrier/BrandstoreApp | app/src/main/java/com/brandstore1/activities/OutletListActivity.java | [
"public class BrandstoreApplication extends Application {\r\n // model\r\n private static int numUnreadMessages;\r\n private static NotificationCompat.InboxStyle inboxStyle;\r\n\r\n private static BrandstoreApplication mInstance;\r\n\r\n private static NotificationStatus notificationStatus = NotificationStatus.DEFAULT;\r\n\r\n private static String combinedUserSongId =\"\";\r\n public static final int NOTIFICATION_ID = 1;\r\n\r\n public static String getCombinedUserSongId() {\r\n return combinedUserSongId;\r\n }\r\n\r\n public static void setCombinedUserSongId(String combinedUserSongId) {\r\n BrandstoreApplication.combinedUserSongId = combinedUserSongId;\r\n }\r\n\r\n public NotificationCompat.InboxStyle getInboxStyle() {\r\n return inboxStyle;\r\n }\r\n\r\n public void setInboxStyle(NotificationCompat.InboxStyle inboxStyle) {\r\n this.inboxStyle = inboxStyle;\r\n }\r\n\r\n public int getNumUnreadMessages() {\r\n return numUnreadMessages;\r\n }\r\n\r\n public void setNumUnreadMessages(int numUnreadMessages) {\r\n this.numUnreadMessages = numUnreadMessages;\r\n }\r\n\r\n public static NotificationStatus addNotification(NotificationMessage notificationMessage){\r\n numUnreadMessages++;\r\n String newUserSongId = notificationMessage.getUserSongId();\r\n\r\n if(notificationMessage.getNotificationType() == NotificationType.ADD_SONG){\r\n setCombinedUserSongId(\"\");\r\n switch(notificationStatus){\r\n case DEFAULT:\r\n // Old was default(none) , New is ADD_SONG. So change to ADD_SONG\r\n notificationStatus = NotificationStatus.ONLY_ADD_SONG;\r\n break;\r\n case ONLY_ADD_SONG:\r\n // Old was ADD_SONG , New is also ADD_SONG. So keep as ADD_SONG (DO NOTHING)\r\n break;\r\n case SAME_TALK_SONG:\r\n // Old was TALK_SONG for same song, New is ADD_SONG. So change to BOTH\r\n notificationStatus = NotificationStatus.ALL_TYPES;\r\n break;\r\n case ALL_TYPES:\r\n // Old was BOTH , New is ADD_SONG. So keep as BOTH (DO NOTHING)\r\n break;\r\n case DIFFERENT_TALK_SONG:\r\n // Old was TALK_SONG for different song, New is ADD_SONG. So change to BOTH\r\n notificationStatus = NotificationStatus.ALL_TYPES;\r\n break;\r\n default:\r\n break;\r\n }\r\n }\r\n else if (notificationMessage.getNotificationType() == NotificationType.TALK_SONG){\r\n switch(notificationStatus){\r\n case DEFAULT:\r\n // Old was default(none) , New is TALK_SONG. So change to TALK_SONG\r\n notificationStatus = NotificationStatus.SAME_TALK_SONG;\r\n setCombinedUserSongId(newUserSongId);\r\n break;\r\n case ONLY_ADD_SONG:\r\n // Old was ADD_SONG , New is TALK_SONG. So change to BOTH\r\n notificationStatus = NotificationStatus.ALL_TYPES;\r\n setCombinedUserSongId(\"\");\r\n break;\r\n case SAME_TALK_SONG:\r\n // Old was TALK_SONG for same song, New is TALK_SONG. So , check if UserSongId is same.\r\n // if same, DO NOTHING\r\n // if different, change to 4 :TALK_SONG for different Songs\r\n if(!getCombinedUserSongId().equals(newUserSongId)){\r\n setCombinedUserSongId(\"\");\r\n notificationStatus= NotificationStatus.DIFFERENT_TALK_SONG;\r\n }\r\n\r\n break;\r\n case ALL_TYPES:\r\n // Old was BOTH , New is TALK_SONG. So keep as BOTH (DO NOTHING)\r\n break;\r\n case DIFFERENT_TALK_SONG:\r\n // Old was TALK_SONG for Different songs, New is TALK_SONG. So keep as TALK_SONG for Different songs(Do nothing)\r\n break;\r\n default:\r\n break;\r\n }\r\n\r\n }\r\n return notificationStatus;\r\n }\r\n\r\n @Override\r\n public void onCreate() {\r\n super.onCreate();\r\n mInstance = this;\r\n mInstance.initializeInstance();\r\n }\r\n\r\n private void initializeInstance() {\r\n // TODO: Initialize Image Loader and other libraries here.\r\n }\r\n\r\n public void removeAllNotifications(){\r\n setNumUnreadMessages(0);\r\n setInboxStyle(new NotificationCompat.InboxStyle());\r\n notificationStatus = NotificationStatus.DEFAULT;\r\n setCombinedUserSongId(\"\");\r\n\r\n NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);\r\n notificationManager.cancel(NOTIFICATION_ID);\r\n }\r\n\r\n public static BrandstoreApplication getInstance() {\r\n return mInstance;\r\n }\r\n\r\n public enum NotificationType{\r\n ADD_SONG , TALK_SONG;\r\n }\r\n\r\n public enum NotificationStatus{\r\n DEFAULT, ONLY_ADD_SONG, SAME_TALK_SONG,DIFFERENT_TALK_SONG , ALL_TYPES\r\n /*\r\n Notification Status meanings:\r\n 0: default,\r\n 1: only ADD_SONG ,\r\n 2: only TALK_SONG (and for the same song),\r\n 3 : both 1 and 2 ,\r\n 4: only TALK_SONG but for DIFFERENT songs. !\r\n */\r\n }\r\n // The following line should be changed to include the correct property id.\r\n private static final String PROPERTY_ID = \"UA-60355049-1\";\r\n\r\n public enum TrackerName {\r\n APP_TRACKER, // Tracker used only in this app.\r\n GLOBAL_TRACKER, // Tracker used by all the apps from a company. eg: roll-up tracking.\r\n ECOMMERCE_TRACKER, // Tracker used by all ecommerce transactions from a company.\r\n }\r\n\r\n HashMap<TrackerName, Tracker> mTrackers = new HashMap<TrackerName, Tracker>();\r\n\r\n public synchronized Tracker getTracker(TrackerName trackerId) {\r\n if (!mTrackers.containsKey(trackerId)) {\r\n\r\n GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);\r\n Tracker t = (trackerId == TrackerName.APP_TRACKER) ? analytics.newTracker(PROPERTY_ID) : null;\r\n mTrackers.put(trackerId, t);\r\n\r\n }\r\n return mTrackers.get(trackerId);\r\n }\r\n\r\n}\r",
"public class OutletListAdapter extends BaseAdapter implements Filterable {\n ArrayList<Outlet> mOutletList;\n ArrayList<Outlet> origOutletList;\n private LayoutInflater inflater;\n private Filter filter;\n private Filter saleFilter;\n Toolbar toolbar;\n TextView emptyView;\n OutletListFilterConstraint outletListFilterConstraint;\n\n public OutletListAdapter(ArrayList<Outlet> outlet, Activity context, Toolbar toolbar, TextView emptyView) {\n this.inflater = (LayoutInflater) context\n .getSystemService(Context.LAYOUT_INFLATER_SERVICE);\n mOutletList = outlet;\n origOutletList = new ArrayList<Outlet>();\n this.toolbar = toolbar;\n this.emptyView = emptyView;\n }\n\n public void setOutletListFilterConstraint(OutletListFilterConstraint outletListFilterConstraint){\n this.outletListFilterConstraint = outletListFilterConstraint;\n }\n\n @Override\n public int getCount() {\n return mOutletList.size();\n }\n\n @Override\n public Object getItem(int position) {\n return null;\n }\n\n @Override\n public long getItemId(int position) {\n return 0;\n }\n\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n ViewHolder1 mHolder;\n\n if (convertView == null) {\n mHolder = new ViewHolder1();\n convertView = inflater.inflate(R.layout.outlet_list_list_view_item, null);\n mHolder.brandNameTextView = (TextView) convertView.findViewById(R.id.outletname);\n mHolder.floorAndHubNameTextView = (TextView) convertView.findViewById(R.id.floorAndHubName);\n mHolder.tagTextView = (TextView) convertView.findViewById(R.id.tag_label);\n mHolder.priceTextView= (TextView) convertView.findViewById(R.id.price_label);\n mHolder.image = (ImageView) convertView.findViewById(R.id.outlet_image);\n mHolder.male = (ImageView) convertView.findViewById(R.id.first);\n mHolder.female = (ImageView) convertView.findViewById(R.id.second);\n mHolder.kids = (ImageView) convertView.findViewById(R.id.third);\n convertView.setTag(mHolder);\n } else {\n mHolder = (ViewHolder1) convertView.getTag();\n }\n\n mHolder.male.setVisibility(View.INVISIBLE);\n mHolder.female.setVisibility(View.INVISIBLE);\n mHolder.kids.setVisibility(View.INVISIBLE);\n if (mOutletList.get(position).getGenderCodeString().contains(\"M\"))\n mHolder.male.setVisibility(View.VISIBLE);\n\n if (mOutletList.get(position).getGenderCodeString().contains(\"F\"))\n mHolder.female.setVisibility(View.VISIBLE);\n\n if (mOutletList.get(position).getGenderCodeString().contains(\"K\"))\n mHolder.kids.setVisibility(View.VISIBLE);\n\n\n mHolder.brandNameTextView.setText(mOutletList.get(position).getBrandOutletName());\n mHolder.floorAndHubNameTextView.setText(mOutletList.get(position).getFloorNumber() + \", \" + mOutletList.get(position).getMallName());\n mHolder.tagTextView.setText(mOutletList.get(position).getRelevantTag());\n mHolder.priceTextView.setText(\" : ₹ \" + mOutletList.get(position).getPrice());\n\n LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT);\n p.weight = 1;\n mHolder.tagTextView.setLayoutParams(p);\n\n ImageLoader.getInstance().displayImage(mOutletList.get(position).getImageUrl(), mHolder.image);\n\n return convertView;\n }\n\n\n static class ViewHolder1 {\n\n TextView brandNameTextView;\n TextView floorAndHubNameTextView;\n\n TextView tagTextView;\n TextView priceTextView;\n\n ImageView image;\n ImageView male;\n ImageView female;\n ImageView kids;\n }\n\n// public void resetData() {\n// mOutletList = origOutletList;\n// }\n\n @Override\n public Filter getFilter(){\n if (filter == null){\n filter = new OutletFilter();\n }\n return filter;\n }\n\n\n private class OutletFilter extends Filter\n {\n @Override\n protected FilterResults performFiltering(CharSequence filter) {\n\n FilterResults result = new FilterResults();\n ArrayList<Outlet> list = new ArrayList<Outlet>();\n for (int i = 0, l = mOutletList.size(); i < l; i++) {\n Outlet m = mOutletList.get(i);\n\n if (outletListFilterConstraint.satisfiesConstraint(m))\n list.add(m);\n }\n\n if(list!=null && list.size()>0 && !outletListFilterConstraint.isSORT_BY_RELEVANCE()){\n list = outletListFilterConstraint.getSortedOutletArrayList(list);\n }\n\n result.values = list;\n result.count = list.size();\n return result;\n }\n @SuppressWarnings(\"unchecked\")\n @Override\n protected void publishResults(CharSequence filter, FilterResults results) {\n\n //mOutletList = (ArrayList<Outlet>) results.values;\n setOutletListFrom((ArrayList<Outlet>) results.values);\n toolbar.setSubtitle(getCount() + \" \" + \"Outlets\");\n notifyDataSetChanged();\n if (results.count == 0)\n emptyView.setText(\"No outlets found\");\n }\n }\n\n\n public void setOutletListFrom(ArrayList<Outlet> theOrigOutletList){\n int count = theOrigOutletList.size();\n mOutletList.clear();\n for (int i = 0; i < count; i++) {\n mOutletList.add(theOrigOutletList.get(i));\n }\n notifyDataSetChanged();\n }\n\n public void setOutletListFromOriginal(){\n int count = origOutletList.size();\n mOutletList.clear();\n for (int i = 0; i < count; i++) {\n mOutletList.add(origOutletList.get(i));\n }\n notifyDataSetChanged();\n }\n\n\n public void setOrigOutletListFrom(ArrayList<Outlet> theOutletList){\n int count = theOutletList.size();\n origOutletList.clear();\n for (int i = 0; i < count; i++) {\n origOutletList.add(theOutletList.get(i));\n }\n }\n\n}",
"public class OutletListAsyncTask extends AsyncTask<Void, Void, String> {\n ArrayList<Outlet> mOutletArrayList;\n String query;\n OutletListAdapter mOutletListAdapter;\n Outlet obj;\n String tagOrCollectionId;\n TextView emptyView;\n Toolbar toolbar;\n\n CircularProgressDialog circularProgressDialog;\n Context mContext;\n\n String urlString;\n\n public OutletListAsyncTask(ArrayList<Outlet> outletArrayList,\n String text,\n OutletListAdapter adapter,\n String id,\n TextView theEmptyView,\n Toolbar toolbar,\n Context context,\n OutletListActivity.OutletListType outletListType) {\n // Basic\n this.mOutletArrayList = outletArrayList;\n this.mOutletListAdapter = adapter;\n this.mContext = context;\n\n // UI Elements\n this.emptyView = theEmptyView;\n this.toolbar = toolbar;\n\n // Parameters\n String userId = \"6\";\n this.tagOrCollectionId = id;\n this.query = text;\n Connections connections = new Connections();\n this.urlString = connections.getOutletListForTagURL(this.tagOrCollectionId);\n\n switch(outletListType){\n case ALL_FAVORITE:\n this.urlString = connections.getAllFavoriteOutletsURL();\n break;\n case ALL_ON_SALE:\n this.urlString = connections.getAllOnSaleOutletsURL();\n break;\n case CLICKED_ON_COLLECTION:\n this.urlString = connections.getOutletListForCollectionURL(this.tagOrCollectionId);\n break;\n case CLICKED_ON_TAG:\n this.urlString = connections.getOutletListForTagURL(this.tagOrCollectionId);\n break;\n case SEARCHED_QUERY:\n break;\n default:\n break;\n }\n }\n\n @Override\n protected void onPreExecute() {\n super.onPreExecute();\n\n circularProgressDialog = new CircularProgressDialog(this.mContext);\n circularProgressDialog = CircularProgressDialog.show(this.mContext,\"\",\"\");\n }\n\n @Override\n protected String doInBackground(Void... params) {\n mOutletArrayList.clear();\n StringBuilder builder = null;\n try {\n URL url = new URL(urlString);\n\n HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();\n\n String line;\n builder = new StringBuilder();\n InputStreamReader isr = new InputStreamReader(\n urlConnection.getInputStream()\n );\n BufferedReader reader = new BufferedReader(isr);\n while ((line = reader.readLine()) != null) builder.append(line);\n\n return (builder.toString());\n } catch (MalformedURLException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n return null;\n }\n\n @Override\n protected void onPostExecute(String resultString) {\n super.onPostExecute(resultString);\n try {\n\n JSONArray json = new JSONArray(resultString);\n\n for (int i = 0; i < json.length(); i++) {\n Log.i(\"Brandstore - Outletlist\", \"Start \");\n obj = new Outlet();\n JSONObject object = json.getJSONObject(i);\n obj.setBrandOutletName(object.get(\"outletName\").toString());\n obj.setImageUrl(object.get(\"imageUrl\").toString());\n obj.setContactNumber(object.get(\"phoneNumber\").toString());\n obj.setFloorNumber(object.get(\"floorNumber\").toString());\n obj.setId(object.get(\"outletID\").toString());\n obj.setRelevantTag(object.get(\"tagName\").toString());\n obj.setPrice(object.get(\"avgPrice\").toString());\n obj.setGenderCodeString(object.get(\"genderCodeString\").toString());\n obj.setMallName(object.get(\"hubName\").toString());\n obj.setIsFavorite(object.get(\"isFavorite\").toString());\n obj.setIsOnSale(object.get(\"isOnSale\").toString());\n\n Log.i(\"Brandstore - Outletlist\", \"object:\" + obj.toString());\n mOutletArrayList.add(obj);\n }\n } catch (JSONException e) {\n e.printStackTrace();\n } catch (Exception e) {\n e.printStackTrace();\n }\n\n\n try {\n if (mOutletArrayList.size() == 0) {\n emptyView.setText(\"No outlets found\");\n }\n else{\n //toolbar.setTitle(mOutletArrayList.get(0).getRelevantTag().toString());\n toolbar.setSubtitle(mOutletArrayList.size() + \" \" + \"Outlets\");\n }\n }catch(Exception e){\n e.printStackTrace();\n }\n mOutletListAdapter.setOrigOutletListFrom(mOutletArrayList);\n mOutletListAdapter.notifyDataSetChanged();\n circularProgressDialog.dismiss();\n //OutletList\n\n }\n}",
"public class Outlet {\n\n\n private String BrandOutletName;\n private String ImageUrl;\n private String ContactNumber;\n private String FloorNumber;\n private String MallName;\n private String RelevantTag;\n private String Price;\n private String Id;\n private String genderCodeString;\n private String descriptionString;\n private String websiteString;\n private String isFavorite;\n private String isOnSale;\n\n public String getGenderCodeString() {\n return genderCodeString;\n }\n\n public void setGenderCodeString(String genderCodeString) {\n this.genderCodeString = genderCodeString;\n }\n\n public String getBrandOutletName() {\n return BrandOutletName;\n }\n\n public void setBrandOutletName(String brandOutletName) {\n BrandOutletName = brandOutletName;\n }\n\n public String getImageUrl() {\n return ImageUrl;\n }\n\n public void setImageUrl(String imageUrl) {\n ImageUrl = imageUrl;\n }\n\n\n public String getContactNumber() {\n return ContactNumber;\n }\n\n public void setContactNumber(String contactNumber) {\n ContactNumber = contactNumber;\n }\n\n public String getFloorNumber() {\n return FloorNumber;\n }\n\n public void setFloorNumber(String floorNumber) {\n FloorNumber = floorNumber;\n }\n\n public String getMallName() {\n return MallName;\n }\n\n public void setMallName(String mallName) {\n MallName = mallName;\n }\n\n public String getPrice() {\n return Price;\n }\n\n public void setPrice(String price) {\n Price = price;\n }\n\n\n public String getId() {\n return Id;\n }\n\n public void setId(String id) {\n Id = id;\n }\n\n\n public String getRelevantTag() {\n return RelevantTag;\n }\n\n public void setRelevantTag(String relevantTag) {\n RelevantTag = relevantTag;\n }\n\n public String getDescriptionString() {\n return descriptionString;\n }\n\n public void setDescriptionString(String descriptionString) {\n this.descriptionString = descriptionString;\n }\n\n public String getWebsiteString() {\n return websiteString;\n }\n\n public void setWebsiteString(String websiteString) {\n this.websiteString = websiteString;\n }\n\n public String getIsFavorite() {\n return isFavorite;\n }\n\n public void setIsFavorite(String isFavorite) {\n this.isFavorite = isFavorite;\n }\n\n public String getIsOnSale() {\n return isOnSale;\n }\n\n public void setIsOnSale(String isOnSale) {\n this.isOnSale = isOnSale;\n }\n\n\n}",
"public class OutletListFilterConstraint {\n\n /* Gender Filter Constraints */\n private boolean HAS_TO_BE_MALE_OUTLET;\n private boolean HAS_TO_BE_FEMALE_OUTLET;\n private boolean HAS_TO_BE_CHILDREN_OUTLET;\n public final String FILTER_GENDER_MALE = \"Male\";\n public final String FILTER_GENDER_FEMALE = \"Female\";\n public final String FILTER_GENDER_CHILDREN =\"Children\";\n\n /* Average Price Filter Constraints */\n private boolean PRICE_BETWEEN_0_AND_500;\n private boolean PRICE_BETWEEN_500_AND_1500;\n private boolean PRICE_BETWEEN_1500_AND_2500;\n private boolean PRICE_BETWEEN_2500_AND_3500;\n private boolean PRICE_ABOVE_3500;\n public final String FILTER_PRICE_BETWEEN_0_AND_500 = \"0-500\";\n public final String FILTER_PRICE_BETWEEN_500_AND_1500 = \"500-1500\";\n public final String FILTER_PRICE_BETWEEN_1500_AND_2500 = \"1500-2500\";\n public final String FILTER_PRICE_BETWEEN_2500_AND_3500 = \"2500-3500\";\n public final String FILTER_PRICE_ABOVE_3500 = \"3500+\";\n\n\n /* Floor Constraints */\n private boolean HAS_TO_BE_LOWER_GROUND_FLOOR;\n private boolean HAS_TO_BE_GROUND_FLOOR;\n private boolean HAS_TO_BE_FIRST_FLOOR;\n private boolean HAS_TO_BE_SECOND_FLOOR;\n public final String FLOOR_LOWER_GROUND = \"Lower ground floor\";\n public final String FLOOR_GROUND = \"Ground floor\";\n public final String FLOOR_FIRST = \"First floor\";\n public final String FLOOR_SECOND = \"Second floor\";\n\n /* More Filter Constraints */\n private boolean HAS_TO_BE_ON_SALE;\n private boolean HAS_TO_BE_FAVORITE;\n public final String FILTER_ON_SALE= \"On Sale\";\n public final String FILTER_IS_FAVORITE = \"My Favourites\";\n\n /* Sort Types */\n private boolean SORT_BY_RELEVANCE=true;\n private boolean SORT_BY_PRICE_LOW_TO_HIGH;\n private boolean SORT_BY_PRICE_HIGH_TO_LOW;\n public final String STRING_SORT_BY_RELEVANCE= \"Relevance\";\n public final String STRING_SORT_BY_PRICE_LOW_TO_HIGH= \"Average Price (Low to high)\";\n public final String STRING_SORT_BY_PRICE_HIGH_TO_LOW= \"Average Price (High to low)\";\n\n\n // Create empty constraint ArrayLists\n public ArrayList<String> genderArrayList = new ArrayList<>();\n public ArrayList<String> averagePriceArrayList = new ArrayList<>();\n public ArrayList<String> floorArrayList = new ArrayList<>();\n public ArrayList<String> moreFiltersArrayList = new ArrayList<>();\n public ArrayList<String> sortArrayList = new ArrayList<>();\n\n public OutletListFilterConstraint(){\n genderArrayList.add(FILTER_GENDER_MALE);\n genderArrayList.add(FILTER_GENDER_FEMALE);\n genderArrayList.add(FILTER_GENDER_CHILDREN);\n averagePriceArrayList.add(FILTER_PRICE_BETWEEN_0_AND_500);\n averagePriceArrayList.add(FILTER_PRICE_BETWEEN_500_AND_1500);\n averagePriceArrayList.add(FILTER_PRICE_BETWEEN_1500_AND_2500);\n averagePriceArrayList.add(FILTER_PRICE_BETWEEN_2500_AND_3500);\n averagePriceArrayList.add(FILTER_PRICE_ABOVE_3500);\n moreFiltersArrayList.add(FILTER_ON_SALE);\n moreFiltersArrayList.add(FILTER_IS_FAVORITE);\n sortArrayList.add(STRING_SORT_BY_RELEVANCE);\n sortArrayList.add(STRING_SORT_BY_PRICE_LOW_TO_HIGH);\n sortArrayList.add(STRING_SORT_BY_PRICE_HIGH_TO_LOW);\n floorArrayList.add(FLOOR_LOWER_GROUND);\n floorArrayList.add(FLOOR_GROUND);\n floorArrayList.add(FLOOR_FIRST);\n floorArrayList.add(FLOOR_SECOND);\n }\n\n public boolean satisfiesConstraint(Outlet outlet){\n boolean returnValue = true;\n if(isHAS_TO_BE_FAVORITE()){\n if(!outlet.getIsFavorite().equals(\"true\")) {\n return false;\n }\n returnValue = true;\n }\n if(isHAS_TO_BE_ON_SALE()){\n if(!outlet.getIsOnSale().equals(\"true\")){\n return false;\n }\n returnValue = true;\n }\n // Look for all 3 checks : Male , Female, Children\n if(isHAS_TO_BE_MALE_OUTLET()){\n // If male is checked, look for \"M\" in genderCodeString\n if(!outlet.getGenderCodeString().contains(\"M\")){\n return false;\n }\n returnValue = true;\n }\n if(isHAS_TO_BE_FEMALE_OUTLET()){\n // If female is checked, look for \"F\" in genderCodeString\n if(!outlet.getGenderCodeString().contains(\"F\")){\n return false;\n }\n returnValue = true;\n }\n if(isHAS_TO_BE_CHILDREN_OUTLET()){\n // If children is checked, look for \"K\" in genderCodeString\n if(!outlet.getGenderCodeString().contains(\"K\")){\n return false;\n }\n returnValue = true;\n }\n if(isPRICE_BETWEEN_0_AND_500() ||\n isPRICE_BETWEEN_500_AND_1500() ||\n isPRICE_BETWEEN_1500_AND_2500() ||\n isPRICE_BETWEEN_2500_AND_3500() ||\n isPRICE_ABOVE_3500() )\n {\n if(outlet.getPrice().equals(\"\")){\n return false;\n }\n int price = Integer.parseInt(outlet.getPrice());\n returnValue = returnValue &&\n ( ( (price>=0 && price<=500) && (isPRICE_BETWEEN_0_AND_500()) ) ||\n ( (price>=500 && price<=1500) && (isPRICE_BETWEEN_500_AND_1500()) ) ||\n ( (price>=1500 && price<=2500) && (isPRICE_BETWEEN_1500_AND_2500()) ) ||\n ( (price>=2500 && price<=3500) && (isPRICE_BETWEEN_2500_AND_3500()) ) ||\n ( (price>=3500) && (isPRICE_ABOVE_3500()) )\n );\n\n }\n if(isHAS_TO_BE_LOWER_GROUND_FLOOR() ||\n isHAS_TO_BE_GROUND_FLOOR() ||\n isHAS_TO_BE_FIRST_FLOOR() ||\n isHAS_TO_BE_SECOND_FLOOR() )\n {\n returnValue = returnValue &&\n ( (outlet.getFloorNumber().equalsIgnoreCase(FLOOR_LOWER_GROUND) && isHAS_TO_BE_LOWER_GROUND_FLOOR() ) ||\n (outlet.getFloorNumber().equalsIgnoreCase(FLOOR_GROUND) && isHAS_TO_BE_GROUND_FLOOR() ) ||\n (outlet.getFloorNumber().equalsIgnoreCase(FLOOR_FIRST) && isHAS_TO_BE_FIRST_FLOOR() ) ||\n (outlet.getFloorNumber().equalsIgnoreCase(FLOOR_SECOND) && isHAS_TO_BE_SECOND_FLOOR() )\n );\n }\n return returnValue;\n }\n\n public ArrayList<Outlet> getSortedOutletArrayList(ArrayList<Outlet> outletArrayList){\n if(isSORT_BY_PRICE_LOW_TO_HIGH()){\n Collections.sort(outletArrayList, new Comparator<Outlet>() {\n @Override\n public int compare(Outlet outlet1, Outlet outlet2) {\n int price1 = (outlet1.getPrice().equals(\"\"))?0:Integer.parseInt(outlet1.getPrice()),\n price2 = (outlet2.getPrice().equals(\"\"))?0:Integer.parseInt(outlet2.getPrice());\n return (price1 - price2);\n }\n });\n return outletArrayList;\n }else if(isSORT_BY_PRICE_HIGH_TO_LOW()){\n Collections.sort(outletArrayList, new Comparator<Outlet>() {\n @Override\n public int compare(Outlet outlet1, Outlet outlet2) {\n int price1 = (outlet1.getPrice().equals(\"\"))?0:Integer.parseInt(outlet1.getPrice()),\n price2 = (outlet2.getPrice().equals(\"\"))?0:Integer.parseInt(outlet2.getPrice());\n return (price2 - price1);\n }\n });\n return outletArrayList;\n }\n return outletArrayList;\n }\n\n public boolean getIsClicked(String FILTER_TITLE){\n switch (FILTER_TITLE){\n case FILTER_IS_FAVORITE:\n return isHAS_TO_BE_FAVORITE();\n case FILTER_ON_SALE:\n return isHAS_TO_BE_ON_SALE();\n case FILTER_GENDER_MALE:\n return isHAS_TO_BE_MALE_OUTLET();\n case FILTER_GENDER_FEMALE:\n return isHAS_TO_BE_FEMALE_OUTLET();\n case FILTER_GENDER_CHILDREN:\n return isHAS_TO_BE_CHILDREN_OUTLET();\n case FILTER_PRICE_BETWEEN_0_AND_500 :\n return isPRICE_BETWEEN_0_AND_500();\n case FILTER_PRICE_BETWEEN_500_AND_1500 :\n return isPRICE_BETWEEN_500_AND_1500();\n case FILTER_PRICE_BETWEEN_1500_AND_2500 :\n return isPRICE_BETWEEN_1500_AND_2500();\n case FILTER_PRICE_BETWEEN_2500_AND_3500 :\n return isPRICE_BETWEEN_2500_AND_3500();\n case FILTER_PRICE_ABOVE_3500 :\n return isPRICE_ABOVE_3500();\n case STRING_SORT_BY_RELEVANCE:\n return isSORT_BY_RELEVANCE();\n case STRING_SORT_BY_PRICE_LOW_TO_HIGH:\n return isSORT_BY_PRICE_LOW_TO_HIGH();\n case STRING_SORT_BY_PRICE_HIGH_TO_LOW:\n return isSORT_BY_PRICE_HIGH_TO_LOW();\n case FLOOR_LOWER_GROUND:\n return isHAS_TO_BE_LOWER_GROUND_FLOOR();\n case FLOOR_GROUND:\n return isHAS_TO_BE_GROUND_FLOOR();\n case FLOOR_FIRST:\n return isHAS_TO_BE_FIRST_FLOOR();\n case FLOOR_SECOND:\n return isHAS_TO_BE_SECOND_FLOOR();\n }\n return false;\n }\n\n public void onFilterClicked(String FILTER_TITLE, boolean isSetNow){\n switch (FILTER_TITLE){\n case FILTER_IS_FAVORITE:\n setHAS_TO_BE_FAVORITE(isSetNow);\n break;\n case FILTER_ON_SALE:\n setHAS_TO_BE_ON_SALE(isSetNow);\n break;\n case FILTER_GENDER_MALE:\n setHAS_TO_BE_MALE_OUTLET(isSetNow);\n setHAS_TO_BE_FEMALE_OUTLET(false);\n setHAS_TO_BE_CHILDREN_OUTLET(false);\n break;\n case FILTER_GENDER_FEMALE:\n setHAS_TO_BE_MALE_OUTLET(false);\n setHAS_TO_BE_FEMALE_OUTLET(isSetNow);\n setHAS_TO_BE_CHILDREN_OUTLET(false);\n break;\n case FILTER_GENDER_CHILDREN:\n setHAS_TO_BE_MALE_OUTLET(false);\n setHAS_TO_BE_FEMALE_OUTLET(false);\n setHAS_TO_BE_CHILDREN_OUTLET(isSetNow);\n break;\n case FILTER_PRICE_BETWEEN_0_AND_500 :\n setPRICE_BETWEEN_0_AND_500(isSetNow);\n break;\n case FILTER_PRICE_BETWEEN_500_AND_1500 :\n setPRICE_BETWEEN_500_AND_1500(isSetNow);\n break;\n case FILTER_PRICE_BETWEEN_1500_AND_2500 :\n setPRICE_BETWEEN_1500_AND_2500(isSetNow);\n break;\n case FILTER_PRICE_BETWEEN_2500_AND_3500 :\n setPRICE_BETWEEN_2500_AND_3500(isSetNow);\n break;\n case FILTER_PRICE_ABOVE_3500 :\n setPRICE_ABOVE_3500(isSetNow);\n break;\n case STRING_SORT_BY_RELEVANCE :\n setSORT_BY_RELEVANCE(true);\n setSORT_BY_PRICE_LOW_TO_HIGH(false);\n setSORT_BY_PRICE_HIGH_TO_LOW(false);\n break;\n case STRING_SORT_BY_PRICE_LOW_TO_HIGH:\n setSORT_BY_RELEVANCE(false);\n setSORT_BY_PRICE_LOW_TO_HIGH(true);\n setSORT_BY_PRICE_HIGH_TO_LOW(false);\n break;\n case STRING_SORT_BY_PRICE_HIGH_TO_LOW:\n setSORT_BY_RELEVANCE(false);\n setSORT_BY_PRICE_LOW_TO_HIGH(false);\n setSORT_BY_PRICE_HIGH_TO_LOW(true);\n break;\n case FLOOR_LOWER_GROUND:\n setHAS_TO_BE_LOWER_GROUND_FLOOR(isSetNow);\n break;\n case FLOOR_GROUND:\n setHAS_TO_BE_GROUND_FLOOR(isSetNow);\n break;\n case FLOOR_FIRST:\n setHAS_TO_BE_FIRST_FLOOR(isSetNow);\n break;\n case FLOOR_SECOND:\n setHAS_TO_BE_SECOND_FLOOR(isSetNow);\n break;\n }\n }\n\n public boolean isInResetState(){\n if( isSORT_BY_RELEVANCE() &&\n !isSORT_BY_PRICE_HIGH_TO_LOW() &&\n !isSORT_BY_PRICE_LOW_TO_HIGH() &&\n !isPRICE_BETWEEN_0_AND_500() &&\n !isPRICE_BETWEEN_500_AND_1500() &&\n !isPRICE_BETWEEN_1500_AND_2500() &&\n !isPRICE_BETWEEN_2500_AND_3500() &&\n !isPRICE_ABOVE_3500() &&\n !isHAS_TO_BE_MALE_OUTLET() &&\n !isHAS_TO_BE_FEMALE_OUTLET() &&\n !isHAS_TO_BE_CHILDREN_OUTLET() &&\n !isHAS_TO_BE_FAVORITE() &&\n !isHAS_TO_BE_ON_SALE() &&\n !isHAS_TO_BE_LOWER_GROUND_FLOOR() &&\n !isHAS_TO_BE_GROUND_FLOOR() &&\n !isHAS_TO_BE_FIRST_FLOOR() &&\n !isHAS_TO_BE_SECOND_FLOOR()\n ){\n return true;\n }\n return false;\n }\n public void setToResetState(){\n setSORT_BY_RELEVANCE(true);\n setSORT_BY_PRICE_HIGH_TO_LOW(false);\n setSORT_BY_PRICE_LOW_TO_HIGH(false);\n setPRICE_BETWEEN_0_AND_500(false);\n setPRICE_BETWEEN_500_AND_1500(false);\n setPRICE_BETWEEN_1500_AND_2500(false);\n setPRICE_BETWEEN_2500_AND_3500(false);\n setPRICE_ABOVE_3500(false);\n setHAS_TO_BE_MALE_OUTLET(false);\n setHAS_TO_BE_FEMALE_OUTLET(false);\n setHAS_TO_BE_CHILDREN_OUTLET(false);\n setHAS_TO_BE_FAVORITE(false);\n setHAS_TO_BE_ON_SALE(false);\n setHAS_TO_BE_LOWER_GROUND_FLOOR(false);\n setHAS_TO_BE_GROUND_FLOOR(false);\n setHAS_TO_BE_FIRST_FLOOR(false);\n setHAS_TO_BE_SECOND_FLOOR(false);\n }\n\n\n public boolean isHAS_TO_BE_MALE_OUTLET() {\n return HAS_TO_BE_MALE_OUTLET;\n }\n\n public void setHAS_TO_BE_MALE_OUTLET(boolean HAS_TO_BE_MALE_OUTLET) {\n this.HAS_TO_BE_MALE_OUTLET = HAS_TO_BE_MALE_OUTLET;\n }\n\n public boolean isHAS_TO_BE_FEMALE_OUTLET() {\n return HAS_TO_BE_FEMALE_OUTLET;\n }\n\n public void setHAS_TO_BE_FEMALE_OUTLET(boolean HAS_TO_BE_FEMALE_OUTLET) {\n this.HAS_TO_BE_FEMALE_OUTLET = HAS_TO_BE_FEMALE_OUTLET;\n }\n\n public boolean isHAS_TO_BE_CHILDREN_OUTLET() {\n return HAS_TO_BE_CHILDREN_OUTLET;\n }\n\n public void setHAS_TO_BE_CHILDREN_OUTLET(boolean HAS_TO_BE_CHILDREN_OUTLET) {\n this.HAS_TO_BE_CHILDREN_OUTLET = HAS_TO_BE_CHILDREN_OUTLET;\n }\n\n public boolean isPRICE_BETWEEN_0_AND_500() {\n return PRICE_BETWEEN_0_AND_500;\n }\n\n public void setPRICE_BETWEEN_0_AND_500(boolean PRICE_BETWEEN_0_AND_500) {\n this.PRICE_BETWEEN_0_AND_500 = PRICE_BETWEEN_0_AND_500;\n }\n\n public boolean isPRICE_BETWEEN_500_AND_1500() {\n return PRICE_BETWEEN_500_AND_1500;\n }\n\n public void setPRICE_BETWEEN_500_AND_1500(boolean PRICE_BETWEEN_500_AND_1500) {\n this.PRICE_BETWEEN_500_AND_1500 = PRICE_BETWEEN_500_AND_1500;\n }\n\n public boolean isPRICE_BETWEEN_1500_AND_2500() {\n return PRICE_BETWEEN_1500_AND_2500;\n }\n\n public void setPRICE_BETWEEN_1500_AND_2500(boolean PRICE_BETWEEN_1500_AND_2500) {\n this.PRICE_BETWEEN_1500_AND_2500 = PRICE_BETWEEN_1500_AND_2500;\n }\n\n public boolean isPRICE_BETWEEN_2500_AND_3500() {\n return PRICE_BETWEEN_2500_AND_3500;\n }\n\n public void setPRICE_BETWEEN_2500_AND_3500(boolean PRICE_BETWEEN_2500_AND_3500) {\n this.PRICE_BETWEEN_2500_AND_3500 = PRICE_BETWEEN_2500_AND_3500;\n }\n\n public boolean isHAS_TO_BE_ON_SALE() {\n return HAS_TO_BE_ON_SALE;\n }\n\n public void setHAS_TO_BE_ON_SALE(boolean HAS_TO_BE_ON_SALE) {\n this.HAS_TO_BE_ON_SALE = HAS_TO_BE_ON_SALE;\n }\n\n public boolean isHAS_TO_BE_FAVORITE() {\n return HAS_TO_BE_FAVORITE;\n }\n\n public void setHAS_TO_BE_FAVORITE(boolean HAS_TO_BE_FAVORITE) {\n this.HAS_TO_BE_FAVORITE = HAS_TO_BE_FAVORITE;\n }\n\n public boolean isPRICE_ABOVE_3500() {\n return PRICE_ABOVE_3500;\n }\n\n public void setPRICE_ABOVE_3500(boolean PRICE_ABOVE_3500) {\n this.PRICE_ABOVE_3500 = PRICE_ABOVE_3500;\n }\n\n public boolean isSORT_BY_RELEVANCE() {\n return SORT_BY_RELEVANCE;\n }\n\n public void setSORT_BY_RELEVANCE(boolean SORT_BY_RELEVANCE) {\n this.SORT_BY_RELEVANCE = SORT_BY_RELEVANCE;\n }\n\n public boolean isSORT_BY_PRICE_LOW_TO_HIGH() {\n return SORT_BY_PRICE_LOW_TO_HIGH;\n }\n\n public void setSORT_BY_PRICE_LOW_TO_HIGH(boolean SORT_BY_PRICE_LOW_TO_HIGH) {\n this.SORT_BY_PRICE_LOW_TO_HIGH = SORT_BY_PRICE_LOW_TO_HIGH;\n }\n\n public boolean isSORT_BY_PRICE_HIGH_TO_LOW() {\n return SORT_BY_PRICE_HIGH_TO_LOW;\n }\n\n public void setSORT_BY_PRICE_HIGH_TO_LOW(boolean SORT_BY_PRICE_HIGH_TO_LOW) {\n this.SORT_BY_PRICE_HIGH_TO_LOW = SORT_BY_PRICE_HIGH_TO_LOW;\n }\n\n public boolean isHAS_TO_BE_LOWER_GROUND_FLOOR() {\n return HAS_TO_BE_LOWER_GROUND_FLOOR;\n }\n\n public void setHAS_TO_BE_LOWER_GROUND_FLOOR(boolean HAS_TO_BE_LOWER_GROUND_FLOOR) {\n this.HAS_TO_BE_LOWER_GROUND_FLOOR = HAS_TO_BE_LOWER_GROUND_FLOOR;\n }\n\n public boolean isHAS_TO_BE_GROUND_FLOOR() {\n return HAS_TO_BE_GROUND_FLOOR;\n }\n\n public void setHAS_TO_BE_GROUND_FLOOR(boolean HAS_TO_BE_GROUND_FLOOR) {\n this.HAS_TO_BE_GROUND_FLOOR = HAS_TO_BE_GROUND_FLOOR;\n }\n\n public boolean isHAS_TO_BE_FIRST_FLOOR() {\n return HAS_TO_BE_FIRST_FLOOR;\n }\n\n public void setHAS_TO_BE_FIRST_FLOOR(boolean HAS_TO_BE_FIRST_FLOOR) {\n this.HAS_TO_BE_FIRST_FLOOR = HAS_TO_BE_FIRST_FLOOR;\n }\n\n public boolean isHAS_TO_BE_SECOND_FLOOR() {\n return HAS_TO_BE_SECOND_FLOOR;\n }\n\n public void setHAS_TO_BE_SECOND_FLOOR(boolean HAS_TO_BE_SECOND_FLOOR) {\n this.HAS_TO_BE_SECOND_FLOOR = HAS_TO_BE_SECOND_FLOOR;\n }\n}",
"public class OutletListFilters extends Fragment {\n private static final String TAG = \"OLFiltersFragment\";\n public static boolean isOpen = false;\n RecyclerView rvAveragePrice, rvGender, rvMoreFilters,rvSort ,rvFloor;\n AveragePriceAdapter averagePriceAdapter;\n GenderAdapter genderAdapter;\n MoreFiltersAdapter moreFiltersAdapter;\n SortAdapter sortAdapter;\n FloorAdapter floorAdapter;\n LinearLayoutManager genderLayoutManager, moreFiltersLayoutManger, averagePriceLayoutManager , sortLayoutManager , floorLayoutManager;\n\n ArrayList<String> genderArray ;\n ArrayList<String> moreFiltersArray ;\n ArrayList<String> averagePriceArray ;\n ArrayList<String> sortArray ;\n ArrayList<String> floorArray ;\n\n Button applyFilterButton;\n\n OutletListFilterConstraint outletListFilterConstraint;\n Toolbar mToolbar;\n\n public OutletListFilters() {\n\n }\n\n public static OutletListFilters getInstance() {\n OutletListFilters outletListFilters = new OutletListFilters();\n Bundle bundle = new Bundle();\n outletListFilters.setArguments(bundle);\n return outletListFilters;\n }\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n if(((OutletListActivity)getActivity()).getOutletListFilterConstraint()==null){\n outletListFilterConstraint = new OutletListFilterConstraint();\n }\n else{\n outletListFilterConstraint =((OutletListActivity)getActivity()).getOutletListFilterConstraint();\n }\n genderArray = outletListFilterConstraint.genderArrayList;\n moreFiltersArray = outletListFilterConstraint.moreFiltersArrayList;\n averagePriceArray = outletListFilterConstraint.averagePriceArrayList;\n sortArray = outletListFilterConstraint.sortArrayList;\n floorArray = outletListFilterConstraint.floorArrayList;\n }\n\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {\n super.onCreateView(inflater, container, savedInstanceState);\n isOpen = true;\n View layout = inflater.inflate(R.layout.fragment_filters, container, false);\n getViewReferences(layout);\n initViews();\n\n //for create home button\n mToolbar.setNavigationIcon(R.drawable.ic_cancel_white);\n mToolbar.setNavigationOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n FragmentManager fragmentManager = getFragmentManager();\n fragmentManager.beginTransaction().\n remove(fragmentManager.findFragmentById(R.id.fl_filters)).commit();\n }\n });\n mToolbar.setTitle(\"\");\n mToolbar.inflateMenu(R.menu.menu_fragment_filters);\n mToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {\n @Override\n public boolean onMenuItemClick(MenuItem item) {\n switch (item.getItemId()){\n case R.id.reset_button:\n outletListFilterConstraint.setToResetState();\n sortAdapter.notifyDataSetChanged();\n averagePriceAdapter.notifyDataSetChanged();\n genderAdapter.notifyDataSetChanged();\n moreFiltersAdapter.notifyDataSetChanged();\n floorAdapter.notifyDataSetChanged();\n return true;\n }\n return false;\n }\n });\n\n\n applyFilterButton = (Button) layout.findViewById(R.id.btn_apply_filters);\n applyFilterButton.setOnClickListener(new View.OnClickListener() {\n\n @Override\n public void onClick(View v) {\n Log.i(TAG, \"Clicked\");\n\n // Set outletListFilterConstraint\n ((OutletListActivity) getActivity()).setOutletListFilterConstraint(outletListFilterConstraint);\n\n // If outletListFilterConstraint has any change, then change Filter icon on Toolbar\n if (!outletListFilterConstraint.isInResetState()) {\n ((OutletListActivity) getActivity()).setFilterIconSelected(true);\n }\n else {\n ((OutletListActivity) getActivity()).setFilterIconSelected(false);\n }\n\n // Reset list\n ((OutletListActivity) getActivity()).resetArrayList();\n\n FragmentManager fragmentManager = getFragmentManager();\n fragmentManager.beginTransaction().\n remove(fragmentManager.findFragmentById(R.id.fl_filters)).commit();\n }\n });\n return layout;\n }\n\n private void getViewReferences(View layout) {\n rvAveragePrice = (RecyclerView) layout.findViewById(R.id.rv_average_price);\n rvGender = (RecyclerView) layout.findViewById(R.id.rv_gender);\n rvMoreFilters = (RecyclerView) layout.findViewById(R.id.rv_more_filters);\n rvSort = (RecyclerView) layout.findViewById(R.id.rv_sort);\n rvFloor = (RecyclerView) layout.findViewById(R.id.rv_floor);\n mToolbar = (Toolbar) layout.findViewById(R.id.outletlistfiltertoolbar);\n }\n\n public static boolean isOpen() {\n return isOpen;\n }\n\n @Override\n public void onDestroy() {\n super.onDestroy();\n isOpen = false;\n }\n\n public void initViews() {\n genderAdapter = new GenderAdapter(genderArray, outletListFilterConstraint, getContext());\n averagePriceAdapter = new AveragePriceAdapter(averagePriceArray,outletListFilterConstraint , getActivity());\n moreFiltersAdapter = new MoreFiltersAdapter(moreFiltersArray,outletListFilterConstraint, getActivity());\n sortAdapter = new SortAdapter(sortArray, outletListFilterConstraint, getActivity());\n floorAdapter = new FloorAdapter(floorArray, outletListFilterConstraint, getActivity());\n\n genderLayoutManager = new LinearLayoutManager(getActivity());\n averagePriceLayoutManager = new LinearLayoutManager(getContext());\n moreFiltersLayoutManger = new LinearLayoutManager(getContext());\n sortLayoutManager = new LinearLayoutManager(getContext());\n floorLayoutManager = new LinearLayoutManager(getContext());\n\n rvAveragePrice.setLayoutManager(averagePriceLayoutManager);\n rvGender.setLayoutManager(genderLayoutManager);\n rvMoreFilters.setLayoutManager(moreFiltersLayoutManger);\n rvSort.setLayoutManager(sortLayoutManager);\n rvFloor.setLayoutManager(floorLayoutManager);\n\n rvAveragePrice.addItemDecoration(new DividerItemDecoration(getActivity(), null));\n rvGender.addItemDecoration(new DividerItemDecoration(getActivity(), null));\n rvMoreFilters.addItemDecoration(new DividerItemDecoration(getActivity(), null));\n rvSort.addItemDecoration(new DividerItemDecoration(getActivity(),null));\n rvFloor.addItemDecoration(new DividerItemDecoration(getActivity(),null));\n\n rvAveragePrice.setAdapter(averagePriceAdapter);\n rvGender.setAdapter(genderAdapter);\n rvMoreFilters.setAdapter(moreFiltersAdapter);\n rvSort.setAdapter(sortAdapter);\n rvFloor.setAdapter(floorAdapter);\n }\n\n public void onApplyFilterClicked(View v){\n\n }\n}"
] | import android.content.Intent;
import android.graphics.Point;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import com.brandstore1.BrandstoreApplication;
import com.brandstore1.R;
import com.brandstore1.adapters.OutletListAdapter;
import com.brandstore1.asynctasks.OutletListAsyncTask;
import com.brandstore1.entities.Outlet;
import com.brandstore1.entities.OutletListFilterConstraint;
import com.brandstore1.fragments.OutletListFilters;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.utils.StorageUtils;
import java.io.File;
import java.util.ArrayList; | package com.brandstore1.activities;
public class OutletListActivity extends ActionBarActivity {
private static final String TAG = OutletListActivity.class.getSimpleName();
ListView lvOutletListView;
Toolbar toolbar;
MenuItem favoriteMenuItem;
MenuItem saleMenuItem;
MenuItem filterItem;
OutletListAdapter mOutletListAdapter;
OutletListType outletListType;
OutletListFilters outletListFilters;
| ArrayList<Outlet> outletArrayList = new ArrayList<Outlet>(); | 3 |
jklingsporn/vertx-jooq-async | vertx-jooq-async-generate/src/test/java/generated/rx/async/vertx/tables/Something.java | [
"@Generated(\n value = {\n \"http://www.jooq.org\",\n \"jOOQ version:3.10.1\"\n },\n comments = \"This class is generated by jOOQ\"\n)\n@SuppressWarnings({ \"all\", \"unchecked\", \"rawtypes\" })\npublic class DefaultSchema extends SchemaImpl {\n\n private static final long serialVersionUID = -1561434826;\n\n /**\n * The reference instance of <code></code>\n */\n public static final DefaultSchema DEFAULT_SCHEMA = new DefaultSchema();\n\n /**\n * The table <code>something</code>.\n */\n public final Something SOMETHING = generated.rx.async.vertx.tables.Something.SOMETHING;\n\n /**\n * The table <code>somethingComposite</code>.\n */\n public final Somethingcomposite SOMETHINGCOMPOSITE = generated.rx.async.vertx.tables.Somethingcomposite.SOMETHINGCOMPOSITE;\n\n /**\n * The table <code>somethingWithoutJson</code>.\n */\n public final Somethingwithoutjson SOMETHINGWITHOUTJSON = generated.rx.async.vertx.tables.Somethingwithoutjson.SOMETHINGWITHOUTJSON;\n\n /**\n * No further instances allowed\n */\n private DefaultSchema() {\n super(\"\", null);\n }\n\n\n /**\n * {@inheritDoc}\n */\n @Override\n public Catalog getCatalog() {\n return DefaultCatalog.DEFAULT_CATALOG;\n }\n\n @Override\n public final List<Table<?>> getTables() {\n List result = new ArrayList();\n result.addAll(getTables0());\n return result;\n }\n\n private final List<Table<?>> getTables0() {\n return Arrays.<Table<?>>asList(\n Something.SOMETHING,\n Somethingcomposite.SOMETHINGCOMPOSITE,\n Somethingwithoutjson.SOMETHINGWITHOUTJSON);\n }\n}",
"@Generated(\n value = {\n \"http://www.jooq.org\",\n \"jOOQ version:3.10.1\"\n },\n comments = \"This class is generated by jOOQ\"\n)\n@SuppressWarnings({ \"all\", \"unchecked\", \"rawtypes\" })\npublic class Indexes {\n\n // -------------------------------------------------------------------------\n // INDEX definitions\n // -------------------------------------------------------------------------\n\n public static final Index SOMETHING_PRIMARY = Indexes0.SOMETHING_PRIMARY;\n public static final Index SOMETHINGCOMPOSITE_PRIMARY = Indexes0.SOMETHINGCOMPOSITE_PRIMARY;\n public static final Index SOMETHINGWITHOUTJSON_PRIMARY = Indexes0.SOMETHINGWITHOUTJSON_PRIMARY;\n\n // -------------------------------------------------------------------------\n // [#1459] distribute members to avoid static initialisers > 64kb\n // -------------------------------------------------------------------------\n\n private static class Indexes0 extends AbstractKeys {\n public static Index SOMETHING_PRIMARY = createIndex(\"PRIMARY\", Something.SOMETHING, new OrderField[] { Something.SOMETHING.SOMEID }, true);\n public static Index SOMETHINGCOMPOSITE_PRIMARY = createIndex(\"PRIMARY\", Somethingcomposite.SOMETHINGCOMPOSITE, new OrderField[] { Somethingcomposite.SOMETHINGCOMPOSITE.SOMEID, Somethingcomposite.SOMETHINGCOMPOSITE.SOMESECONDID }, true);\n public static Index SOMETHINGWITHOUTJSON_PRIMARY = createIndex(\"PRIMARY\", Somethingwithoutjson.SOMETHINGWITHOUTJSON, new OrderField[] { Somethingwithoutjson.SOMETHINGWITHOUTJSON.SOMEID }, true);\n }\n}",
"@Generated(\n value = {\n \"http://www.jooq.org\",\n \"jOOQ version:3.10.1\"\n },\n comments = \"This class is generated by jOOQ\"\n)\n@SuppressWarnings({ \"all\", \"unchecked\", \"rawtypes\" })\npublic class Keys {\n\n // -------------------------------------------------------------------------\n // IDENTITY definitions\n // -------------------------------------------------------------------------\n\n public static final Identity<SomethingRecord, Integer> IDENTITY_SOMETHING = Identities0.IDENTITY_SOMETHING;\n public static final Identity<SomethingwithoutjsonRecord, Integer> IDENTITY_SOMETHINGWITHOUTJSON = Identities0.IDENTITY_SOMETHINGWITHOUTJSON;\n\n // -------------------------------------------------------------------------\n // UNIQUE and PRIMARY KEY definitions\n // -------------------------------------------------------------------------\n\n public static final UniqueKey<SomethingRecord> KEY_SOMETHING_PRIMARY = UniqueKeys0.KEY_SOMETHING_PRIMARY;\n public static final UniqueKey<SomethingcompositeRecord> KEY_SOMETHINGCOMPOSITE_PRIMARY = UniqueKeys0.KEY_SOMETHINGCOMPOSITE_PRIMARY;\n public static final UniqueKey<SomethingwithoutjsonRecord> KEY_SOMETHINGWITHOUTJSON_PRIMARY = UniqueKeys0.KEY_SOMETHINGWITHOUTJSON_PRIMARY;\n\n // -------------------------------------------------------------------------\n // FOREIGN KEY definitions\n // -------------------------------------------------------------------------\n\n\n // -------------------------------------------------------------------------\n // [#1459] distribute members to avoid static initialisers > 64kb\n // -------------------------------------------------------------------------\n\n private static class Identities0 extends AbstractKeys {\n public static Identity<SomethingRecord, Integer> IDENTITY_SOMETHING = createIdentity(Something.SOMETHING, Something.SOMETHING.SOMEID);\n public static Identity<SomethingwithoutjsonRecord, Integer> IDENTITY_SOMETHINGWITHOUTJSON = createIdentity(Somethingwithoutjson.SOMETHINGWITHOUTJSON, Somethingwithoutjson.SOMETHINGWITHOUTJSON.SOMEID);\n }\n\n private static class UniqueKeys0 extends AbstractKeys {\n public static final UniqueKey<SomethingRecord> KEY_SOMETHING_PRIMARY = createUniqueKey(Something.SOMETHING, \"KEY_something_PRIMARY\", Something.SOMETHING.SOMEID);\n public static final UniqueKey<SomethingcompositeRecord> KEY_SOMETHINGCOMPOSITE_PRIMARY = createUniqueKey(Somethingcomposite.SOMETHINGCOMPOSITE, \"KEY_somethingComposite_PRIMARY\", Somethingcomposite.SOMETHINGCOMPOSITE.SOMEID, Somethingcomposite.SOMETHINGCOMPOSITE.SOMESECONDID);\n public static final UniqueKey<SomethingwithoutjsonRecord> KEY_SOMETHINGWITHOUTJSON_PRIMARY = createUniqueKey(Somethingwithoutjson.SOMETHINGWITHOUTJSON, \"KEY_somethingWithoutJson_PRIMARY\", Somethingwithoutjson.SOMETHINGWITHOUTJSON.SOMEID);\n }\n}",
"@Generated(\n value = {\n \"http://www.jooq.org\",\n \"jOOQ version:3.10.1\"\n },\n comments = \"This class is generated by jOOQ\"\n)\n@SuppressWarnings({ \"all\", \"unchecked\", \"rawtypes\" })\npublic class SomethingRecord extends UpdatableRecordImpl<SomethingRecord> implements Record9<Integer, String, Long, Short, Integer, Double, String, JsonObject, JsonArray>, ISomething {\n\n private static final long serialVersionUID = 900372103;\n\n /**\n * Setter for <code>something.someId</code>.\n */\n @Override\n public SomethingRecord setSomeid(Integer value) {\n set(0, value);\n return this;\n }\n\n /**\n * Getter for <code>something.someId</code>.\n */\n @Override\n public Integer getSomeid() {\n return (Integer) get(0);\n }\n\n /**\n * Setter for <code>something.someString</code>.\n */\n @Override\n public SomethingRecord setSomestring(String value) {\n set(1, value);\n return this;\n }\n\n /**\n * Getter for <code>something.someString</code>.\n */\n @Override\n public String getSomestring() {\n return (String) get(1);\n }\n\n /**\n * Setter for <code>something.someHugeNumber</code>.\n */\n @Override\n public SomethingRecord setSomehugenumber(Long value) {\n set(2, value);\n return this;\n }\n\n /**\n * Getter for <code>something.someHugeNumber</code>.\n */\n @Override\n public Long getSomehugenumber() {\n return (Long) get(2);\n }\n\n /**\n * Setter for <code>something.someSmallNumber</code>.\n */\n @Override\n public SomethingRecord setSomesmallnumber(Short value) {\n set(3, value);\n return this;\n }\n\n /**\n * Getter for <code>something.someSmallNumber</code>.\n */\n @Override\n public Short getSomesmallnumber() {\n return (Short) get(3);\n }\n\n /**\n * Setter for <code>something.someRegularNumber</code>.\n */\n @Override\n public SomethingRecord setSomeregularnumber(Integer value) {\n set(4, value);\n return this;\n }\n\n /**\n * Getter for <code>something.someRegularNumber</code>.\n */\n @Override\n public Integer getSomeregularnumber() {\n return (Integer) get(4);\n }\n\n /**\n * Setter for <code>something.someDouble</code>.\n */\n @Override\n public SomethingRecord setSomedouble(Double value) {\n set(5, value);\n return this;\n }\n\n /**\n * Getter for <code>something.someDouble</code>.\n */\n @Override\n public Double getSomedouble() {\n return (Double) get(5);\n }\n\n /**\n * Setter for <code>something.someEnum</code>.\n */\n @Override\n public SomethingRecord setSomeenum(String value) {\n set(6, value);\n return this;\n }\n\n /**\n * Getter for <code>something.someEnum</code>.\n */\n @Override\n public String getSomeenum() {\n return (String) get(6);\n }\n\n /**\n * Setter for <code>something.someJsonObject</code>.\n */\n @Override\n public SomethingRecord setSomejsonobject(JsonObject value) {\n set(7, value);\n return this;\n }\n\n /**\n * Getter for <code>something.someJsonObject</code>.\n */\n @Override\n public JsonObject getSomejsonobject() {\n return (JsonObject) get(7);\n }\n\n /**\n * Setter for <code>something.someJsonArray</code>.\n */\n @Override\n public SomethingRecord setSomejsonarray(JsonArray value) {\n set(8, value);\n return this;\n }\n\n /**\n * Getter for <code>something.someJsonArray</code>.\n */\n @Override\n public JsonArray getSomejsonarray() {\n return (JsonArray) get(8);\n }\n\n // -------------------------------------------------------------------------\n // Primary key information\n // -------------------------------------------------------------------------\n\n /**\n * {@inheritDoc}\n */\n @Override\n public Record1<Integer> key() {\n return (Record1) super.key();\n }\n\n // -------------------------------------------------------------------------\n // Record9 type implementation\n // -------------------------------------------------------------------------\n\n /**\n * {@inheritDoc}\n */\n @Override\n public Row9<Integer, String, Long, Short, Integer, Double, String, JsonObject, JsonArray> fieldsRow() {\n return (Row9) super.fieldsRow();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public Row9<Integer, String, Long, Short, Integer, Double, String, JsonObject, JsonArray> valuesRow() {\n return (Row9) super.valuesRow();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public Field<Integer> field1() {\n return Something.SOMETHING.SOMEID;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public Field<String> field2() {\n return Something.SOMETHING.SOMESTRING;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public Field<Long> field3() {\n return Something.SOMETHING.SOMEHUGENUMBER;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public Field<Short> field4() {\n return Something.SOMETHING.SOMESMALLNUMBER;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public Field<Integer> field5() {\n return Something.SOMETHING.SOMEREGULARNUMBER;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public Field<Double> field6() {\n return Something.SOMETHING.SOMEDOUBLE;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public Field<String> field7() {\n return Something.SOMETHING.SOMEENUM;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public Field<JsonObject> field8() {\n return Something.SOMETHING.SOMEJSONOBJECT;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public Field<JsonArray> field9() {\n return Something.SOMETHING.SOMEJSONARRAY;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public Integer component1() {\n return getSomeid();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public String component2() {\n return getSomestring();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public Long component3() {\n return getSomehugenumber();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public Short component4() {\n return getSomesmallnumber();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public Integer component5() {\n return getSomeregularnumber();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public Double component6() {\n return getSomedouble();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public String component7() {\n return getSomeenum();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public JsonObject component8() {\n return getSomejsonobject();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public JsonArray component9() {\n return getSomejsonarray();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public Integer value1() {\n return getSomeid();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public String value2() {\n return getSomestring();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public Long value3() {\n return getSomehugenumber();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public Short value4() {\n return getSomesmallnumber();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public Integer value5() {\n return getSomeregularnumber();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public Double value6() {\n return getSomedouble();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public String value7() {\n return getSomeenum();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public JsonObject value8() {\n return getSomejsonobject();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public JsonArray value9() {\n return getSomejsonarray();\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public SomethingRecord value1(Integer value) {\n setSomeid(value);\n return this;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public SomethingRecord value2(String value) {\n setSomestring(value);\n return this;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public SomethingRecord value3(Long value) {\n setSomehugenumber(value);\n return this;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public SomethingRecord value4(Short value) {\n setSomesmallnumber(value);\n return this;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public SomethingRecord value5(Integer value) {\n setSomeregularnumber(value);\n return this;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public SomethingRecord value6(Double value) {\n setSomedouble(value);\n return this;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public SomethingRecord value7(String value) {\n setSomeenum(value);\n return this;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public SomethingRecord value8(JsonObject value) {\n setSomejsonobject(value);\n return this;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public SomethingRecord value9(JsonArray value) {\n setSomejsonarray(value);\n return this;\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public SomethingRecord values(Integer value1, String value2, Long value3, Short value4, Integer value5, Double value6, String value7, JsonObject value8, JsonArray value9) {\n value1(value1);\n value2(value2);\n value3(value3);\n value4(value4);\n value5(value5);\n value6(value6);\n value7(value7);\n value8(value8);\n value9(value9);\n return this;\n }\n\n // -------------------------------------------------------------------------\n // FROM and INTO\n // -------------------------------------------------------------------------\n\n /**\n * {@inheritDoc}\n */\n @Override\n public void from(ISomething from) {\n setSomeid(from.getSomeid());\n setSomestring(from.getSomestring());\n setSomehugenumber(from.getSomehugenumber());\n setSomesmallnumber(from.getSomesmallnumber());\n setSomeregularnumber(from.getSomeregularnumber());\n setSomedouble(from.getSomedouble());\n setSomeenum(from.getSomeenum());\n setSomejsonobject(from.getSomejsonobject());\n setSomejsonarray(from.getSomejsonarray());\n }\n\n /**\n * {@inheritDoc}\n */\n @Override\n public <E extends ISomething> E into(E into) {\n into.from(this);\n return into;\n }\n\n // -------------------------------------------------------------------------\n // Constructors\n // -------------------------------------------------------------------------\n\n /**\n * Create a detached SomethingRecord\n */\n public SomethingRecord() {\n super(Something.SOMETHING);\n }\n\n /**\n * Create a detached, initialised SomethingRecord\n */\n public SomethingRecord(Integer someid, String somestring, Long somehugenumber, Short somesmallnumber, Integer someregularnumber, Double somedouble, String someenum, JsonObject somejsonobject, JsonArray somejsonarray) {\n super(Something.SOMETHING);\n\n set(0, someid);\n set(1, somestring);\n set(2, somehugenumber);\n set(3, somesmallnumber);\n set(4, someregularnumber);\n set(5, somedouble);\n set(6, someenum);\n set(7, somejsonobject);\n set(8, somejsonarray);\n }\n}",
"public class JsonArrayConverter implements Converter<String,JsonArray> {\n\n private static JsonArrayConverter INSTANCE;\n public static JsonArrayConverter getInstance() {\n return INSTANCE == null ? INSTANCE = new JsonArrayConverter() : INSTANCE;\n }\n\n @Override\n public JsonArray from(String databaseObject) {\n return databaseObject==null?null:new JsonArray(databaseObject);\n }\n\n @Override\n public String to(JsonArray userObject) {\n return userObject==null?null:userObject.encode();\n }\n\n @Override\n public Class<String> fromType() {\n return String.class;\n }\n\n @Override\n public Class<JsonArray> toType() {\n return JsonArray.class;\n }\n}",
"public class JsonObjectConverter implements Converter<String,JsonObject> {\n\n private static JsonObjectConverter INSTANCE;\n public static JsonObjectConverter getInstance() {\n return INSTANCE == null ? INSTANCE = new JsonObjectConverter() : INSTANCE;\n }\n\n @Override\n public JsonObject from(String databaseObject) {\n return databaseObject==null?null:new JsonObject(databaseObject);\n }\n\n @Override\n public String to(JsonObject userObject) {\n return userObject==null?null:userObject.encode();\n }\n\n @Override\n public Class<String> fromType() {\n return String.class;\n }\n\n @Override\n public Class<JsonObject> toType() {\n return JsonObject.class;\n }\n}"
] | import generated.rx.async.vertx.DefaultSchema;
import generated.rx.async.vertx.Indexes;
import generated.rx.async.vertx.Keys;
import generated.rx.async.vertx.tables.records.SomethingRecord;
import io.github.jklingsporn.vertx.jooq.async.shared.JsonArrayConverter;
import io.github.jklingsporn.vertx.jooq.async.shared.JsonObjectConverter;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import java.util.Arrays;
import java.util.List;
import javax.annotation.Generated;
import org.jooq.Field;
import org.jooq.Identity;
import org.jooq.Index;
import org.jooq.Name;
import org.jooq.Schema;
import org.jooq.Table;
import org.jooq.TableField;
import org.jooq.UniqueKey;
import org.jooq.impl.DSL;
import org.jooq.impl.TableImpl; | /*
* This file is generated by jOOQ.
*/
package generated.rx.async.vertx.tables;
/**
* This class is generated by jOOQ.
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.10.1"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class Something extends TableImpl<SomethingRecord> {
private static final long serialVersionUID = 537755446;
/**
* The reference instance of <code>something</code>
*/
public static final Something SOMETHING = new Something();
/**
* The class holding records for this type
*/
@Override
public Class<SomethingRecord> getRecordType() {
return SomethingRecord.class;
}
/**
* The column <code>something.someId</code>.
*/
public final TableField<SomethingRecord, Integer> SOMEID = createField("someId", org.jooq.impl.SQLDataType.INTEGER.nullable(false).identity(true), this, "");
/**
* The column <code>something.someString</code>.
*/
public final TableField<SomethingRecord, String> SOMESTRING = createField("someString", org.jooq.impl.SQLDataType.VARCHAR(45), this, "");
/**
* The column <code>something.someHugeNumber</code>.
*/
public final TableField<SomethingRecord, Long> SOMEHUGENUMBER = createField("someHugeNumber", org.jooq.impl.SQLDataType.BIGINT, this, "");
/**
* The column <code>something.someSmallNumber</code>.
*/
public final TableField<SomethingRecord, Short> SOMESMALLNUMBER = createField("someSmallNumber", org.jooq.impl.SQLDataType.SMALLINT, this, "");
/**
* The column <code>something.someRegularNumber</code>.
*/
public final TableField<SomethingRecord, Integer> SOMEREGULARNUMBER = createField("someRegularNumber", org.jooq.impl.SQLDataType.INTEGER, this, "");
/**
* The column <code>something.someDouble</code>.
*/
public final TableField<SomethingRecord, Double> SOMEDOUBLE = createField("someDouble", org.jooq.impl.SQLDataType.DOUBLE, this, "");
/**
* The column <code>something.someEnum</code>.
*/
public final TableField<SomethingRecord, String> SOMEENUM = createField("someEnum", org.jooq.impl.SQLDataType.VARCHAR(3), this, "");
/**
* The column <code>something.someJsonObject</code>.
*/ | public final TableField<SomethingRecord, JsonObject> SOMEJSONOBJECT = createField("someJsonObject", org.jooq.impl.SQLDataType.VARCHAR(45), this, "", new JsonObjectConverter()); | 5 |
tim-savage/SavageDeathChest | src/main/java/com/winterhavenmc/deathchest/listeners/PlayerEventListener.java | [
"public final class PluginMain extends JavaPlugin {\n\n\tpublic MessageBuilder<MessageId, Macro> messageBuilder;\n\tpublic WorldManager worldManager;\n\tpublic SoundConfiguration soundConfig;\n\tpublic ChestManager chestManager;\n\tpublic CommandManager commandManager;\n\tpublic ProtectionPluginRegistry protectionPluginRegistry;\n\n\n\t@Override\n\tpublic void onEnable() {\n\n\t\t// bStats\n\t\tnew Metrics(this, 13916);\n\n\t\t// copy default config from jar if it doesn't exist\n\t\tsaveDefaultConfig();\n\n\t\t// initialize message builder\n\t\tmessageBuilder = new MessageBuilder<>(this);\n\n\t\t// instantiate sound configuration\n\t\tsoundConfig = new YamlSoundConfiguration(this);\n\n\t\t// instantiate world manager\n\t\tworldManager = new WorldManager(this);\n\n\t\t// instantiate chest manager\n\t\tchestManager = new ChestManager(this);\n\n\t\t// load all chests from datastore\n\t\tchestManager.loadChests();\n\n\t\t// instantiate command manager\n\t\tcommandManager = new CommandManager(this);\n\n\t\t// initialize event listeners\n\t\tnew PlayerEventListener(this);\n\t\tnew BlockEventListener(this);\n\t\tnew InventoryEventListener(this);\n\n\t\t// instantiate protection plugin registry\n\t\tprotectionPluginRegistry = new ProtectionPluginRegistry(this);\n\t}\n\n\n\t@Override\n\tpublic void onDisable() {\n\n\t\t// close datastore\n\t\tchestManager.closeDataStore();\n\t}\n\n}",
"@Immutable\npublic final class DeathChest {\n\n\t// reference to main class\n\tprivate final PluginMain plugin = JavaPlugin.getPlugin(PluginMain.class);\n\n\t// the UUID of this death chest\n\tprivate final UUID chestUId;\n\n\t// the UUID of the owner of this death chest\n\tprivate final UUID ownerUid;\n\n\t// the UUID of the player who killed the death chest owner, if any; otherwise null\n\tprivate final UUID killerUid;\n\n\t// item count; for future use\n\tprivate final int itemCount;\n\n\t// placementTime time of this death chest, in milliseconds since epoch\n\tprivate final long placementTime;\n\n\t// the expirationTime time of this death chest, in milliseconds since epoch\n\tprivate final long expirationTime;\n\n\t// the protectionExpirationTime time of this death chest, in milliseconds since epoch\n\tprivate final long protectionExpirationTime;\n\n\t// task id of expire task for this death chest block\n\tprivate final int expireTaskId;\n\n\t/**\n\t * Class constructor\n\t * This constructor is used to create a DeathChest object from an existing record read from the datastore.\n\t *\n\t * @param chestUId the chest UUID\n\t * @param ownerUid the chest owner UUID\n\t * @param killerUid the chest killer UUID\n\t * @param itemCount the chest item count\n\t * @param placementTime the chest placement time\n\t * @param protectionExpirationTime the chest protection expiration time\n\t * @param expirationTime the chest expiration time\n\t */\n\tpublic DeathChest(final UUID chestUId,\n\t\t\t\t\t final UUID ownerUid,\n\t\t\t\t\t final UUID killerUid,\n\t\t\t\t\t final int itemCount,\n\t\t\t\t\t final long placementTime,\n\t\t\t\t\t final long expirationTime,\n\t final long protectionExpirationTime) {\n\n\t\tthis.chestUId = chestUId;\n\t\tthis.ownerUid = ownerUid;\n\t\tthis.killerUid = killerUid;\n\t\tthis.itemCount = itemCount;\n\t\tthis.placementTime = placementTime;\n\t\tthis.expirationTime = expirationTime;\n\t\tthis.protectionExpirationTime = protectionExpirationTime;\n\t\tthis.expireTaskId = createExpireTask();\n\t}\n\n\n\t/**\n\t * Class constructor\n\t * This constructor is used to create a new DeathChest object on player death.\n\t *\n\t * @param player the death chest owner\n\t */\n\tpublic DeathChest(final Player player) {\n\n\t\t// create random chestUUID\n\t\tthis.chestUId = UUID.randomUUID();\n\n\t\t// set playerUUID\n\t\tif (player != null) {\n\t\t\tthis.ownerUid = player.getUniqueId();\n\t\t}\n\t\telse {\n\t\t\tthis.ownerUid = null;\n\t\t}\n\n\t\t// set killerUUID\n\t\tif (player != null && player.getKiller() != null) {\n\t\t\tthis.killerUid = player.getKiller().getUniqueId();\n\t\t}\n\t\telse {\n\t\t\tthis.killerUid = new UUID(0,0);\n\t\t}\n\n\t\t// set item count\n\t\tthis.itemCount = 0;\n\n\t\t// set placementTime timestamp\n\t\tthis.placementTime = System.currentTimeMillis();\n\n\t\t// set expirationTime timestamp\n\t\t// if configured expiration is zero, set expiration to negative to signify no expiration\n\t\tif (plugin.getConfig().getLong(\"expire-time\") <= 0) {\n\t\t\tthis.expirationTime = -1;\n\t\t}\n\t\telse {\n\t\t\t// set expiration field based on config setting (converting from minutes to milliseconds)\n\t\t\tthis.expirationTime = System.currentTimeMillis()\n\t\t\t\t\t+ TimeUnit.MINUTES.toMillis(plugin.getConfig().getLong(\"expire-time\"));\n\t\t}\n\n\t\t// set expireTaskId from new expire task\n\t\tthis.expireTaskId = createExpireTask();\n\n\t\t// set protectionExpirationTime timestamp\n\t\t// if configured protection expiration is zero, set protection expiration to negative to signify no expiration\n\t\tif (plugin.getConfig().getLong(\"chest-protection-time\") <= 0) {\n\t\t\tthis.protectionExpirationTime = expirationTime;\n\t\t}\n\t\telse {\n\t\t\t// set protection expiration field based on config setting (converting from minutes to milliseconds)\n\t\t\tthis.protectionExpirationTime = System.currentTimeMillis()\n\t\t\t\t\t+ TimeUnit.MINUTES.toMillis(plugin.getConfig().getLong(\"chest-protection-time\"));\n\t\t}\n\t}\n\n\n\t/**\n\t * Getter method for DeathChest chestUUID\n\t *\n\t * @return UUID\n\t */\n\tpublic UUID getChestUid() {\n\t\treturn chestUId;\n\t}\n\n\n\t/**\n\t * Getter method for DeathChest ownerUUID\n\t *\n\t * @return UUID\n\t */\n\tpublic UUID getOwnerUid() {\n\t\treturn ownerUid;\n\t}\n\n\n\t/**\n\t * Getter method for DeathChest killerUUID\n\t *\n\t * @return UUID\n\t */\n\tpublic UUID getKillerUid() {\n\t\treturn killerUid;\n\t}\n\n\n\t/**\n\t * Get owner name for DeathChest by looking up offline player by uuid\n\t *\n\t * @return String - chest owner name\n\t */\n\tpublic String getOwnerName() {\n\t\tString returnName = \"???\";\n\t\tif (ownerUid != null && plugin.getServer().getOfflinePlayer(ownerUid).getName() != null) {\n\t\t\treturnName = plugin.getServer().getOfflinePlayer(ownerUid).getName();\n\t\t}\n\t\treturn returnName;\n\t}\n\n\n\t/**\n\t * Get owner name for DeathChest by looking up offline player by uuid\n\t *\n\t * @return String - chest owner name\n\t */\n\tpublic String getKillerName() {\n\t\tString returnName = \"???\";\n\t\tif (killerUid != null && plugin.getServer().getOfflinePlayer(killerUid).getName() != null) {\n\t\t\treturnName = plugin.getServer().getOfflinePlayer(killerUid).getName();\n\t\t}\n\t\treturn returnName;\n\t}\n\n\n\t/**\n\t * Getter method for DeathChest itemCount\n\t *\n\t * @return integer - itemCount\n\t */\n\t@SuppressWarnings(\"unused\")\n\tpublic int getItemCount() {\n\t\treturn itemCount;\n\t}\n\n\n\t/**\n\t * Getter method for DeathChest placementTime timestamp\n\t *\n\t * @return long placementTime timestamp\n\t */\n\tpublic long getPlacementTime() {\n\t\treturn this.placementTime;\n\t}\n\n\n\t/**\n\t * Getter method for DeathChest expirationTime timestamp\n\t *\n\t * @return long expirationTime timestamp\n\t */\n\tpublic long getExpirationTime() {\n\t\treturn this.expirationTime;\n\t}\n\n\n\t/**\n\t * Getter method for DeathChest protectionExpirationTime timestamp\n\t *\n\t * @return long expirationTime timestamp\n\t */\n\tpublic long getProtectionTime() {\n\t\treturn this.protectionExpirationTime;\n\t}\n\n\n\t/**\n\t * Getter method for DeathChest expireTaskId\n\t *\n\t * @return the value of the expireTaskId field in the DeathChest object\n\t */\n\tprivate int getExpireTaskId() {\n\t\treturn this.expireTaskId;\n\t}\n\n\n\t/**\n\t * Get chest location. Attempt to get chest location from right chest, left chest or sign in that order.\n\t * Returns null if location could not be derived from chest blocks.\n\t *\n\t * @return Location - the chest location or null if no location found\n\t */\n\tpublic Location getLocation() {\n\n\t\tMap<ChestBlockType, ChestBlock> chestBlockMap = plugin.chestManager.getBlockMap(this.chestUId);\n\n\t\tif (chestBlockMap.containsKey(ChestBlockType.RIGHT_CHEST)) {\n\t\t\treturn chestBlockMap.get(ChestBlockType.RIGHT_CHEST).getLocation();\n\t\t}\n\t\telse if (chestBlockMap.containsKey(ChestBlockType.LEFT_CHEST)) {\n\t\t\treturn chestBlockMap.get(ChestBlockType.LEFT_CHEST).getLocation();\n\t\t}\n\t\telse if (chestBlockMap.containsKey(ChestBlockType.SIGN)) {\n\t\t\treturn chestBlockMap.get(ChestBlockType.SIGN).getLocation();\n\t\t}\n\n\t\treturn null;\n\t}\n\n\n\t/**\n\t * Set chest metadata on all component blocks\n\t */\n\tvoid setMetadata() {\n\n\t\t// set metadata on blocks in set\n\t\tfor (ChestBlock chestBlock : plugin.chestManager.getBlocks(this.chestUId)) {\n\t\t\tchestBlock.setMetadata(this);\n\t\t\tif (plugin.getConfig().getBoolean(\"debug\")) {\n\t\t\t\tplugin.getLogger().info(\"Metadata set on chest block \" + this.chestUId);\n\t\t\t}\n\t\t}\n\t}\n\n\n\t/**\n\t * Test if a player is the owner of this DeathChest\n\t *\n\t * @param player The player to test for DeathChest ownership\n\t * @return {@code true} if the player is the DeathChest owner, false if not\n\t */\n\tpublic boolean isOwner(final Player player) {\n\n\t\t// if ownerUUID is null, return false\n\t\tif (this.getOwnerUid() == null) {\n\t\t\treturn false;\n\t\t}\n\t\treturn this.getOwnerUid().equals(player.getUniqueId());\n\t}\n\n\n\t/**\n\t * Test if a player is the killer of this DeathChest owner\n\t *\n\t * @param player The player to test for DeathChest killer\n\t * @return {@code true} if the player is the killer of the DeathChest owner, false if not\n\t */\n\tpublic boolean isKiller(final Player player) {\n\t\treturn this.hasValidKillerUid() && this.getKillerUid().equals(player.getUniqueId());\n\t}\n\n\n\t/**\n\t * Transfer all chest contents to player inventory and remove in-game chest if empty.\n\t * Items that do not fit in player inventory will be retained in chest.\n\t *\n\t * @param player the player whose inventory the chest contents will be transferred\n\t */\n\tpublic void autoLoot(final Player player) {\n\n\t\t// if passed player is null, do nothing and return\n\t\tif (player == null) {\n\t\t\treturn;\n\t\t}\n\n\t\t// create collection to hold items that did not fit in player inventory\n\t\tCollection<ItemStack> remainingItems = new LinkedList<>();\n\n\t\t// transfer contents of any chest blocks to player, putting any items that did not fit in remainingItems\n\t\tfor (ChestBlock chestBlock : plugin.chestManager.getBlocks(this.chestUId)) {\n\t\t\tremainingItems.addAll(chestBlock.transferContents(player));\n\t\t}\n\n\t\t// if remainingItems is empty, all chest items fit in player inventory so destroy chest and return\n\t\tif (remainingItems.isEmpty()) {\n\t\t\tthis.destroy();\n\t\t\treturn;\n\t\t}\n\n\t\t// send player message\n\t\tplugin.messageBuilder.build(player, MessageId.INVENTORY_FULL)\n\t\t\t\t.setMacro(Macro.LOCATION, player.getLocation())\n\t\t\t\t.send();\n\n\t\t// try to put remaining items back in chest\n\t\tremainingItems = this.fill(remainingItems);\n\n\t\t// if remainingItems is still not empty, items could not be placed back in chest, so drop items at player location\n\t\t// this should never actually occur, but let's play it safe just in case\n\t\tif (!remainingItems.isEmpty()) {\n\t\t\tfor (ItemStack itemStack : remainingItems) {\n\t\t\t\tplayer.getWorld().dropItem(player.getLocation(), itemStack);\n\t\t\t}\n\t\t}\n\t}\n\n\n\t/**\n\t * Expire this death chest, destroying in game chest and dropping contents,\n\t * and sending message to chest owner if online.\n\t */\n\tpublic void expire() {\n\n\t\t// get player from ownerUUID\n\t\tfinal Player player = plugin.getServer().getPlayer(this.ownerUid);\n\n\t\t// destroy DeathChest\n\t\tthis.destroy();\n\n\t\t// if player is not null, send player message\n\t\tif (player != null) {\n\t\t\tplugin.messageBuilder.build(player, MessageId.CHEST_EXPIRED)\n\t\t\t\t\t.setMacro(Macro.LOCATION, this.getLocation())\n\t\t\t\t\t.send();\n\t\t}\n\t}\n\n\tpublic void dropContents() {\n\n\t\tif (this.getLocation() !=null && this.getLocation().getWorld() != null) {\n\n\t\t\tItemStack[] contents = this.getInventory().getStorageContents();\n\n\t\t\tthis.getInventory().clear();\n\n\t\t\tfor (ItemStack stack : contents) {\n\t\t\t\tif (stack !=null) {\n\t\t\t\t\tthis.getLocation().getWorld().dropItemNaturally(this.getLocation(), stack);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Destroy this death chest, dropping chest contents\n\t */\n\tpublic void destroy() {\n\n\t\tdropContents();\n\n\t\t// play chest break sound at chest location\n\t\tplugin.soundConfig.playSound(this.getLocation(), SoundId.CHEST_BREAK);\n\n\t\t// get block map for this chest\n\t\tMap<ChestBlockType, ChestBlock> chestBlockMap = plugin.chestManager.getBlockMap(this.chestUId);\n\n\t\t// destroy DeathChest blocks (sign gets destroyed first due to enum order, preventing detach before being destroyed)\n\t\tfor (ChestBlock chestBlock : chestBlockMap.values()) {\n\t\t\tchestBlock.destroy();\n\t\t}\n\n\t\t// delete DeathChest record from datastore\n\t\tplugin.chestManager.deleteChestRecord(this);\n\n\t\t// cancel expire block task\n\t\tif (this.getExpireTaskId() > 0) {\n\t\t\tplugin.getServer().getScheduler().cancelTask(this.getExpireTaskId());\n\t\t}\n\n\t\t// remove DeathChest from ChestManager DeathChest map\n\t\tplugin.chestManager.removeChest(this);\n\t}\n\n\n\t/**\n\t * Get inventory associated with this death chest\n\t *\n\t * @return Inventory - the inventory associated with this death chest;\n\t * returns null if both right and left chest block inventories are invalid\n\t */\n\tpublic Inventory getInventory() {\n\n\t\t// get chest block map\n\t\tMap<ChestBlockType, ChestBlock> chestBlocks = plugin.chestManager.getBlockMap(this.chestUId);\n\n\t\t// get right chest inventory\n\t\tInventory inventory = chestBlocks.get(ChestBlockType.RIGHT_CHEST).getInventory();\n\n\t\t// if right chest inventory is null, try left chest\n\t\tif (inventory == null) {\n\t\t\tinventory = chestBlocks.get(ChestBlockType.LEFT_CHEST).getInventory();\n\t\t}\n\n\t\t// return the inventory, or null if right and left chest inventories were both invalid\n\t\treturn inventory;\n\t}\n\n\n\t/**\n\t * Get the number of players currently viewing a DeathChest inventory\n\t *\n\t * @return The number of inventory viewers\n\t */\n\tpublic int getViewerCount() {\n\n\t\t// get chest inventory\n\t\tInventory inventory = this.getInventory();\n\n\t\t// if inventory is not null, return viewer count\n\t\tif (inventory != null) {\n\t\t\treturn inventory.getViewers().size();\n\t\t}\n\t\telse {\n\t\t\t// inventory is null, so return 0 for viewer count\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\n\t/**\n\t * Create expire chest task\n\t */\n\tprivate int createExpireTask() {\n\n\t\t// if DeathChestBlock expirationTime is zero or less, it is set to never expire\n\t\tif (this.getExpirationTime() < 1) {\n\t\t\treturn -1;\n\t\t}\n\n\t\t// get current time\n\t\tlong currentTime = System.currentTimeMillis();\n\n\t\t// compute ticks remaining until expire time (millisecond interval divided by 50 yields ticks)\n\t\tlong ticksRemaining = (this.expirationTime - currentTime) / 50;\n\t\tif (ticksRemaining < 1) {\n\t\t\tticksRemaining = 1L;\n\t\t}\n\n\t\t// create task to expire death chest after ticksRemaining\n\t\tBukkitTask chestExpireTask = new ExpireChestTask(this).runTaskLater(plugin, ticksRemaining);\n\n\t\t// return taskId\n\t\treturn chestExpireTask.getTaskId();\n\t}\n\n\n\t/**\n\t * Cancel expire task for this death chest\n\t */\n\tvoid cancelExpireTask() {\n\n\t\t// if task id is positive integer, cancel task\n\t\tif (this.expireTaskId > 0) {\n\t\t\tplugin.getServer().getScheduler().cancelTask(this.expireTaskId);\n\t\t}\n\t}\n\n\n\t/**\n\t * Place collection of ItemStacks in chest, returning collection of ItemStacks that did not fit in chest\n\t *\n\t * @param itemStacks Collection of ItemStacks to place in chest\n\t * @return Collection of ItemStacks that did not fit in chest\n\t */\n\tCollection<ItemStack> fill(final Collection<ItemStack> itemStacks) {\n\n\t\t// create empty list for return\n\t\tCollection<ItemStack> remainingItems = new LinkedList<>();\n\n\t\t// get inventory for this death chest\n\t\tInventory inventory = this.getInventory();\n\n\t\t// if inventory is not null, add itemStacks to inventory and put leftovers in remainingItems\n\t\tif (inventory != null) {\n\t\t\tremainingItems = new LinkedList<>(inventory.addItem(itemStacks.toArray(new ItemStack[0])).values());\n\t\t}\n\n\t\t// return collection of items that did not fit in inventory\n\t\treturn remainingItems;\n\t}\n\n\n\t/**\n\t * Check if protection is enabled and has expired\n\t * @return boolean - true if protection has expired, false if not\n\t */\n\tpublic boolean protectionExpired() {\n\t\treturn this.getProtectionTime() > 0 &&\n\t\t\t\tthis.getProtectionTime() < System.currentTimeMillis();\n\t}\n\n\n\tpublic boolean hasValidOwnerUid() {\n\t\treturn this.ownerUid != null &&\n\t\t\t\t(this.ownerUid.getMostSignificantBits() != 0 && this.ownerUid.getLeastSignificantBits() != 0);\n\t}\n\n\n\tpublic boolean hasValidKillerUid() {\n\t\treturn this.killerUid != null &&\n\t\t\t\t(this.killerUid.getMostSignificantBits() != 0 && this.killerUid.getLeastSignificantBits() != 0);\n\t}\n\n\n}",
"public final class Deployment {\n\n\t// reference to main class\n\tprivate final PluginMain plugin;\n\n\t// death chest object\n\tprivate final DeathChest deathChest;\n\n\t// set of path block type names as strings\n\tprivate static final Collection<String> pathBlockTypeNames = Set.of(\n\t\t\t\"GRASS_PATH\",\n\t\t\t\"LEGACY_GRASS_PATH\",\n\t\t\t\"DIRT_PATH\"\t);\n\n\n\t/**\n\t * Class constructor for DeathChest deployment\n\t *\n\t * @param plugin reference to plugin main class instance\n\t * @param player the player for whom to deploy a death chest\n\t * @param droppedItems list of items dropped by player on death\n\t */\n\tpublic Deployment(final PluginMain plugin, final Player player, final Collection<ItemStack> droppedItems) {\n\n\t\t// set reference to main class\n\t\tthis.plugin = plugin;\n\n\t\t// create new deathChest object for player\n\t\tthis.deathChest = new DeathChest(player);\n\n\t\t// deploy chest\n\t\tSearchResult result = deployChest(player, droppedItems);\n\n\t\t// if debugging, log result\n\t\tif (plugin.getConfig().getBoolean(\"debug\")) {\n\t\t\tlogResult(result);\n\t\t}\n\n\t\t// get configured expire-time\n\t\tlong expireTime = plugin.getConfig().getLong(\"expire-time\");\n\n\t\t// if configured expire-time is zero, set to negative to display infinite time in messages\n\t\tif (expireTime == 0) {\n\t\t\texpireTime = -1;\n\t\t}\n\n\t\t// send message based on result\n\t\tsendResultMessage(player, result, expireTime);\n\n\t\t// drop any remaining items that were not placed in a chest\n\t\tfor (ItemStack item : result.getRemainingItems()) {\n\t\t\tplayer.getWorld().dropItemNaturally(player.getLocation(), item);\n\t\t}\n\n\t\t// if result is negative cancel expire task and return\n\t\tif (!result.getResultCode().equals(SearchResultCode.SUCCESS)\n\t\t\t\t&& !result.getResultCode().equals(SearchResultCode.PARTIAL_SUCCESS)) {\n\n\t\t\t// cancel DeathChest expire task\n\t\t\tdeathChest.cancelExpireTask();\n\t\t\treturn;\n\t\t}\n\n\t\t// get configured chest protection time\n\t\tlong chestProtectionTime = plugin.getConfig().getLong(\"chest-protection-time\");\n\n\t\t// protection time is zero, set to negative to display infinite time in message\n\t\tif (chestProtectionTime == 0) {\n\t\t\tchestProtectionTime = -1;\n\t\t}\n\n\t\t// if chest protection is enabled and chest-protection-time is set (non-zero), send message\n\t\tif (plugin.getConfig().getBoolean(\"chest-protection\") && chestProtectionTime > 0) {\n\t\t\tplugin.messageBuilder.build(player, MessageId.CHEST_DEPLOYED_PROTECTION_TIME)\n\t\t\t\t\t.setMacro(Macro.OWNER, player.getName())\n\t\t\t\t\t.setMacro(Macro.LOCATION, deathChest.getLocation())\n\t\t\t\t\t.setMacro(Macro.PROTECTION_DURATION, TimeUnit.MINUTES.toMillis(chestProtectionTime))\n\t\t\t\t\t.setMacro(Macro.PROTECTION_DURATION_MINUTES, TimeUnit.MINUTES.toMillis(chestProtectionTime))\n\t\t\t\t\t.send();\n\t\t}\n\n\t\t// put DeathChest in DeathChest map\n\t\tplugin.chestManager.putChest(deathChest);\n\n\t\t// put DeathChest in datastore\n\t\tSet<DeathChest> deathChests = new HashSet<>();\n\t\tdeathChests.add(deathChest);\n\t\tplugin.chestManager.insertChestRecords(deathChests);\n\t}\n\n\n\t/**\n\t * Deploy a DeathChest for player and fill with dropped items on player death\n\t *\n\t * @param player the player who died\n\t * @param droppedItems the player's items dropped on death\n\t * @return SearchResult - the result of the attempted DeathChest deployment\n\t */\n\tprivate SearchResult deployChest(final Player player, final Collection<ItemStack> droppedItems) {\n\n\t\t// combine stacks of same items where possible\n\t\tCollection<ItemStack> remainingItems = consolidateItemStacks(droppedItems);\n\n\t\t// get required chest size\n\t\tChestSize chestSize = ChestSize.selectFor(remainingItems.size());\n\n\t\t// deploy appropriately sized chest\n\t\tif (chestSize.equals(ChestSize.SINGLE)\n\t\t\t\t|| !player.hasPermission(\"deathchest.doublechest\")) {\n\t\t\treturn deploySingleChest(player, remainingItems);\n\t\t}\n\t\telse {\n\t\t\treturn deployDoubleChest(player, remainingItems);\n\t\t}\n\t}\n\n\n\t/**\n\t * Deploy a single chest for player and fill with dropped items on player death\n\t *\n\t * @param player the player who died\n\t * @param droppedItems Collection of the player's items dropped on death\n\t * @return SearchResult - the result of the attempted DeathChest deployment\n\t */\n\tprivate SearchResult deploySingleChest(final Player player, final Collection<ItemStack> droppedItems) {\n\n\t\t// make copy of dropped items\n\t\tCollection<ItemStack> remainingItems = new LinkedList<>(droppedItems);\n\n\t\t// if require-chest option is enabled and player does not have permission override\n\t\tif (plugin.getConfig().getBoolean(\"require-chest\")\n\t\t\t\t&& !player.hasPermission(\"deathchest.freechest\")) {\n\n\t\t\t// check that player has chest in inventory\n\t\t\tif (containsChest(remainingItems)) {\n\n\t\t\t\t// if consume-required-chest configured true: remove one chest from remaining items\n\t\t\t\tif (plugin.getConfig().getBoolean(\"consume-required-chest\")) {\n\t\t\t\t\tremainingItems = removeOneChest(remainingItems);\n\t\t\t\t}\n\t\t\t}\n\t\t\t// else return NO_CHEST result\n\t\t\telse {\n\t\t\t\treturn new SearchResult(SearchResultCode.NO_CHEST, remainingItems);\n\t\t\t}\n\t\t}\n\n\t\t// search for valid chest location\n\t\tSearch search = new QuadrantSearch(plugin, player, ChestSize.SINGLE);\n\t\tsearch.execute();\n\t\tSearchResult result = search.getSearchResult();\n\n\t\t// if search successful, place chest\n\t\tif (result.getResultCode().equals(SearchResultCode.SUCCESS)) {\n\n\t\t\t// place chest at result location\n\t\t\tplaceChest(player, result.getLocation(), ChestBlockType.RIGHT_CHEST);\n\n\t\t\t// get chest block state\n\t\t\tBlockState chestBlockState = result.getLocation().getBlock().getState();\n\n\t\t\t// get chest block data\n\t\t\tChest chestBlockData = (Chest) chestBlockState.getBlockData();\n\n\t\t\t// set chest block data type to single chest\n\t\t\tchestBlockData.setType(Chest.Type.SINGLE);\n\n\t\t\t// set chest block data\n\t\t\tchestBlockState.setBlockData(chestBlockData);\n\n\t\t\t// update chest block state\n\t\t\tchestBlockState.update();\n\n\t\t\t// fill chest\n\t\t\tremainingItems = deathChest.fill(remainingItems);\n\n\t\t\t// place sign on chest\n\t\t\tplaceSign(player, result.getLocation().getBlock());\n\t\t}\n\n\t\t// set remaining items in result\n\t\tresult.setRemainingItems(remainingItems);\n\n\t\t// return result\n\t\treturn result;\n\t}\n\n\n\t/**\n\t * Deploy a double chest for player and fill with dropped items on player death\n\t *\n\t * @param player the player who died\n\t * @param droppedItems the player's items dropped on death\n\t * @return SearchResult - the result of the attempted DeathChest deployment\n\t */\n\tprivate SearchResult deployDoubleChest(final Player player, final Collection<ItemStack> droppedItems) {\n\n\t\t// make copy of dropped items\n\t\tCollection<ItemStack> remainingItems = new LinkedList<>(droppedItems);\n\n\t\t// search for valid chest location\n\t\tSearch search = new QuadrantSearch(plugin, player, ChestSize.DOUBLE);\n\t\tsearch.execute();\n\t\tSearchResult searchResult = search.getSearchResult();\n\n\t\t// if only single chest location found, deploy single chest\n\t\tif (searchResult.getResultCode().equals(SearchResultCode.PARTIAL_SUCCESS)) {\n\t\t\tsearchResult = deploySingleChest(player, remainingItems);\n\n\t\t\t// if single chest deployment was successful, set PARTIAL_SUCCESS result\n\t\t\tif (searchResult.getResultCode().equals(SearchResultCode.SUCCESS)) {\n\t\t\t\tsearchResult.setResultCode(SearchResultCode.PARTIAL_SUCCESS);\n\t\t\t}\n\n\t\t\t// return result\n\t\t\treturn searchResult;\n\t\t}\n\n\t\t// if search failed, return result with remaining items\n\t\tif (!searchResult.getResultCode().equals(SearchResultCode.SUCCESS)) {\n\t\t\tsearchResult.setRemainingItems(remainingItems);\n\t\t\treturn searchResult;\n\t\t}\n\n\t\t// if require-chest option is enabled\n\t\t// and player does not have permission override\n\t\tif (plugin.getConfig().getBoolean(\"require-chest\")\n\t\t\t\t&& !player.hasPermission(\"deathchest.freechest\")) {\n\n\t\t\t// check that player has chest in inventory\n\t\t\tif (containsChest(remainingItems)) {\n\n\t\t\t\t// if consume-required-chest configured true: remove one chest from remaining items\n\t\t\t\tif (plugin.getConfig().getBoolean(\"consume-required-chest\")) {\n\t\t\t\t\tremainingItems = removeOneChest(remainingItems);\n\t\t\t\t}\n\t\t\t}\n\t\t\t// else return NO_CHEST result\n\t\t\telse {\n\t\t\t\tsearchResult.setResultCode(SearchResultCode.NO_CHEST);\n\t\t\t\tsearchResult.setRemainingItems(remainingItems);\n\t\t\t\treturn searchResult;\n\t\t\t}\n\t\t}\n\n\t\t// place chest at result location\n\t\tplaceChest(player, searchResult.getLocation(), ChestBlockType.RIGHT_CHEST);\n\n\t\t// place sign on chest\n\t\tplaceSign(player, searchResult.getLocation().getBlock());\n\n\t\t// attempt to place second chest\n\n\t\t// if require-chest option is enabled\n\t\t// and player does not have permission override\n\t\tif (plugin.getConfig().getBoolean(\"require-chest\")\n\t\t\t\t&& !player.hasPermission(\"deathchest.freechest\")) {\n\n\t\t\t// check that player has chest in inventory\n\t\t\tif (containsChest(remainingItems)) {\n\t\t\t\t// if consume-required-chest configured true: remove one chest from remaining items\n\t\t\t\tif (plugin.getConfig().getBoolean(\"consume-required-chest\")) {\n\t\t\t\t\tremainingItems = removeOneChest(remainingItems);\n\t\t\t\t}\n\t\t\t}\n\t\t\t// else return new PARTIAL_SUCCESS result with location and remaining items after filling chest\n\t\t\telse {\n\t\t\t\tsearchResult.setResultCode(SearchResultCode.PARTIAL_SUCCESS);\n\t\t\t\tsearchResult.setRemainingItems(deathChest.fill(remainingItems));\n\t\t\t\treturn searchResult;\n\t\t\t}\n\t\t}\n\n\t\t// place chest at result location\n\t\tplaceChest(player, LocationUtilities.getLocationToRight(searchResult.getLocation()), ChestBlockType.LEFT_CHEST);\n\n\t\t// set chest type to left/right for double chest\n\n\t\t// get left and right chest block state\n\t\tBlockState rightChestState = searchResult.getLocation().getBlock().getState();\n\t\tBlockState leftChestState = LocationUtilities.getLocationToRight(searchResult.getLocation()).getBlock().getState();\n\n\t\t// get left and right chest block data\n\t\tChest rightChestBlockData = (Chest) rightChestState.getBlockData();\n\t\tChest leftChestBlockData = (Chest) leftChestState.getBlockData();\n\n\t\t// set left and right chest types in block data\n\t\trightChestBlockData.setType(Chest.Type.RIGHT);\n\t\tleftChestBlockData.setType(Chest.Type.LEFT);\n\n\t\t// set left and right block data\n\t\trightChestState.setBlockData(rightChestBlockData);\n\t\tleftChestState.setBlockData(leftChestBlockData);\n\n\t\t// update left and right chest block data\n\t\trightChestState.update();\n\t\tleftChestState.update();\n\n\t\t// put remaining items after filling chest in result\n\t\tsearchResult.setRemainingItems(deathChest.fill(remainingItems));\n\n\t\t// return result\n\t\treturn searchResult;\n\t}\n\n\n\t/**\n\t * Combine ItemStacks of same material up to max stack size\n\t *\n\t * @param itemStacks Collection of ItemStacks to combine\n\t * @return Collection of ItemStack with same materials combined\n\t */\n\tprivate Collection<ItemStack> consolidateItemStacks(final Collection<ItemStack> itemStacks) {\n\n\t\tfinal Collection<ItemStack> returnList = new LinkedList<>();\n\n\t\tfor (ItemStack itemStack : itemStacks) {\n\t\t\tif (itemStack == null) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tfor (ItemStack checkStack : returnList) {\n\t\t\t\tif (checkStack == null) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (checkStack.isSimilar(itemStack)) {\n\t\t\t\t\tint transferAmount =\n\t\t\t\t\t\t\tMath.min(itemStack.getAmount(), checkStack.getMaxStackSize() - checkStack.getAmount());\n\t\t\t\t\titemStack.setAmount(itemStack.getAmount() - transferAmount);\n\t\t\t\t\tcheckStack.setAmount(checkStack.getAmount() + transferAmount);\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (itemStack.getAmount() > 0) {\n\t\t\t\treturnList.add(itemStack);\n\t\t\t}\n\t\t}\n\t\treturn returnList;\n\t}\n\n\n\t/**\n\t * Check if Collection of ItemStack contains at least one chest\n\t *\n\t * @param itemStacks Collection of ItemStack to check for chest\n\t * @return boolean - {@code true} if collection contains at least one chest, {@code false} if not\n\t */\n\tprivate boolean containsChest(final Collection<ItemStack> itemStacks) {\n\n\t\t// check for null parameter\n\t\tif (itemStacks == null) {\n\t\t\treturn false;\n\t\t}\n\n\t\tboolean result = false;\n\t\tfor (ItemStack itemStack : itemStacks) {\n\t\t\tif (itemStack.getType().equals(Material.CHEST)) {\n\t\t\t\tresult = true;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\n\t/**\n\t * Remove one chest from list of item stacks. If a stack contains only one chest, remove the stack from\n\t * the list and return. If a stack contains more than one chest, decrease the stack amount by one and return.\n\t *\n\t * @param itemStacks List of ItemStack to remove chest\n\t * @return Collection of ItemStacks with one chest item removed. If passed collection contained no chest items,\n\t * the returned collection will be a copy of the passed collection.\n\t */\n\tprivate Collection<ItemStack> removeOneChest(final Collection<ItemStack> itemStacks) {\n\n\t\tCollection<ItemStack> remainingItems = new LinkedList<>(itemStacks);\n\n\t\tIterator<ItemStack> iterator = remainingItems.iterator();\n\n\t\twhile (iterator.hasNext()) {\n\n\t\t\tItemStack itemStack = iterator.next();\n\n\t\t\tif (itemStack.getType().equals(Material.CHEST) && !itemStack.hasItemMeta()) {\n\t\t\t\tif (itemStack.getAmount() == 1) {\n\t\t\t\t\titerator.remove();\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\titemStack.setAmount(itemStack.getAmount() - 1);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn remainingItems;\n\t}\n\n\n\t/**\n\t * Place a chest block and fill with items\n\t *\n\t * @param location the location to place the chest block\n\t * @param chestBlockType the type of chest block (left or right)\n\t */\n\tprivate void placeChest(final Player player, final Location location, final ChestBlockType chestBlockType) {\n\n\t\t// get current block at location\n\t\tBlock block = location.getBlock();\n\n\t\t// set block material to chest\n\t\tblock.setType(Material.CHEST);\n\n\t\t// set custom inventory name\n\t\tsetCustomInventoryName(player, block);\n\n\t\t// set chest direction\n\t\tsetChestDirection(block, location);\n\n\t\t// create new ChestBlock object\n\t\tChestBlock chestBlock = new ChestBlock(deathChest.getChestUid(), block.getLocation());\n\n\t\t// add this ChestBlock to block map\n\t\tplugin.chestManager.putBlock(chestBlockType, chestBlock);\n\n\t\t// set block metadata\n\t\tchestBlock.setMetadata(deathChest);\n\t}\n\n\n\t/**\n\t * Set custom inventory name for chest\n\t * @param player the owner of the chest\n\t * @param block the chest block\n\t */\n\tprivate void setCustomInventoryName(final Player player, final Block block) {\n\n\t\t// get custom inventory name from language file\n\t\tString customInventoryName = plugin.messageBuilder.getString(\"CHEST_INFO.INVENTORY_NAME\");\n\n\t\t// if custom inventory name is not blank, do substitutions for player name\n\t\tif (!customInventoryName.isEmpty()) {\n\t\t\tcustomInventoryName = customInventoryName.replace(\"%PLAYER%\", player.getDisplayName());\n\t\t\tcustomInventoryName = customInventoryName.replace(\"%OWNER%\", player.getDisplayName());\n\t\t}\n\t\telse {\n\t\t\t// set default custom inventory name\n\t\t\tcustomInventoryName = \"Death Chest\";\n\t\t}\n\n\t\t// set custom inventory name in chest metadata\n\t\torg.bukkit.block.Chest chestState = (org.bukkit.block.Chest) block.getState();\n\t\tchestState.setCustomName(customInventoryName);\n\t\tchestState.update();\n\t}\n\n\n\t/**\n\t * Set chest facing direction from player death location\n\t * @param block the chest block\n\t * @param location the player death location\n\t */\n\tprivate void setChestDirection(final Block block, final Location location) {\n\t\t// get block direction data\n\t\tDirectional blockData = (Directional) block.getBlockData();\n\n\t\t// set new direction from player death location\n\t\tblockData.setFacing(LocationUtilities.getCardinalDirection(location));\n\n\t\t// set block data\n\t\tblock.setBlockData(blockData);\n\t}\n\n\n\t/**\n\t * Place sign on chest\n\t *\n\t * @param player Chest owner\n\t * @param chestBlock Chest block\n\t * @return boolean - Success or failure to place sign\n\t */\n\t@SuppressWarnings(\"UnusedReturnValue\")\n\tprivate boolean placeSign(final Player player, final Block chestBlock) {\n\n\t\t// if chest-signs are not enabled in configuration, do nothing and return\n\t\tif (!plugin.getConfig().getBoolean(\"chest-signs\")) {\n\t\t\treturn false;\n\t\t}\n\n\t\t// try placing sign on chest, catching any exception thrown\n\t\ttry {\n\t\t\t// get block adjacent to chest facing player direction\n\t\t\tBlock signBlock = chestBlock.getRelative(LocationUtilities.getCardinalDirection(player));\n\n\t\t\t// if chest face is valid location, create wall sign\n\t\t\tif (isValidSignLocation(signBlock.getLocation())) {\n\n\t\t\t\tsignBlock.setType(Material.OAK_WALL_SIGN);\n\n\t\t\t\tBlockState blockState = signBlock.getState();\n\t\t\t\torg.bukkit.block.data.type.WallSign signBlockDataType = (org.bukkit.block.data.type.WallSign) blockState.getBlockData();\n\t\t\t\tsignBlockDataType.setFacing(LocationUtilities.getCardinalDirection(player));\n\t\t\t\tblockState.setBlockData(signBlockDataType);\n\t\t\t\tblockState.update();\n\t\t\t}\n\t\t\telse {\n\t\t\t\t// create sign post on top of chest if chest face was invalid location\n\t\t\t\tsignBlock = chestBlock.getRelative(BlockFace.UP);\n\t\t\t\tif (isValidSignLocation(signBlock.getLocation())) {\n\n\t\t\t\t\tsignBlock.setType(Material.OAK_SIGN);\n\n\t\t\t\t\tBlockState blockState = signBlock.getState();\n\t\t\t\t\torg.bukkit.block.data.type.Sign signBlockDataType = (org.bukkit.block.data.type.Sign) blockState.getBlockData();\n\t\t\t\t\tsignBlockDataType.setRotation(LocationUtilities.getCardinalDirection(player));\n\t\t\t\t\tblockState.setBlockData(signBlockDataType);\n\t\t\t\t\tblockState.update();\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// if top of chest is also an invalid location, do nothing and return\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// get block state of sign block\n\t\t\tBlockState signBlockState = signBlock.getState();\n\n\t\t\t// if block has not been successfully transformed into a sign, return false\n\t\t\tif (!(signBlockState instanceof org.bukkit.block.Sign)) {\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\t// Place text on sign with player name and death date\n\t\t\t// cast signBlockState to org.bukkit.block.Sign type object\n\t\t\torg.bukkit.block.Sign sign = (org.bukkit.block.Sign) signBlockState;\n\n\t\t\t// get configured date format from config file\n\t\t\tString dateFormat = plugin.getConfig().getString(\"DATE_FORMAT\");\n\n\t\t\t// if configured date format is null or empty, use default format\n\t\t\tif (dateFormat == null || dateFormat.isEmpty()) {\n\t\t\t\tdateFormat = \"MMM d, yyyy\";\n\t\t\t}\n\n\t\t\t// create formatted date string from current time\n\t\t\tString dateString = new SimpleDateFormat(dateFormat).format(System.currentTimeMillis());\n\n\t\t\t// get sign text from config file\n\t\t\tList<String> lines = plugin.getConfig().getStringList(\"SIGN_TEXT\");\n\n\t\t\tint lineCount = 0;\n\t\t\tfor (String line : lines) {\n\n\t\t\t\t// stop after four lines (zero indexed)\n\t\t\t\tif (lineCount > 3) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\t// do string replacements\n\t\t\t\tline = line.replace(\"%PLAYER%\", player.getName());\n\t\t\t\tline = line.replace(\"%DATE%\", dateString);\n\t\t\t\tline = line.replace(\"%WORLD%\", plugin.worldManager.getWorldName(player.getWorld()));\n\t\t\t\tline = ChatColor.translateAlternateColorCodes('&', line);\n\n\t\t\t\t// set sign text\n\t\t\t\tsign.setLine(lineCount, line);\n\t\t\t\tlineCount++;\n\t\t\t}\n\n\t\t\t// update sign block with text and direction\n\t\t\tsign.update();\n\n\t\t\t// create ChestBlock for this sign block\n\t\t\tChestBlock signChestBlock = new ChestBlock(deathChest.getChestUid(), signBlock.getLocation());\n\n\t\t\t// add this ChestBlock to block map\n\t\t\tplugin.chestManager.putBlock(ChestBlockType.SIGN, signChestBlock);\n\n\t\t\t// set sign block metadata\n\t\t\tsignChestBlock.setMetadata(deathChest);\n\n\t\t\t// return success\n\t\t\treturn true;\n\t\t}\n\t\tcatch (Exception e) {\n\t\t\tplugin.getLogger().severe(\"An error occurred while trying to place the death chest sign.\");\n\t\t\tplugin.getLogger().severe(e.getLocalizedMessage());\n\t\t\tif (plugin.getConfig().getBoolean(\"debug\")) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t\treturn false;\n\t\t}\n\t}\n\n\n\t/**\n\t * Check if sign can be placed at location\n\t *\n\t * @param location Location to check\n\t * @return boolean {@code true} if location is valid for sign placement, {@code false} if not\n\t */\n\tprivate boolean isValidSignLocation(final Location location) {\n\n\t\t// check for null parameter\n\t\tif (location == null) {\n\t\t\treturn false;\n\t\t}\n\n\t\t// get block at location\n\t\tBlock block = location.getBlock();\n\n\t\tif (isAbovePath(block)) {\n\t\t\treturn false;\n\t\t}\n\n\t\t// check if block at location is a ReplaceableBlock\n\t\treturn plugin.chestManager.isReplaceableBlock(block);\n\t}\n\n\n\tpublic static boolean isAbovePath(final Block block) {\n\n\t\t// get string for block material type at location below block\n\t\tString materialType = block.getRelative(0, -1, 0).getType().toString();\n\n\t\t// if block at location is above grass path, return negative result\n\t\treturn pathBlockTypeNames.contains(materialType);\n\t}\n\n\n\tprivate void sendResultMessage(final Player player, final SearchResult result, final long expireTime) {\n\n\t\t// send message based on result\n\t\tswitch (result.getResultCode()) {\n\t\t\tcase SUCCESS:\n\t\t\t\tplugin.messageBuilder.build(player, MessageId.CHEST_SUCCESS)\n\t\t\t\t\t\t.setMacro(Macro.LOCATION, result.getLocation())\n\t\t\t\t\t\t.setMacro(Macro.EXPIRATION_DURATION, TimeUnit.MINUTES.toMillis(expireTime))\n\t\t\t\t\t\t.setMacro(Macro.EXPIRATION_DURATION_MINUTES, TimeUnit.MINUTES.toMillis(expireTime))\n\t\t\t\t\t\t.setMacro(Macro.PROTECTION_DURATION, TimeUnit.MINUTES.toMillis(deathChest.getProtectionTime()))\n\t\t\t\t\t\t.setMacro(Macro.PROTECTION_DURATION_MINUTES, TimeUnit.MINUTES.toMillis(deathChest.getProtectionTime()))\n\t\t\t\t\t\t.send();\n\t\t\t\tbreak;\n\n\t\t\tcase PARTIAL_SUCCESS:\n\t\t\t\tplugin.messageBuilder.build(player, MessageId.DOUBLECHEST_PARTIAL_SUCCESS)\n\t\t\t\t\t\t.setMacro(Macro.LOCATION, result.getLocation())\n\t\t\t\t\t\t.setMacro(Macro.EXPIRATION_DURATION, TimeUnit.MINUTES.toMillis(expireTime))\n\t\t\t\t\t\t.setMacro(Macro.EXPIRATION_DURATION_MINUTES, TimeUnit.MINUTES.toMillis(expireTime))\n\t\t\t\t\t\t.send();\n\t\t\t\tbreak;\n\n\t\t\tcase PROTECTION_PLUGIN:\n\t\t\t\tplugin.messageBuilder.build(player, MessageId.CHEST_DENIED_DEPLOYMENT_BY_PLUGIN)\n\t\t\t\t\t\t.setMacro(Macro.LOCATION, result.getLocation())\n\t\t\t\t\t\t.setMacro(Macro.PLUGIN, result.getProtectionPlugin())\n\t\t\t\t\t\t.send();\n\t\t\t\tbreak;\n\n\t\t\tcase ABOVE_GRASS_PATH:\n\t\t\tcase NON_REPLACEABLE_BLOCK:\n\t\t\t\tplugin.messageBuilder.build(player, MessageId.CHEST_DENIED_BLOCK)\n\t\t\t\t\t\t.setMacro(Macro.LOCATION, result.getLocation())\n\t\t\t\t\t\t.send();\n\t\t\t\tbreak;\n\n\t\t\tcase ADJACENT_CHEST:\n\t\t\t\tplugin.messageBuilder.build(player, MessageId.CHEST_DENIED_ADJACENT)\n\t\t\t\t\t\t.setMacro(Macro.LOCATION, result.getLocation())\n\t\t\t\t\t\t.send();\n\t\t\t\tbreak;\n\n\t\t\tcase NO_CHEST:\n\t\t\t\tplugin.messageBuilder.build(player, MessageId.NO_CHEST_IN_INVENTORY)\n\t\t\t\t\t\t.setMacro(Macro.LOCATION, result.getLocation())\n\t\t\t\t\t\t.send();\n\t\t\t\tbreak;\n\n\t\t\tcase SPAWN_RADIUS:\n\t\t\t\tplugin.messageBuilder.build(player, MessageId.CHEST_DENIED_SPAWN_RADIUS)\n\t\t\t\t\t\t.setMacro(Macro.LOCATION, result.getLocation())\n\t\t\t\t\t\t.send();\n\t\t\t\tbreak;\n\n\t\t\tcase VOID:\n\t\t\t\tplugin.messageBuilder.build(player, MessageId.CHEST_DENIED_VOID)\n\t\t\t\t\t\t.setMacro(Macro.LOCATION, result.getLocation())\n\t\t\t\t\t\t.send();\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\n\tprivate void logResult(final SearchResult result) {\n\n\t\tif (result == null) {\n\t\t\tplugin.getLogger().info(\"SearchResult is null!\");\n\t\t\treturn;\n\t\t}\n\n\t\tif (result.getResultCode() != null) {\n\t\t\tplugin.getLogger().info(\"SearchResult Code: \" + result.getResultCode());\n\t\t}\n\t\tif (result.getLocation() != null) {\n\t\t\tplugin.getLogger().info(\"Location: \" + result.getLocation());\n\t\t}\n\t\tif (result.getProtectionPlugin() != null) {\n\t\t\tplugin.getLogger().info(\"Protection Plugin: \" + result.getProtectionPlugin());\n\t\t}\n\t\tif (result.getRemainingItems() != null) {\n\t\t\tplugin.getLogger().info(\"Remaining Items: \" + result.getRemainingItems());\n\t\t}\n\t}\n\n}",
"public enum Macro {\n\n\tEXPIRATION_DURATION,\n\tEXPIRATION_DURATION_MINUTES,\n\tPROTECTION_DURATION,\n\tPROTECTION_DURATION_MINUTES,\n\tLOCATION,\n\tPLUGIN,\n\tITEM_NUMBER,\n\tPAGE_NUMBER,\n\tPAGE_TOTAL,\n\tOWNER,\n\tKILLER,\n\tVIEWER,\n\n}",
"public enum MessageId {\n\n\tCHEST_SUCCESS,\n\tDOUBLECHEST_PARTIAL_SUCCESS,\n\tCHEST_DENIED_DEPLOYMENT_BY_PLUGIN,\n\tCHEST_DENIED_ACCESS_BY_PLUGIN,\n\tCHEST_DENIED_BLOCK,\n\tCHEST_DENIED_PERMISSION,\n\tCHEST_DENIED_ADJACENT,\n\tCHEST_DENIED_SPAWN_RADIUS,\n\tCHEST_DENIED_WORLD_DISABLED,\n\tCHEST_DENIED_VOID,\n\tCHEST_DEPLOYED_PROTECTION_TIME,\n\tCHEST_ACCESSED_PROTECTION_TIME,\n\tINVENTORY_EMPTY,\n\tINVENTORY_FULL,\n\tNO_CHEST_IN_INVENTORY,\n\tNOT_OWNER,\n\tCHEST_EXPIRED,\n\tCREATIVE_MODE,\n\tNO_CREATIVE_ACCESS,\n\tCHEST_CURRENTLY_OPEN,\n\n\tCOMMAND_FAIL_INVALID_COMMAND,\n\tCOMMAND_FAIL_ARGS_COUNT_OVER,\n\tCOMMAND_FAIL_HELP_PERMISSION,\n\tCOMMAND_FAIL_LIST_PERMISSION,\n\tCOMMAND_FAIL_LIST_OTHER_PERMISSION,\n\tCOMMAND_FAIL_RELOAD_PERMISSION,\n\tCOMMAND_FAIL_STATUS_PERMISSION,\n\tCOMMAND_SUCCESS_RELOAD,\n\n\tCOMMAND_HELP_INVALID,\n\tCOMMAND_HELP_HELP,\n\tCOMMAND_HELP_LIST,\n\tCOMMAND_HELP_RELOAD,\n\tCOMMAND_HELP_STATUS,\n\tCOMMAND_HELP_USAGE,\n\n\tLIST_HEADER,\n\tLIST_FOOTER,\n\tLIST_EMPTY,\n\tLIST_ITEM,\n\tLIST_ITEM_ALL,\n\tLIST_PLAYER_NOT_FOUND,\n\n}",
"public class InventoryOpenAction implements ResultAction {\n\n\t@Override\n\tpublic void execute(final Cancellable event, final Player player, final DeathChest deathChest) {\n\t\tevent.setCancelled(true);\n\t\tplayer.openInventory(deathChest.getInventory());\n\t}\n\n}",
"final public class PermissionCheck {\n\n\t// reference to plugin main class\n\tPluginMain plugin;\n\n\n\t/**\n\t * Class constructor\n\t *\n\t * @param plugin reference to plugin main class\n\t */\n\tpublic PermissionCheck(final PluginMain plugin) {\n\t\tthis.plugin = plugin;\n\t}\n\n\n\t/**\n\t * Send debug message to log if debugging is enabled in configuration file\n\t *\n \t * @param message the debug message to log\n\t */\n\t@SuppressWarnings(\"unused\")\n\tpublic void logDebugMessage(final String message) {\n\t\tif (plugin.getConfig().getBoolean(\"debug\")) {\n\t\t\tplugin.getLogger().info(message);\n\t\t}\n\t}\n\n\n\t/**\n\t * Check if chest access is blocked by another plugin\n\t *\n\t * @param result the access check result\n\t * @return true if protectionPlugin is a valid plugin, false if it is null\n\t */\n\tpublic boolean isPluginBlockingAccess(final ProtectionCheckResult result) {\n\t\treturn result.getResultCode().equals(ProtectionCheckResultCode.BLOCKED);\n\t}\n\n\n\t/**\n\t * Check if player is in create mode and deployment is configured disabled\n\t * and player does not have overriding permission\n\t *\n\t * @param player the player on whose behalf a chest is being deployed\n\t * @return true if deployment should be denied, false if not\n\t */\n\tpublic boolean isCreativeDeployDisabled(final Player player) {\n\t\treturn player.getGameMode().equals(GameMode.CREATIVE)\n\t\t\t\t&& !plugin.getConfig().getBoolean(\"creative-deploy\")\n\t\t\t\t&& !player.hasPermission(\"deathchest.creative-deploy\");\n\t}\n\n\n\t/**\n\t * Check if player is in creative mode and access is configured disabled\n\t * and player does not have overriding permission\n\t *\n\t * @param player the player attempting to access a chest\n\t * @return true if player should be denied access, false if not\n\t */\n\tprivate boolean isCreativeAccessDisabled(final Player player) {\n\t\treturn player.getGameMode().equals(GameMode.CREATIVE)\n\t\t\t\t&& !plugin.getConfig().getBoolean(\"creative-access\")\n\t\t\t\t&& !player.hasPermission(\"deathchest.creative-access\");\n\t}\n\n\n\t/**\n\t * Check if a chest inventory is already open and being viewed by another player\n\t * @param deathChest the deathchest to check\n\t *\n\t * @return true if chest is already open, false if not\n\t */\n\tprivate boolean isCurrentlyOpen(final DeathChest deathChest) {\n\t\treturn deathChest.getViewerCount() > 0;\n\t}\n\n\n\t/**\n\t * check if chest protection is enabled in configuration file\n\t *\n\t * @return true if chest protection is enabled, false if not\n\t */\n\tprivate boolean isProtectionDisabled() {\n\t\treturn !plugin.getConfig().getBoolean(\"chest-protection\");\n\t}\n\n\n\t/**\n\t * Check if chest protection is enabled and has expired for death chest\n\t *\n\t * @param deathChest the death chest to check expiration\n\t * @return true if protection is enabled and chest has expired, false if not\n\t */\n\tprivate boolean isProtectionExpired(final DeathChest deathChest) {\n\t\treturn plugin.getConfig().getBoolean(\"chest-protection\") &&\n\t\t\t\tdeathChest.protectionExpired();\n\t}\n\n\n\t/**\n\t * Check if chest protection is enabled and has not expired for death chest\n\t *\n\t * @param deathChest the death chest to check expiration\n\t * @return true if protection is enabled and chest has not expired, otherwise false\n\t */\n\tprivate boolean isProtectionNotExpired(final DeathChest deathChest) {\n\t\treturn plugin.getConfig().getBoolean(\"chest-protection\") &&\n\t\t\t\t!deathChest.protectionExpired();\n\t}\n\n\n\t/**\n\t * Check if chest protection is enabled and player has permission to loot other's chests\n\t *\n\t * @param player the player to check for permission\n\t * @return true if player has permission, false if not\n\t */\n\tprivate boolean hasLootOtherPermission(final Player player) {\n\t\treturn plugin.getConfig().getBoolean(\"chest-protection\") &&\n\t\t\t\tplayer.hasPermission(\"deathchest.loot.other\");\n\t}\n\n\n\t/**\n\t * Check if chest protection is enabled and killer looting is enabled\n\t * and player is killer of death chest owner and player has killer looting permission\n\t *\n\t * @param player the player to check for killer looting\n\t * @param deathChest the death chest being looted\n\t * @return true if all killer looting checks pass, false if not\n\t */\n\tprivate boolean isKillerLooting(final Player player, final DeathChest deathChest) {\n\t\treturn plugin.getConfig().getBoolean(\"chest-protection\") &&\n\t\t\t\tplugin.getConfig().getBoolean(\"killer-looting\") &&\n\t\t\t\tdeathChest.isKiller(player) &&\n\t\t\t\tplayer.hasPermission(\"deathchest.loot.killer\");\n\t}\n\n\n\t/**\n\t * Perform permission checks and take action for a player interacting with death chest\n\t *\n\t * @param event the PlayerInteractEvent being checked\n\t * @param player the player who is attempting to open a chest\n\t * @param deathChest the deathchest that is being quick-looted\n\t */\n\tpublic void performChecks(final Cancellable event, final Player player,\n\t final DeathChest deathChest, final ResultAction resultAction) {\n\n\t\t// get protectionCheckResult of all protection plugin checks\n\t\tfinal ProtectionCheckResult protectionCheckResult = plugin.protectionPluginRegistry.AccessAllowed(player, deathChest.getLocation());\n\n\t\t// if access blocked by protection plugin, do nothing and return (allow protection plugin to handle)\n\t\tif (isPluginBlockingAccess(protectionCheckResult)) {\n\t\t\t// do not cancel event - allow protection plugin to handle it\n\t\t\treturn;\n\t\t}\n\n\t\t// if chest inventory is already being viewed: cancel event, send message and return\n\t\tif (isCurrentlyOpen(deathChest)) {\n\t\t\tevent.setCancelled(true);\n\t\t\tString viewerName = deathChest.getInventory().getViewers().iterator().next().getName();\n\t\t\tplugin.messageBuilder.build(player, MessageId.CHEST_CURRENTLY_OPEN)\n\t\t\t\t\t.setMacro(Macro.LOCATION, deathChest.getLocation())\n\t\t\t\t\t.setMacro(Macro.OWNER, deathChest.getOwnerName())\n\t\t\t\t\t.setMacro(Macro.KILLER, deathChest.getKillerName())\n\t\t\t\t\t.setMacro(Macro.VIEWER, viewerName)\n\t\t\t\t\t.send();\n\t\t\tplugin.soundConfig.playSound(player, SoundId.CHEST_DENIED_ACCESS);\n\t\t\treturn;\n\t\t}\n\n\t\t// if player is in creative mode, and creative-access is configured false,\n\t\t// and player does not have override permission: cancel event, send message and return\n\t\tif (isCreativeAccessDisabled(player)) {\n\t\t\tevent.setCancelled(true);\n\t\t\tplugin.messageBuilder.build(player, MessageId.NO_CREATIVE_ACCESS)\n\t\t\t\t\t.setMacro(Macro.LOCATION, player.getLocation()\n\t\t\t\t\t).send();\n\t\t\tplugin.soundConfig.playSound(player, SoundId.CHEST_DENIED_ACCESS);\n\t\t\treturn;\n\t\t}\n\n\t\t// if player is chest owner, perform result action and return\n\t\tif (deathChest.isOwner(player)) {\n\t\t\tresultAction.execute(event, player, deathChest);\n\t\t\treturn;\n\t\t}\n\n\t\t// if chest protection is not enabled, perform result action and return\n\t\tif (isProtectionDisabled()) {\n\t\t\tresultAction.execute(event, player, deathChest);\n\t\t\treturn;\n\t\t}\n\n\t\t// if chest protection is not enabled or chest protection has expired, perform result action and return\n\t\tif (isProtectionExpired(deathChest)) {\n\t\t\tresultAction.execute(event, player, deathChest);\n\t\t\treturn;\n\t\t}\n\n\t\t// if player has loot other permission, perform result action and return\n\t\tif (hasLootOtherPermission(player)) {\n\t\t\tresultAction.execute(event, player, deathChest);\n\t\t\treturn;\n\t\t}\n\n\t\t// if player is killer and killer looting enabled, perform result action and return\n\t\tif (isKillerLooting(player, deathChest)) {\n\t\t\tresultAction.execute(event, player, deathChest);\n\t\t\treturn;\n\t\t}\n\n\t\t// cancel event\n\t\tevent.setCancelled(true);\n\n\t\t// if chest protection is enabled and has not expired, send message and return\n\t\tif (isProtectionNotExpired(deathChest)) {\n\t\t\tlong protectionTimeRemainingMillis = deathChest.getProtectionTime() - System.currentTimeMillis();\n\t\t\tplugin.messageBuilder.build(player, MessageId.CHEST_ACCESSED_PROTECTION_TIME)\n\t\t\t\t\t.setMacro(Macro.OWNER, deathChest.getOwnerName())\n\t\t\t\t\t.setMacro(Macro.PROTECTION_DURATION, protectionTimeRemainingMillis)\n\t\t\t\t\t.setMacro(Macro.PROTECTION_DURATION_MINUTES, protectionTimeRemainingMillis)\n\t\t\t\t\t.setMacro(Macro.LOCATION, deathChest.getLocation())\n\t\t\t\t\t.send();\n\t\t}\n\t\t// else send player not-owner message\n\t\telse {\n\t\t\tplugin.messageBuilder.build(player, MessageId.NOT_OWNER)\n\t\t\t\t\t.setMacro(Macro.LOCATION, deathChest.getLocation())\n\t\t\t\t\t.setMacro(Macro.OWNER, deathChest.getOwnerName())\n\t\t\t\t\t.setMacro(Macro.KILLER, deathChest.getKillerName())\n\t\t\t\t\t.send();\n\t\t}\n\n\t\t// play denied access sound\n\t\tplugin.soundConfig.playSound(player, SoundId.CHEST_DENIED_ACCESS);\n\t}\n\n}",
"public class QuickLootAction implements ResultAction {\n\n\t@Override\n\tpublic void execute(final Cancellable event, final Player player, final DeathChest deathChest) {\n\t\tevent.setCancelled(true);\n\t\tdeathChest.autoLoot(player);\n\t}\n\n}",
"public interface ResultAction {\n\n\t/**\n\t * Execute action for permission check\n\t *\n\t * @param event the event where the permission check occurred\n\t * @param player the player involved in the event\n\t * @param deathChest the deathchest involved in the event\n\t */\n\tvoid execute(final Cancellable event, final Player player, final DeathChest deathChest);\n\n}"
] | import com.winterhavenmc.deathchest.PluginMain;
import com.winterhavenmc.deathchest.chests.DeathChest;
import com.winterhavenmc.deathchest.chests.Deployment;
import com.winterhavenmc.deathchest.messages.Macro;
import com.winterhavenmc.deathchest.messages.MessageId;
import com.winterhavenmc.deathchest.permissions.InventoryOpenAction;
import com.winterhavenmc.deathchest.permissions.PermissionCheck;
import com.winterhavenmc.deathchest.permissions.QuickLootAction;
import com.winterhavenmc.deathchest.permissions.ResultAction;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.Collection;
import java.util.LinkedList; | /*
* Copyright (c) 2022 Tim Savage.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.winterhavenmc.deathchest.listeners;
/**
* A class that contains {@code EventHandler} methods to process player related events
*/
public final class PlayerEventListener implements Listener {
// reference to main class
private final PluginMain plugin;
// reference to permissionCheck class
private final PermissionCheck permissionCheck;
| private final ResultAction inventoryOpenAction = new InventoryOpenAction(); | 5 |
AKuznetsov/russianmorphology | dictionary-reader/src/test/java/org/apache/lucene/morphology/AnalyzersTest.java | [
"public class MorphologyAnalyzer extends Analyzer {\r\n private LuceneMorphology luceneMorph;\r\n\r\n public MorphologyAnalyzer(LuceneMorphology luceneMorph) {\r\n this.luceneMorph = luceneMorph;\r\n }\r\n\r\n public MorphologyAnalyzer(String pathToMorph, LetterDecoderEncoder letterDecoderEncoder) throws IOException {\r\n luceneMorph = new LuceneMorphology(pathToMorph, letterDecoderEncoder);\r\n }\r\n\r\n public MorphologyAnalyzer(InputStream inputStream, LetterDecoderEncoder letterDecoderEncoder) throws IOException {\r\n luceneMorph = new LuceneMorphology(inputStream, letterDecoderEncoder);\r\n }\r\n\r\n\r\n @Override\r\n protected TokenStreamComponents createComponents(String s) {\r\n\r\n StandardTokenizer src = new StandardTokenizer();\r\n final PayloadEncoder encoder = new PayloadEncoder() {\r\n @Override\r\n public BytesRef encode(char[] buffer) {\r\n final Float payload = Float.valueOf(new String(buffer));\r\n System.out.println(payload);\r\n final byte[] bytes = PayloadHelper.encodeFloat(payload);\r\n return new BytesRef(bytes, 0, bytes.length);\r\n }\r\n\r\n @Override\r\n public BytesRef encode(char[] buffer, int offset, int length) {\r\n\r\n final Float payload = Float.valueOf(new String(buffer, offset, length));\r\n System.out.println(payload);\r\n final byte[] bytes = PayloadHelper.encodeFloat(payload);\r\n\r\n return new BytesRef(bytes, 0, bytes.length);\r\n }\r\n };\r\n\r\n TokenFilter filter = new LowerCaseFilter(src);\r\n filter = new MorphologyFilter(filter, luceneMorph);\r\n\r\n return new TokenStreamComponents(src::setReader, filter);\r\n }\r\n}\r",
"public class MorphologyFilter extends TokenFilter {\r\n private LuceneMorphology luceneMorph;\r\n private Iterator<String> iterator;\r\n private final CharTermAttribute termAtt = addAttribute(CharTermAttribute.class);\r\n private final KeywordAttribute keywordAttr = addAttribute(KeywordAttribute.class);\r\n private final PositionIncrementAttribute position = addAttribute(PositionIncrementAttribute.class);\r\n private State state = null;\r\n\r\n public MorphologyFilter(TokenStream tokenStream, LuceneMorphology luceneMorph) {\r\n super(tokenStream);\r\n this.luceneMorph = luceneMorph;\r\n }\r\n\r\n\r\n final public boolean incrementToken() throws IOException {\r\n if (iterator != null) {\r\n if (iterator.hasNext()) {\r\n restoreState(state);\r\n position.setPositionIncrement(0);\r\n termAtt.setEmpty().append(iterator.next());\r\n return true;\r\n } else {\r\n state = null;\r\n iterator = null;\r\n }\r\n }\r\n while (true) {\r\n boolean b = input.incrementToken();\r\n if (!b) {\r\n return false;\r\n }\r\n if (!keywordAttr.isKeyword() && termAtt.length() > 0) {\r\n String s = new String(termAtt.buffer(), 0, termAtt.length());\r\n if (luceneMorph.checkString(s)) {\r\n List<String> forms = luceneMorph.getNormalForms(s);\r\n if (forms.isEmpty()) {\r\n continue;\r\n } else if (forms.size() == 1) {\r\n termAtt.setEmpty().append(forms.get(0));\r\n } else {\r\n state = captureState();\r\n iterator = forms.iterator();\r\n termAtt.setEmpty().append(iterator.next());\r\n }\r\n }\r\n }\r\n return true;\r\n }\r\n }\r\n\r\n @Override\r\n public void reset() throws IOException {\r\n super.reset();\r\n state = null;\r\n iterator = null;\r\n }\r\n}\r",
"public class EnglishAnalyzer extends MorphologyAnalyzer {\r\n\r\n public EnglishAnalyzer() throws IOException {\r\n super(new EnglishLuceneMorphology());\r\n }\r\n\r\n}",
"public class EnglishLuceneMorphology extends LuceneMorphology {\n\n public EnglishLuceneMorphology() throws IOException {\n super(EnglishLuceneMorphology.class.getResourceAsStream(\"/org/apache/lucene/morphology/english/morph.info\"), new EnglishLetterDecoderEncoder());\n }\n}",
"public class RussianAnalyzer extends MorphologyAnalyzer {\r\n public RussianAnalyzer() throws IOException {\r\n super(new RussianLuceneMorphology());\r\n }\r\n}\r",
"public class RussianLuceneMorphology extends LuceneMorphology {\n\n public RussianLuceneMorphology() throws IOException {\n super(RussianLuceneMorphology.class.getResourceAsStream(\"/org/apache/lucene/morphology/russian/morph.info\"), new RussianLetterDecoderEncoder());\n }\n}"
] | import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.BaseTokenStreamTestCase;
import org.apache.lucene.analysis.CharArraySet;
import org.apache.lucene.analysis.LowerCaseFilter;
import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.miscellaneous.SetKeywordMarkerFilter;
import org.apache.lucene.analysis.standard.StandardTokenizer;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute;
import org.apache.lucene.morphology.analyzer.MorphologyAnalyzer;
import org.apache.lucene.morphology.analyzer.MorphologyFilter;
import org.apache.lucene.morphology.english.EnglishAnalyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.morphology.english.EnglishLuceneMorphology;
import org.apache.lucene.morphology.russian.RussianAnalyzer;
import org.apache.lucene.morphology.russian.RussianLuceneMorphology;
import org.hamcrest.MatcherAssert;
import org.junit.Test;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import static org.hamcrest.Matchers.equalTo;
| /**
* Copyright 2009 Alexander Kuznetsov
*
* 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 org.apache.lucene.morphology;
public class AnalyzersTest extends BaseTokenStreamTestCase {
@Test
public void shouldGiveCorrectWordsForEnglish() throws IOException {
Analyzer morphlogyAnalyzer = new EnglishAnalyzer();
String answerPath = "/english/english-analyzer-answer.txt";
String testPath = "/english/english-analyzer-data.txt";
testAnalayzer(morphlogyAnalyzer, answerPath, testPath);
}
@Test
public void shouldGiveCorrectWordsForRussian() throws IOException {
Analyzer morphlogyAnalyzer = new RussianAnalyzer();
String answerPath = "/russian/russian-analyzer-answer.txt";
String testPath = "/russian/russian-analyzer-data.txt";
testAnalayzer(morphlogyAnalyzer, answerPath, testPath);
}
@Test
public void emptyStringTest() throws IOException {
LuceneMorphology russianLuceneMorphology = new RussianLuceneMorphology();
LuceneMorphology englishLuceneMorphology = new EnglishLuceneMorphology();
MorphologyAnalyzer russianAnalyzer = new MorphologyAnalyzer(russianLuceneMorphology);
InputStreamReader reader = new InputStreamReader(new ByteArrayInputStream("тест пм тест".getBytes()), StandardCharsets.UTF_8);
TokenStream stream = russianAnalyzer.tokenStream(null, reader);
| MorphologyFilter englishFilter = new MorphologyFilter(stream, englishLuceneMorphology);
| 1 |
ccascone/JNetMan | src/jnetman/network/Agent.java | [
"public final class MIB {\n\n\t/*\n\t * MIB-II Root\n\t */\n\tpublic static final OID Mib2Root = new OID(\".1.3.6.1.2.1\");\n\t/*\n\t * System\n\t */\n\tpublic static final OID System = new OID(Mib2Root).append(1);\n\tpublic static final OID sysDescr = new OID(System).append(\".1.0\");\n\tpublic static final OID sysUptime = new OID(System).append(\".3.0\");\n\t/*\n\t * MIB-II Interfaces\n\t */\n\tpublic static final OID Interfaces = new OID(Mib2Root).append(2);\n\tpublic static final OID IfNumber = new OID(Interfaces).append(\".1.0\");\n\tpublic static final OID IfTable = new OID(Interfaces).append(2);\n\tpublic static final OID IfTableEntry = new OID(IfTable).append(1);\n\tpublic static final OID IfIndex = new OID(IfTableEntry).append(1);\n\tpublic static final OID IfDescr = new OID(IfTableEntry).append(2);\n\tpublic static final OID IfType = new OID(IfTableEntry).append(3);\n\tpublic static final OID IfInOctets = new OID(IfTableEntry).append(10);\n\tpublic static final OID IfOutOctets = new OID(IfTableEntry).append(16);\n\t/*\n\t * MIB-II Ip\n\t */\n\tpublic static final OID Ip = new OID(Mib2Root).append(4);\n\tpublic static final OID IpOutNoRoutes = new OID(Ip).append(\".12.0\");\n\tpublic static final OID IpAddrTable = new OID(Ip).append(20);\n\tpublic static final OID IpAddrEntry = new OID(IpAddrTable).append(1);\n\tpublic static final OID IpAdEntAddr = new OID(IpAddrEntry).append(1);\n\tpublic static final OID IpAdEntIfIndex = new OID(IpAddrEntry).append(2);\n\tpublic static final OID IpAdEntNetMask = new OID(IpAddrEntry).append(3);\n\n\t/*\n\t * MIB-II Ip = new OID(.1.3.6.1.2.1.4\n\t */\n\tpublic static final OID Ospf = new OID(Mib2Root).append(14);\n\tpublic static final OID ospfIfMetricTable = new OID(Ospf).append(8);\n\tpublic static final OID ospfIfMetricEntry = new OID(ospfIfMetricTable)\n\t\t\t.append(1);\n\tpublic static final OID ospfIfMetricValue = new OID(ospfIfMetricEntry)\n\t\t\t.append(4);\n\n\t/**\n\t * Get the corresponding OID of the ospfIfMetricTable for the passed indexes\n\t * \n\t * @param entryOid\n\t * ospfIfMetricEntry OID\n\t * @param ipAddress\n\t * ospfIfMetricIpAddress\n\t * @param addressLessIf\n\t * ospfIfMetricAddressLessIf\n\t * @param ifMetricTos\n\t * ospfIfMetricTOS\n\t * @return The ospfIfMetricEntry OID completed with the indexes\n\t */\n\tpublic static final OID getOspfIfMetricEntryOID(OID entryOid,\n\t\t\tInetAddress ipAddress, int addressLessIf, int ifMetricTos) {\n\t\tIpAddress addr = new IpAddress(ipAddress);\n\t\tInteger32 lessIf = new Integer32(addressLessIf);\n\t\tInteger32 tos = new Integer32(ifMetricTos);\n\n\t\treturn new OID(entryOid).append(addr.toSubIndex(false))\n\t\t\t\t.append(lessIf.toSubIndex(false)).append(tos.toSubIndex(false));\n\n\t}\n}",
"public class MibHelper {\n\n\tSnmpHelper snmpHelper;\n\tSnmpClient snmpClient;\n\tLogger logger;\n\n\tpublic MibHelper(SnmpHelper snmpHelper) {\n\t\tthis.snmpHelper = snmpHelper;\n\t\tthis.snmpClient = snmpHelper.getSnmpClient();\n\t\tlogger = Logger.getLogger(\"snmp.mibHelper.\"\n\t\t\t\t+ snmpClient.getNetworkDevice().getName());\n\t\tlogger.debug(\"New MIB Helper created\");\n\t}\n\n\tpublic int lookupIfIndex(String ifDescr) throws TimeoutException,\n\t\t\tSnmpErrorException {\n\t\tVariableBinding[] vbs = snmpClient.walk(MIB.IfDescr);\n\t\tfor (VariableBinding vb : vbs) {\n\t\t\tif (vb.toValueString().equals(ifDescr))\n\t\t\t\treturn vb.getOid().last();\n\t\t}\n\t\tlogger.error(\"IfIndex not found\");\n\t\treturn -1;\n\t}\n\n}",
"public class SnmpClient implements PDUFactory {\n\n\tprivate Snmp snmpInstance;\n\tprivate NetworkDevice targetDevice;\n\n\tprivate static int requestID = 1;\n\tprivate Logger logger;\n\n\t/**\n\t * Create a new SnmpClient for the passed NetworkDevice.\n\t * \n\t * @param targetDevice\n\t * NetworkDevice that will be used for SNMP message exchange.\n\t */\n\tpublic SnmpClient(NetworkDevice targetDevice) {\n\t\tthis.targetDevice = targetDevice;\n\n\t\t// Create a new logger with name jnetman.snmp.device_name\n\t\tlogger = Logger.getLogger(\"snmp.snmpClient.\" + targetDevice.getName());\n\n\t\t// If activated SNMP4J will show a huge amount of low level debug info\n\t\tif (SnmpPref.isSnmp4jLogEnabled())\n\t\t\tLogFactory.setLogFactory(new Log4jLogFactory());\n\n\t\ttry {\n\t\t\tDefaultUdpTransportMapping transport = new DefaultUdpTransportMapping();\n\n\t\t\t// Creates Snmp istance for that transport channel\n\t\t\tsnmpInstance = new Snmp(transport);\n\t\t\tlogger.debug(\"New SNMP Client crated\");\n\n\t\t\t// Creates v3 SNMP USM\n\t\t\tUSM usm = new USM(SecurityProtocols.getInstance(), new OctetString(\n\t\t\t\t\tMPv3.createLocalEngineID()), 0);\n\t\t\tSecurityModels.getInstance().addSecurityModel(usm);\n\n\t\t\t// Adds 'jnetman' usm using MD5 authentication and DES encryption\n\t\t\tUsmUser jnetmanUser = new UsmUser(\n\t\t\t\t\tnew OctetString(SnmpPref.getUser()), AuthMD5.ID,\n\t\t\t\t\tnew OctetString(SnmpPref.getPassword()), PrivDES.ID,\n\t\t\t\t\tnew OctetString(SnmpPref.getPassword()));\n\t\t\tsnmpInstance.getUSM().addUser(new OctetString(SnmpPref.getUser()),\n\t\t\t\t\tjnetmanUser);\n\t\t\tlogger.debug(\"New USM User added >> \" + jnetmanUser.getSecurityName());\n\n\t\t\t// Enables listening for incoming SNMP packet\n\t\t\ttransport.listen();\n\n\t\t} catch (IOException e) {\n\t\t\tlogger.fatal(\n\t\t\t\t\t\"IOException while creating a new DefaultUdpTransportMapping()\",\n\t\t\t\t\te);\n\t\t\tSystem.exit(-1);\n\t\t}\n\t}\n\n\tpublic NetworkDevice getNetworkDevice() {\n\t\treturn this.targetDevice;\n\t}\n\n\t/**\n\t * Returns a destination target to be used for a new SNMP message. The\n\t * target returned will use SNMP v3 protocol with authentication and privacy\n\t * enabled.\n\t * \n\t * @return v3 authPriv Target\n\t * @throws AddressException\n\t */\n\tprivate Target getV3AuthPrivTarget() {\n\n\t\tString hostAddress = null;\n\t\ttry {\n\t\t\thostAddress = targetDevice.getAddress().getHostAddress();\n\t\t} catch (AddressException e) {\n\t\t\tlogger.fatal(\"Unable to get the IP address from the NetworkDevice\",\n\t\t\t\t\te);\n\t\t\tSystem.exit(-1);\n\t\t}\n\n\t\t// set the address using the format 'udp:192.168.1.1/161'\n\t\tString address = String.format(\"udp:%s/%d\", hostAddress,\n\t\t\t\tSnmpPref.getPort());\n\t\tAddress targetAddress = GenericAddress.parse(address);\n\n\t\tUserTarget target = new UserTarget();\n\t\ttarget.setAddress(targetAddress);\n\t\ttarget.setRetries(SnmpPref.getMaxRetries());\n\t\ttarget.setTimeout(SnmpPref.getTimeout());\n\t\ttarget.setVersion(SnmpConstants.version3);\n\t\ttarget.setSecurityLevel(SecurityLevel.AUTH_PRIV);\n\t\ttarget.setSecurityName(new OctetString(SnmpPref.getUser()));\n\n\t\treturn target;\n\t}\n\n\t/**\n\t * Send a new GET request for multiple OIDs.\n\t * \n\t * @param oids\n\t * Array of OID for the request.\n\t * @return ResponseEvent for the request only if no timeout has occurred.\n\t * @throws TimeoutException\n\t * If request has timed out\n\t */\n\tpublic VariableBinding[] get(OID oids[]) throws TimeoutException,\n\t\t\tSnmpErrorException {\n\t\treturn this.packPDUAndSend(oids, PDU.GET);\n\t}\n\n\t/**\n\t * Send a new GET request for a single OID.\n\t * \n\t * @param oid\n\t * OID of the request.\n\t * @return ResponseEvent for the request only if no timeout has occurred.\n\t * @throws TimeoutException\n\t * If request has timed out\n\t */\n\tpublic VariableBinding get(OID oid) throws TimeoutException,\n\t\t\tSnmpErrorException {\n\t\treturn this.packPDUAndSend(new OID[] { new OID(oid) }, PDU.GET)[0];\n\t}\n\n\t/**\n\t * Send a new GETNEXT request for multiple OIDs.\n\t * \n\t * @param oids\n\t * Array of OID for the request.\n\t * @return ResponseEvent for the request only if no timeout has occurred.\n\t * @throws TimeoutException\n\t * If request has timed out\n\t */\n\tpublic VariableBinding[] getNext(OID oids[]) throws TimeoutException,\n\t\t\tSnmpErrorException {\n\t\treturn this.packPDUAndSend(oids, PDU.GETNEXT);\n\t}\n\n\t/**\n\t * Send a new GETNEXT request for a single OID\n\t * \n\t * @param oid\n\t * OID of the request\n\t * @return ResponseEvent for the request only if no timeout has occurred\n\t * @throws TimeoutException\n\t * If request has timed out\n\t */\n\tpublic VariableBinding getNext(OID oid) throws TimeoutException,\n\t\t\tSnmpErrorException {\n\t\treturn this.packPDUAndSend(new OID[] { new OID(oid) }, PDU.GETNEXT)[0];\n\t}\n\n\t/**\n\t * Send a new SET request for a single OID/value pair\n\t * \n\t * @param oid\n\t * OID of the value to write\n\t * @param value\n\t * New value to write\n\t * @return ResponseEvent for the request only if no timeout has occurred\n\t * @throws TimeoutException\n\t * If request has timed out\n\t */\n\tpublic VariableBinding set(OID oid, Variable value)\n\t\t\tthrows TimeoutException, SnmpErrorException {\n\t\treturn this.packPDUAndSend(new VariableBinding[] { new VariableBinding(\n\t\t\t\toid, value) }, PDU.SET)[0];\n\t}\n\n\t/**\n\t * Send a new SET request for a single VariableBinding\n\t * \n\t * @param vb\n\t * VariableBinding of the request\n\t * @return ResponseEvent for the request only if no timeout has occurred\n\t * @throws TimeoutException\n\t * If request has timed out\n\t */\n\tpublic VariableBinding set(VariableBinding vb) throws TimeoutException,\n\t\t\tSnmpErrorException {\n\t\treturn this.packPDUAndSend(new VariableBinding[] { vb }, PDU.SET)[0];\n\t}\n\n\t/**\n\t * Send a new SET request for multiple VariableBindings\n\t * \n\t * @param vb\n\t * Array of VariableBinding of the request\n\t * @return ResponseEvent for the request only if no timeout has occurred\n\t * @throws TimeoutException\n\t * If request has timed out\n\t */\n\tpublic VariableBinding[] set(VariableBinding[] vbs)\n\t\t\tthrows TimeoutException, SnmpErrorException {\n\t\treturn this.packPDUAndSend(vbs, PDU.SET);\n\t}\n\n\tpublic VariableBinding[] walk(OID oid) {\n\n\t\tlogger.debug(\"Starting walk at OID \" + oid.toString() + \"...\");\n\n\t\tfinal Vector<VariableBinding> snapshot = new Vector<VariableBinding>();\n\n\t\tfinal WalkCounts counts = new WalkCounts();\n\t\tfinal long startTime = System.nanoTime();\n\n\t\tTreeUtils treeUtils = new TreeUtils(snmpInstance, this);\n\n\t\tTreeListener treeListener = new TreeListener() {\n\n\t\t\tprivate boolean finished;\n\n\t\t\tpublic boolean next(TreeEvent e) {\n\t\t\t\tcounts.requests++;\n\n\t\t\t\tif (e.getVariableBindings() != null) {\n\t\t\t\t\tVariableBinding[] vbs = e.getVariableBindings();\n\t\t\t\t\tcounts.objects += vbs.length;\n\t\t\t\t\tfor (VariableBinding vb : vbs)\n\t\t\t\t\t\tsnapshot.add(vb);\n\t\t\t\t}\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tpublic void finished(TreeEvent e) {\n\t\t\t\tif ((e.getVariableBindings() != null)\n\t\t\t\t\t\t&& (e.getVariableBindings().length > 0))\n\t\t\t\t\tnext(e);\n\n\t\t\t\tlogger.debug(\"Walk completed in \"\n\t\t\t\t\t\t+ (System.nanoTime() - startTime) / 1000000 + \" ms, \"\n\t\t\t\t\t\t+ counts.objects + \" objects received in \"\n\t\t\t\t\t\t+ counts.requests + \" requests\");\n\n\t\t\t\tif (e.isError())\n\t\t\t\t\tlogger.debug(\"The following error occurred during walk: \"\n\t\t\t\t\t\t\t+ e.getErrorMessage());\n\n\t\t\t\tfinished = true;\n\n\t\t\t\tsynchronized (this) {\n\t\t\t\t\tthis.notify();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tpublic boolean isFinished() {\n\t\t\t\treturn finished;\n\t\t\t}\n\n\t\t};\n\t\tsynchronized (treeListener) {\n\t\t\ttreeUtils\n\t\t\t\t\t.getSubtree(getV3AuthPrivTarget(), oid, null, treeListener);\n\t\t\ttry {\n\t\t\t\ttreeListener.wait();\n\t\t\t} catch (InterruptedException ex) {\n\t\t\t\tlogger.debug(\"Tree retrieval interrupted: \" + ex.getMessage());\n\t\t\t\tThread.currentThread().interrupt();\n\t\t\t}\n\t\t}\n\t\treturn snapshot.toArray(new VariableBinding[snapshot.size()]);\n\t}\n\n\tpublic VariableBinding[] packPDUAndSend(OID[] oids, int pduType)\n\t\t\tthrows TimeoutException, SnmpErrorException {\n\n\t\tPDU pdu = new ScopedPDU();\n\t\tfor (OID oid : oids)\n\t\t\tpdu.add(new VariableBinding(oid));\n\n\t\tpdu.setType(pduType);\n\n\t\treturn this.send(pdu);\n\t}\n\n\tpublic VariableBinding[] packPDUAndSend(VariableBinding[] vbs, int pduType)\n\t\t\tthrows TimeoutException, SnmpErrorException {\n\n\t\tPDU pdu = new ScopedPDU();\n\t\tpdu.addAll(vbs);\n\n\t\tpdu.setType(pduType);\n\n\t\treturn this.send(pdu);\n\t}\n\n\tprivate synchronized VariableBinding[] send(PDU pdu)\n\t\t\tthrows TimeoutException, SnmpErrorException {\n\n\t\tResponseEvent event = null;\n\n\t\t/*\n\t\t * Well, it's now time to send a new SNMP message! Set the RequestID of\n\t\t * the PDU and increment the counter for the next operation.\n\t\t */\n\t\tpdu.setRequestID(new Integer32(requestID));\n\t\trequestID++;\n\n\t\t/*\n\t\t * The PDU is now ready to be sent\n\t\t */\n\t\tTarget target = getV3AuthPrivTarget();\n\t\t// Target target = getV3AuthNoPrivTarget();\n\t\t/*\n\t\t * Some debug about the request that is going to be sent.\n\t\t */\n\t\tlogger.debug(\"Sending request to \" + target.getAddress() + \" >> \" + pdu);\n\n\t\t/*\n\t\t * Calculate the time elapsed between the beginning of request\n\t\t * transmission and the end of the response reception, for debug\n\t\t * purpose.s\n\t\t */\n\t\tlong startTime = System.nanoTime();\n\t\ttry {\n\t\t\tevent = snmpInstance.send(pdu, target, null);\n\t\t} catch (IOException e) {\n\t\t\tlogger.fatal(\"IOException while sending a new SNMP message\", e);\n\t\t\tSystem.exit(-1);\n\t\t}\n\t\tlong timeElapsed = System.nanoTime() - startTime;\n\n\t\t/*\n\t\t * If response != null means that no timeout has occurred and a response\n\t\t * was successfully delivered.\n\t\t */\n\t\tif (event.getResponse() != null) {\n\n\t\t\tPDU response = event.getResponse();\n\t\t\t/*\n\t\t\t * Some debug about the response received\n\t\t\t */\n\t\t\tlogger.debug(\"Response received from \" + event.getPeerAddress()\n\t\t\t\t\t+ \" in \" + timeElapsed / 1000000 + \" ms >> \" + response);\n\n\t\t\t/*\n\t\t\t * Check for common SNMP errors due to failed request\n\t\t\t */\n\t\t\tif (response.getErrorStatus() == PDU.noError) {\n\n\t\t\t\t/*\n\t\t\t\t * Let's finally return the event, this could still contain a\n\t\t\t\t * SnmpSyntaxException (noSuchInstance, noSuchObject or\n\t\t\t\t * endOfMibView) but we don't care throwing it now. The client\n\t\t\t\t * user could be interested in doing it.\n\t\t\t\t */\n\t\t\t\treturn response.toArray();\n\n\t\t\t} else {\n\t\t\t\t/*\n\t\t\t\t * SNMP error has occurred.\n\t\t\t\t */\n\t\t\t\t/*\n\t\t\t\t * TODO Net-Snmp REPORT for failed authentication\n\t\t\t\t */\n\t\t\t\tlogger.error(\"SNMP ERROR >> \" + response.getErrorStatusText());\n\t\t\t\tthrow new SnmpErrorException(response.getErrorStatusText());\n\t\t\t}\n\t\t}\n\n\t\t/*\n\t\t * If here means that response == null, REQUEST TIME OUT!\n\t\t */\n\t\tlogger.error(\"Request TIMEOUT! No response received from \"\n\t\t\t\t+ target.getAddress());\n\t\tthrow new TimeoutException(target.getAddress());\n\n\t}\n\n\tpublic PDU createPDU(Target target) {\n\t\treturn new ScopedPDU();\n\t}\n\n\tprivate class WalkCounts {\n\t\tpublic int requests;\n\t\tpublic int objects;\n\t}\n\n}",
"public class SnmpErrorException extends Exception {\n\n\t/**\n\t * \n\t */\n\tprivate static final long serialVersionUID = 1304907512926256963L;\n\n\tpublic SnmpErrorException(String errorStatusText) {\n\t\tsuper(errorStatusText);\n\t}\n\n}",
"public class SnmpHelper {\n\n\tprivate SnmpClient snmpClient;\n\tprotected Logger logger;\n\n\tpublic SnmpHelper(SnmpClient snmpClient) {\n\t\tthis.snmpClient = snmpClient;\n\t\tlogger = Logger.getLogger(\"snmp.snmpHelper.\"\n\t\t\t\t+ snmpClient.getNetworkDevice().getName());\n\t\tlogger.debug(\"New Snmp helper created\");\n\t}\n\n\tpublic SnmpClient getSnmpClient() {\n\t\treturn this.snmpClient;\n\t}\n\n\tpublic Variable[] getVariable(OID[] oids) throws TimeoutException,\n\t\t\tSnmpErrorException, SnmpSyntaxException {\n\t\tVariableBinding[] vbs = this.snmpClient.get(oids);\n\t\tVariable[] vs = new Variable[vbs.length];\n\t\tfor (int i = 0; i < vbs.length; i++) {\n\t\t\tSnmpSyntaxException.checkForExceptions(vbs[i]);\n\t\t\tvs[i] = vbs[i].getVariable();\n\t\t}\n\t\treturn vs;\n\t}\n\n\tpublic Variable getVariable(OID oid) throws TimeoutException,\n\t\t\tSnmpErrorException, SnmpSyntaxException {\n\t\treturn getVariable(new OID[] { oid })[0];\n\t}\n\n\tpublic TimedValues getAsTimedValues(OID[] oids) throws TimeoutException,\n\t\t\tSnmpErrorException, SnmpSyntaxException {\n\t\treturn new TimedValues(oids, this);\n\t}\n\n\tpublic int getInt(OID oid) throws TimeoutException, SnmpErrorException,\n\t\t\tSnmpSyntaxException {\n\t\treturn this.getVariable(oid).toInt();\n\t}\n\n\tpublic int[] getInt(OID[] oids) throws TimeoutException,\n\t\t\tSnmpErrorException, SnmpSyntaxException {\n\t\tVariable[] vars = getVariable(oids);\n\t\tint[] ints = new int[vars.length];\n\t\tfor (int i = 0; i < vars.length; i++)\n\t\t\tints[i] = vars[i].toInt();\n\t\treturn ints;\n\t}\n\n\tpublic long getLong(OID oid) throws TimeoutException, SnmpErrorException,\n\t\t\tSnmpSyntaxException {\n\t\treturn this.getVariable(oid).toLong();\n\t}\n\n\tpublic long[] getLong(OID[] oids) throws TimeoutException,\n\t\t\tSnmpErrorException, SnmpSyntaxException {\n\t\tVariable[] vars = getVariable(oids);\n\t\tlong[] longs = new long[vars.length];\n\t\tfor (int i = 0; i < vars.length; i++)\n\t\t\tlongs[i] = vars[i].toLong();\n\t\treturn longs;\n\t}\n\n\tpublic String getString(OID oid) throws TimeoutException,\n\t\t\tSnmpErrorException, SnmpSyntaxException {\n\t\treturn this.getVariable(oid).toString();\n\t}\n\n\tpublic String[] getString(OID[] oids) throws TimeoutException,\n\t\t\tSnmpErrorException, SnmpSyntaxException {\n\t\tVariable[] vars = getVariable(oids);\n\t\tString[] strings = new String[vars.length];\n\t\tfor (int i = 0; i < vars.length; i++)\n\t\t\tstrings[i] = vars[i].toString();\n\t\treturn strings;\n\t}\n\n\tpublic boolean[] setVariableBinding(VariableBinding[] vbs)\n\t\t\tthrows TimeoutException, SnmpErrorException, SnmpSyntaxException {\n\t\tVariableBinding[] resVbs = snmpClient.set(vbs);\n\t\tSnmpSyntaxException.checkForExceptions(resVbs);\n\n\t\tboolean[] res = new boolean[vbs.length];\n\n\t\tfor (int i = 0; i < vbs.length; i++) {\n\t\t\tSnmpSyntaxException.checkForExceptions(resVbs[i]);\n\t\t\tif (resVbs[i].getOid().equals(vbs[i].getOid())\n\t\t\t\t\t&& resVbs[i].getVariable().equals(vbs[i].getVariable()))\n\t\t\t\tres[i] = true;\n\t\t\telse\n\t\t\t\tres[i] = false;\n\t\t}\n\t\treturn res;\n\t}\n\n\tpublic boolean setVariableBinding(VariableBinding vb)\n\t\t\tthrows TimeoutException, SnmpErrorException, SnmpSyntaxException {\n\t\treturn setVariableBinding(new VariableBinding[] { vb })[0];\n\t}\n\n\tpublic boolean[] setVariable(OID[] oids, Variable[] values)\n\t\t\tthrows TimeoutException, SnmpErrorException, SnmpSyntaxException {\n\t\tif (oids.length != values.length)\n\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\"oids and values arrays must have same length\");\n\t\tVariableBinding[] vbs = new VariableBinding[oids.length];\n\t\tfor (int i = 0; i < vbs.length; i++) {\n\t\t\tvbs[i] = new VariableBinding(oids[i], values[i]);\n\t\t}\n\t\treturn setVariableBinding(vbs);\n\t}\n\n\tpublic boolean setVariable(OID oid, Variable value)\n\t\t\tthrows TimeoutException, SnmpErrorException, SnmpSyntaxException {\n\t\treturn setVariable(new OID[] { oid }, new Variable[] { value })[0];\n\t}\n\n\tpublic boolean[] setInt(OID[] oids, int[] values, int[] smiSyntaxs)\n\t\t\tthrows TimeoutException, SnmpErrorException, SnmpSyntaxException {\n\t\tVariable[] vars = intToVariable(values, smiSyntaxs);\n\t\treturn setVariable(oids, vars);\n\t}\n\n\tpublic boolean setInt(OID oid, int value, int smiSyntax)\n\t\t\tthrows TimeoutException, SnmpErrorException, SnmpSyntaxException {\n\t\treturn setInt(new OID[] { oid }, new int[] { value },\n\t\t\t\tnew int[] { smiSyntax })[0];\n\t}\n\n\tpublic boolean[] setLong(OID[] oids, long[] values, int[] smiSyntaxs)\n\t\t\tthrows TimeoutException, SnmpErrorException, SnmpSyntaxException {\n\t\tVariable[] vars = longToVariable(values, smiSyntaxs);\n\t\treturn setVariable(oids, vars);\n\t}\n\n\tpublic boolean setLong(OID oid, long value, int smiSyntax)\n\t\t\tthrows TimeoutException, SnmpErrorException, SnmpSyntaxException {\n\t\treturn setLong(new OID[] { oid }, new long[] { value },\n\t\t\t\tnew int[] { smiSyntax })[0];\n\t}\n\n\tpublic boolean[] setString(OID[] oids, String[] values, int[] smiSyntaxs)\n\t\t\tthrows TimeoutException, SnmpErrorException, SnmpSyntaxException {\n\t\tVariable[] vars = stringToVariable(values, smiSyntaxs);\n\t\treturn setVariable(oids, vars);\n\t}\n\n\tpublic boolean setString(OID oid, String value, int smiSyntax)\n\t\t\tthrows TimeoutException, SnmpErrorException, SnmpSyntaxException {\n\t\treturn setString(new OID[] { oid }, new String[] { value },\n\t\t\t\tnew int[] { smiSyntax })[0];\n\t}\n\n\tpublic static Variable stringToVariable(String value, int smiSyntax) {\n\t\tVariable var = AbstractVariable.createFromSyntax(smiSyntax);\n\t\tif (var instanceof AssignableFromString)\n\t\t\t((AssignableFromString) var).setValue(value);\n\t\telse\n\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\"Unsupported conversion from String to \"\n\t\t\t\t\t\t\t+ var.getSyntaxString());\n\t\treturn var;\n\t}\n\n\tpublic static Variable[] stringToVariable(String[] values, int[] smiSyntaxs) {\n\t\tif (values.length != smiSyntaxs.length)\n\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\"values and smiSyntaxs arrays must have smae length\");\n\t\tVariable[] vars = new Variable[values.length];\n\t\tfor (int i = 0; i < values.length; i++) {\n\t\t\tvars[i] = stringToVariable(values[i], smiSyntaxs[i]);\n\t\t}\n\t\treturn vars;\n\t}\n\n\tpublic static Variable intToVariable(int i, int smiSyntax) {\n\t\tVariable var = AbstractVariable.createFromSyntax(smiSyntax);\n\t\tif (var instanceof AssignableFromInteger)\n\t\t\t((AssignableFromInteger) var).setValue(i);\n\t\telse\n\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\"Unsupported conversion from int to \"\n\t\t\t\t\t\t\t+ var.getSyntaxString());\n\t\treturn var;\n\t}\n\n\tpublic static Variable[] intToVariable(int[] values, int[] smiSyntaxs) {\n\t\tif (values.length != smiSyntaxs.length)\n\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\"values and smiSyntaxs arrays must have smae length\");\n\t\tVariable[] vars = new Variable[values.length];\n\t\tfor (int i = 0; i < values.length; i++) {\n\t\t\tvars[i] = intToVariable(values[i], smiSyntaxs[i]);\n\t\t}\n\t\treturn vars;\n\t}\n\n\tpublic static Variable longToVariable(long l, int smiSyntax) {\n\t\tVariable var = AbstractVariable.createFromSyntax(smiSyntax);\n\t\tif (var instanceof AssignableFromLong)\n\t\t\t((AssignableFromLong) var).setValue(l);\n\t\telse\n\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\"Unsupported conversion from long to \"\n\t\t\t\t\t\t\t+ var.getSyntaxString());\n\t\treturn var;\n\t}\n\n\tpublic static Variable[] longToVariable(long[] values, int[] smiSyntaxs) {\n\t\tif (values.length != smiSyntaxs.length)\n\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\"values and smiSyntaxs arrays must have smae length\");\n\t\tVariable[] vars = new Variable[values.length];\n\t\tfor (int i = 0; i < values.length; i++) {\n\t\t\tvars[i] = longToVariable(values[i], smiSyntaxs[i]);\n\t\t}\n\t\treturn vars;\n\t}\n\n\tpublic Table getTable(OID tableOid) {\n\t\tlogger.trace(\"Table retrieval started\");\n\n\t\tVariableBinding[] vbs = snmpClient.walk(tableOid);\n\n\t\tTable table = new Table();\n\n\t\tint[] subIdxArr;\n\t\tint[] colIdArr;\n\t\tOID subIdxOid;\n\t\tOID colIdOid;\n\n\t\tfor (VariableBinding vb : vbs) {\n\t\t\tif (vb.getOid().leftMostCompare(tableOid.size(), tableOid) != 0) {\n\t\t\t\tlogger.warn(\"The following OID doesn't seems to belong to table \"\n\t\t\t\t\t\t+ vb);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\t// extract the last part of the OID, the index\n\t\t\tsubIdxArr = Arrays.copyOfRange(vb.getOid().toIntArray(),\n\t\t\t\t\ttableOid.size() + 2, vb.getOid().size());\n\t\t\tsubIdxOid = new OID(subIdxArr);\n\t\t\t// extract the first part of the OID, the column\n\t\t\tcolIdArr = Arrays.copyOfRange(vb.getOid().toIntArray(), 0,\n\t\t\t\t\ttableOid.size() + 2);\n\t\t\tcolIdOid = new OID(colIdArr);\n\t\t\tlogger.trace(\"Index = \" + subIdxOid + \"; Column = \" + colIdOid);\n\t\t\ttable.putVariable(subIdxOid, colIdOid, vb.getVariable());\n\t\t}\n\n\t\treturn table;\n\t}\n\n\tpublic static int castToInt(Variable variable) {\n\t\tswitch (variable.getSyntax()) {\n\t\tcase SMIConstants.SYNTAX_INTEGER:\n\t\t\treturn ((Integer32) variable).toInt();\n\t\tdefault:\n\t\t\tthrow new IllegalArgumentException(\"Unsupported cast from \"\n\t\t\t\t\t+ variable.getSyntaxString() + \" to int\");\n\t\t}\n\t}\n\n\tpublic static int[] castToInt(Variable[] variables) {\n\t\tint[] ints = new int[variables.length];\n\t\tfor (int i = 0; i < variables.length; i++)\n\t\t\tints[i] = SnmpHelper.castToInt(variables[i]);\n\n\t\treturn ints;\n\t}\n\n\tpublic static long castToLong(Variable variable) {\n\t\tswitch (variable.getSyntax()) {\n\t\tcase SMIConstants.SYNTAX_GAUGE32:\n\t\t\treturn ((Gauge32) variable).toLong();\n\t\tcase SMIConstants.SYNTAX_COUNTER32:\n\t\t\treturn ((Counter32) variable).toLong();\n\t\tcase SMIConstants.SYNTAX_COUNTER64:\n\t\t\treturn ((Counter64) variable).toLong();\n\t\tcase SMIConstants.SYNTAX_TIMETICKS:\n\t\t\treturn ((TimeTicks) variable).toLong();\n\t\tdefault:\n\t\t\tthrow new IllegalArgumentException(\"Unsupported cast from \"\n\t\t\t\t\t+ variable.getSyntaxString() + \" to long\");\n\t\t}\n\t}\n\n\tpublic static long[] castToLong(Variable[] variables) {\n\t\tlong[] longs = new long[variables.length];\n\t\tfor (int i = 0; i < variables.length; i++)\n\t\t\tlongs[i] = SnmpHelper.castToLong(variables[i]);\n\n\t\treturn longs;\n\t}\n\n\tpublic static String castToString(Variable variable) {\n\t\treturn variable.toString();\n\t}\n\n\tpublic static String[] castToString(Variable[] variables) {\n\t\tString[] strings = new String[variables.length];\n\t\tfor (int i = 0; i < variables.length; i++)\n\t\t\tstrings[i] = SnmpHelper.castToString(variables[i]);\n\n\t\treturn strings;\n\t}\n\n\tpublic static OID[] stringsToOIDs(String[] stringOids) {\n\t\tOID[] oids = new OID[stringOids.length];\n\t\tfor (int i = 0; i < stringOids.length; i++)\n\t\t\toids[i] = new OID(stringOids[i]);\n\t\treturn oids;\n\t}\n\n}",
"public class SnmpSyntaxException extends Exception {\n\n\tprivate VariableBinding vb;\n\tprivate Variable variable;\n\n\tpublic SnmpSyntaxException(VariableBinding vb) {\n\t\tthis.vb = vb;\n\t\tthis.variable = vb.getVariable();\n\t}\n\n\tpublic SnmpSyntaxException(Variable variable) {\n\t\tthis.variable = variable;\n\t}\n\n\t/**\n\t * \n\t */\n\tprivate static final long serialVersionUID = 8067097283760805458L;\n\n\t/**\n\t * Check a ResponseEvent for a syntax exception (noSuchInstance,\n\t * noSuchObject, endOfMibView). If multiple variable bindings are contained\n\t * in the response a SnmpSyntaxException will be thrown at the first syntax\n\t * exception encountered.\n\t * \n\t * @param event\n\t * ResponseEvent to be checked\n\t * @throws SnmpSyntaxException\n\t * If the syntax one of the variable included in the response\n\t * equals one of the following:\n\t * <ul>\n\t * <li>noSuchInstance</li>\n\t * <li>noSuchObject</li>\n\t * <li>endOfMibView</li> </li>\n\t */\n\tpublic static void checkForException(ResponseEvent event)\n\t\t\tthrows SnmpSyntaxException {\n\t\tSnmpSyntaxException.checkForExceptions(event.getResponse().toArray());\n\t}\n\n\t/**\n\t * Check an array of variable bindings for a syntax exception\n\t * (noSuchInstance, noSuchObject, endOfMibView). A SnmpSyntaxException will\n\t * be thrown at the first syntax exception encountered.\n\t * \n\t * @param vbs\n\t * array of variable bindings to be checked\n\t * @throws SnmpSyntaxException\n\t * If the syntax one of the variable equals one of the\n\t * following:\n\t * <ul>\n\t * <li>noSuchInstance</li>\n\t * <li>noSuchObject</li>\n\t * <li>endOfMibView</li> </li>\n\t */\n\tpublic static void checkForExceptions(VariableBinding[] vbs)\n\t\t\tthrows SnmpSyntaxException {\n\t\tfor (VariableBinding vb : vbs)\n\t\t\tSnmpSyntaxException.checkForExceptions(vb);\n\t}\n\n\t/**\n\t * Check a variable binding for a syntax exception (noSuchInstance,\n\t * noSuchObject, endOfMibView).\n\t * \n\t * @param vb\n\t * variable binding to be checked\n\t * @throws SnmpSyntaxException\n\t * if the syntax of this variable equals one of the following:\n\t * <ul>\n\t * <li>noSuchInstance</li>\n\t * <li>noSuchObject</li>\n\t * <li>endOfMibView</li> </li>\n\t */\n\tpublic static void checkForExceptions(VariableBinding vb)\n\t\t\tthrows SnmpSyntaxException {\n\t\tif(vb.getVariable().isException())\n\t\t\tthrow new SnmpSyntaxException(vb);\n\t}\n\n\t/**\n\t * Check a variable for a syntax exception (noSuchInstance, noSuchObject,\n\t * endOfMibView).\n\t * \n\t * @param variable\n\t * variable to be checked\n\t * @throws SnmpSyntaxException\n\t * if the syntax of this variable equals one of the following:\n\t * <ul>\n\t * <li>noSuchInstance</li>\n\t * <li>noSuchObject</li>\n\t * <li>endOfMibView</li> </li>\n\t */\n\tpublic static void checkForExceptions(Variable variable)\n\t\t\tthrows SnmpSyntaxException {\n\t\tif (variable.isException())\n\t\t\tthrow new SnmpSyntaxException(variable);\n\t}\n\n\t/**\n\t * @return <code>true</code> if this exception has been generated by a\n\t * noSuchInstance SNMP syntax exception\n\t */\n\tpublic boolean isNoSuchInstance() {\n\t\tif (this.variable.getSyntax() == SMIConstants.EXCEPTION_NO_SUCH_INSTANCE)\n\t\t\treturn true;\n\t\telse\n\t\t\treturn false;\n\t}\n\n\t/**\n\t * @return <code>true</code> if this exception has been generated by a\n\t * noSuchObject SNMP syntax exception\n\t */\n\tpublic boolean isNoSuchObject() {\n\t\tif (this.variable.getSyntax() == SMIConstants.EXCEPTION_NO_SUCH_OBJECT)\n\t\t\treturn true;\n\t\telse\n\t\t\treturn false;\n\t}\n\n\t/**\n\t * @return <code>true</code> if this exception has been generated by a\n\t * isEndOfMibView SNMP syntax exception\n\t */\n\tpublic boolean isEndOfMibView() {\n\t\tif (this.variable.getSyntax() == SMIConstants.EXCEPTION_END_OF_MIB_VIEW)\n\t\t\treturn true;\n\t\telse\n\t\t\treturn false;\n\t}\n\n\tpublic String getMessage() {\n\t\tif (vb != null)\n\t\t\treturn vb.toString();\n\t\telse\n\t\t\treturn variable.getSyntaxString();\n\t}\n\n}",
"public class TimeoutException extends Exception {\n\n\t/**\n\t * \n\t */\n\tprivate static final long serialVersionUID = 1L;\n\n\tAddress address;\n\n\tpublic TimeoutException(Address address) {\n\t\tthis.address = address;\n\t}\n\n\tpublic String getMessage() {\n\t\treturn \"Request timeout, no response received from \"\n\t\t\t\t+ this.address.toString();\n\n\t}\n\n\tpublic Address getAddress() {\n\t\treturn this.address;\n\t}\n\n}"
] | import jnetman.snmp.MIB;
import jnetman.snmp.MibHelper;
import jnetman.snmp.SnmpClient;
import jnetman.snmp.SnmpErrorException;
import jnetman.snmp.SnmpHelper;
import jnetman.snmp.SnmpSyntaxException;
import jnetman.snmp.TimeoutException;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.snmp4j.smi.TimeTicks;
import org.snmp4j.smi.VariableBinding; | package jnetman.network;
public abstract class Agent {
protected MibHelper mibHelper;
protected SnmpHelper snmpHelper;
protected SnmpClient snmpClient;
protected Logger logger;
public Agent(NetworkDevice networkDevice)
throws AddressException {
if (networkDevice.getAddress() == null)
throw new AddressException(
"No IP address setted for "
+ networkDevice.getName()
+ ", you need to set an IP address before calling the agent ");
this.snmpClient = new SnmpClient(networkDevice);
this.snmpHelper = new SnmpHelper(this.snmpClient);
this.mibHelper = new MibHelper(this.snmpHelper);
logger = Logger.getLogger("network."
+ StringUtils.uncapitalize(this.getClass().getSimpleName())
+ "." + networkDevice.getName());
logger.debug("New agent created");
}
public SnmpClient getSnmpClient() {
return this.snmpClient;
}
public SnmpHelper getSnmpHelper() {
return this.snmpHelper;
}
public MibHelper getMibHelper() {
return this.mibHelper;
}
public boolean isResponding() {
VariableBinding vb = null;
try {
vb = this.snmpClient.get(MIB.sysUptime); | SnmpSyntaxException.checkForExceptions(vb); | 5 |
pdtyreus/conversation-kit | conversation-kit/src/main/java/com/conversationkit/builder/JsonGraphBuilder.java | [
"public class MapBackedNodeRepository<N extends IConversationNode> implements ConversationNodeRepository<N> {\n\n private static final Logger logger = Logger.getLogger(MapBackedNodeRepository.class.getName());\n private final Map<Integer, N> nodeIndex = new HashMap();\n\n @Override\n public N getNodeById(int id) {\n return nodeIndex.get(id);\n }\n \n public void addNodeToIndex(int id, N node) {\n nodeIndex.put(id, node);\n }\n\n}",
"public class ConversationEdge<I extends IConversationIntent, S extends IConversationState> implements IConversationEdge<I,S> {\n\n private final Integer endNodeId;\n private final String id;\n private final BiFunction<I, S, Boolean> validateFunction;\n private final List<BiFunction<I, S, Object>> sideEffects;\n\n public ConversationEdge(Integer endNodeId, String intentId) {\n this.endNodeId = endNodeId;\n this.id = intentId;\n this.validateFunction = (intent, state) -> {\n return true;\n };\n this.sideEffects = new ArrayList();\n }\n\n public ConversationEdge(Integer endNodeId, String intentId, BiFunction<I, S, Boolean> validateFunction, BiFunction<I, S, Object>... sideEffects) {\n this.endNodeId = endNodeId;\n this.id = intentId;\n this.validateFunction = validateFunction;\n this.sideEffects = new ArrayList();\n for (BiFunction<I, S, Object> effect : sideEffects) {\n this.sideEffects.add(effect);\n }\n }\n \n public ConversationEdge(Integer endNodeId, String intentId, BiFunction<I, S, Object> sideEffect) {\n this.endNodeId = endNodeId;\n this.id = intentId;\n this.validateFunction = (intent, state) -> {\n return true;\n };\n this.sideEffects = Arrays.asList(sideEffect);\n }\n\n @Override\n public Integer getEndNodeId() {\n return endNodeId;\n }\n\n @Override\n public String getIntentId() {\n return id;\n }\n\n @Override\n public String toString() {\n return \"ConversationEdge {\" + getIntentId() + '}';\n }\n\n @Override\n public boolean validate(I intent, S state) {\n return validateFunction.apply(intent, state);\n }\n\n @Override\n public List<Object> getSideEffects(I intent, S state) {\n List<Object> effects = new ArrayList();\n for (BiFunction<I, S, Object> effectFunction : sideEffects) {\n effects.add(effectFunction.apply(intent, state));\n }\n return effects;\n }\n}",
"public class DialogTreeNode implements IConversationNode<DialogTreeEdge> {\n\n protected final List<String> messages;\n protected final List<DialogTreeEdge> edges;\n private final int id;\n private final JsonObject metadata;\n\n /**\n * Creates a node with the specified text.\n *\n * @param id the unique ID of the node from the underlying data store\n * @param messages the text responses displayed to the user\n */\n public DialogTreeNode(int id, List<String> messages) {\n this.id = id;\n this.edges = new ArrayList();\n this.metadata = new JsonObject();\n this.messages = messages;\n }\n\n public List<String> getMessages() {\n return messages;\n }\n \n public List<String> getSuggestedResponses() {\n List<String> suggestions = new ArrayList();\n for (DialogTreeEdge edge : edges) {\n suggestions.add(edge.getPrompt());\n }\n return suggestions;\n }\n\n @Override\n public Iterable<DialogTreeEdge> getEdges() {\n return edges;\n }\n\n @Override\n public void addEdge(DialogTreeEdge edge) {\n edges.add(edge);\n }\n\n @Override\n public int getId() {\n return id;\n }\n\n @Override\n public JsonObject getMetadata() {\n return metadata;\n }\n \n \n\n}",
"public interface IConversationEdge<I extends IConversationIntent, S extends IConversationState> {\n\n public Integer getEndNodeId();\n \n public String getIntentId();\n \n /**\n * Additional logic to perform before continuing the conversation along this edge. It's possible for\n * a node to have multiple edges with the same intentId. Each edge could have different preconditions\n * that must be met in order to match. The validate function allows the engine to check the preconditions\n * against the current state and return true or false. If the edge intent matches but the validate\n * fails, the engine will look at the next edge with the same intent.\n * @param intent the intent from the current user input\n * @param state the current conversation sate\n * @return true if the edge should validate, false otherwise\n */\n public boolean validate(I intent, S state);\n \n /**\n * Side effects that should occur if this edge is validated. Side effects are\n * ways to change the state before the next step in the conversation. The type\n * of Object returned depends on the {@link Redux} {@link Middleware}s that are installed.\n * <p>\n * Side effects should be used to perform actions like loading additional data\n * from a web service or database that is required to respond to the user. The state\n * that is passed in should not be modified directly. Instead the list of actions\n * returned will be passed sequentially to the Redux middleware chain and executed in order.\n * @param intent the validated intent\n * @param state immutable copy of the state\n * @return a list of actions to perform before the next conversation step\n */\n public List<Object> getSideEffects(I intent, S state);\n}",
"public interface IConversationNode<E extends IConversationEdge> {\n\n /**\n * Returns a list of outbound edges from the current node. One matching \n * edge may be chosen to continue the conversation to the next node.\n * @return outbound edges\n */\n public Iterable<E> getEdges();\n\n /**\n * Adds an edge to the list of possible outbound edges.\n * @param edge edge to add\n */\n public void addEdge(E edge);\n\n /**\n * Returns the unique identifier for this node.\n * @return the node id\n */\n public int getId();\n \n /**\n * Node metadata is any additional information the node may\n * need to build platform-specific implementations of itself. The values stored\n * in the metadata will be highly dependent on the final use case and is\n * designed to be highly flexible. \n * @return JSON metadata\n */\n public JsonObject getMetadata();\n \n}",
"public interface ConversationNodeRepository <N extends IConversationNode>{\n public N getNodeById(int id);\n}"
] | import com.conversationkit.model.IConversationEdge;
import com.conversationkit.model.IConversationNode;
import com.conversationkit.model.ConversationNodeRepository;
import java.io.IOException;
import java.io.Reader;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import com.eclipsesource.json.Json;
import com.eclipsesource.json.JsonArray;
import com.eclipsesource.json.JsonObject;
import com.eclipsesource.json.JsonValue;
import com.conversationkit.impl.MapBackedNodeRepository;
import com.conversationkit.impl.edge.ConversationEdge;
import com.conversationkit.impl.node.DialogTreeNode; | /*
* The MIT License
*
* Copyright 2016 Synclab Consulting LLC.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.conversationkit.builder;
/**
* I/O class for loading a node index from a JSON file.
*
* @author pdtyreus
* @see <a href="http://jsongraphformat.info/">JSON Graph Format</a>
*/
public class JsonGraphBuilder {
private static final Logger logger = Logger.getLogger(JsonGraphBuilder.class.getName());
/**
* A default implementation of JsonNodeBuilder.
*/
public static final JsonNodeBuilder DEFAULT_NODE_BUILDER = (Integer id, String type, JsonObject metadata) -> {
List<String> messages = new ArrayList();
if (metadata.get("message") != null) {
if (metadata.get("message").isArray()) {
for (JsonValue node : metadata.get("message").asArray()) {
messages.add(node.asString());
}
} else {
messages.add(metadata.get("message").asString());
}
} else {
throw new IOException("No \"message\" metadata for node " + id);
}
//make the node into something | IConversationNode conversationNode = new DialogTreeNode(id, messages); | 4 |
lanrat/CrossFitr | src/com/vorsk/crossfitr/ResultsActivity.java | [
"public class AchievementModel extends SQLiteDAO\r\n{\r\n\t//// Constants\r\n\t\r\n\t// Table-specific columns\r\n\tpublic static final String COL_NAME = \"name\";\r\n\tpublic static final String COL_DESC = \"description\";\r\n\tpublic static final String COL_ACH_TYPE = \"achievement_type_id\";\r\n\tpublic static final String COL_THRESH = \"progress_thresh\";\r\n\tpublic static final String COL_PROG = \"progress\";\r\n\tpublic static final String COL_COUNT = \"count\";\r\n\t\r\n\t\r\n\t/***** Constructors *****/\r\n\t\r\n\t/**\r\n\t * Init SQLiteDAO with table \"Achievement\"\r\n\t * \r\n\t * @param ctx In the example they passed \"this\" from the calling class..\r\n\t * I'm not really sure what this is yet.\r\n\t */\r\n\tpublic AchievementModel(Context ctx)\r\n\t{\r\n\t\tsuper(\"achievement\", ctx);\r\n\t}\r\n\t\r\n\t/***** Private *****/\r\n\t\r\n\t/**\r\n\t * Utility method to grab all the rows from a cursor\r\n\t * \r\n\t * @param cr result of a query\r\n\t * @return Array of entries\r\n\t */\r\n\tprivate AchievementRow[] fetchAchievementRows(Cursor cr)\r\n\t{\r\n\t\tif (cr == null) {\r\n\t\t\treturn null;\r\n\t\t}\r\n\t\tAchievementRow[] result = new AchievementRow[cr.getCount()];\r\n\t\tif (result.length == 0) {\r\n\t\t\tcr.close();\r\n\t\t\treturn result;\r\n\t\t}\r\n\t\t\r\n\t\tboolean valid = cr.moveToFirst();\r\n\t\tint ii = 0;\r\n\t\t\r\n\t\t// Grab the cursor's column indices\r\n\t\t// An error here indicates the COL constants aren't synced with the DB\r\n\t\tint ind_id = cr.getColumnIndexOrThrow(COL_ID);\r\n\t\tint ind_name = cr.getColumnIndexOrThrow(COL_NAME);\r\n\t\tint ind_desc = cr.getColumnIndexOrThrow(COL_DESC);\r\n\t\tint ind_atid = cr.getColumnIndexOrThrow(COL_ACH_TYPE);\r\n\t\tint ind_thres = cr.getColumnIndexOrThrow(COL_THRESH);\r\n\t\tint ind_prog = cr.getColumnIndexOrThrow(COL_PROG);\r\n\t\tint ind_cnt = cr.getColumnIndexOrThrow(COL_COUNT);\r\n\t\tint ind_dm = cr.getColumnIndexOrThrow(COL_MDATE);\r\n\t\tint ind_dc = cr.getColumnIndexOrThrow(COL_CDATE);\r\n\t\t\r\n\t\t// Iterate over every row (move the cursor down the set)\r\n\t\twhile (valid) {\r\n\t\t\tresult[ii] = new AchievementRow();\r\n\t\t\tfetchBaseData(cr, result[ii], ind_id, ind_dm, ind_dc);\r\n\t\t\tresult[ii].name = cr.getString(ind_name);\r\n\t\t\tresult[ii].description = cr.getString(ind_desc);\r\n\t\t\tresult[ii].achievement_type_id = cr.getLong(ind_atid);\r\n\t\t\tresult[ii].progress_thresh = cr.getInt(ind_thres);\r\n\t\t\tresult[ii].progress = cr.getInt(ind_prog);\r\n\t\t\tresult[ii].count = cr.getInt(ind_cnt);\r\n\t\t\r\n\t\t\tvalid = cr.moveToNext();\r\n\t\t\tii ++;\r\n\t\t}\r\n\r\n\t\tcr.close();\r\n\t\treturn result;\r\n\t}\r\n\t\r\n\t/***** Public *****/\r\n\t\r\n\t/**\r\n\t * Inserts a new entry into the workout table\r\n\t * \r\n\t * @param row Add this entry to the DB\r\n\t * @return ID of newly added entry, -1 on failure\r\n\t */\r\n\tpublic long insert(AchievementRow row)\r\n\t{\r\n\t\treturn super.insert(row.toContentValues());\r\n\t}\r\n\t\r\n\t/**\r\n\t * Inserts a new entry into the achievement table, defaults record to 0\r\n\t * \r\n\t * @param name\r\n\t * @param description\r\n\t * @param achievement_type Type of the achievement.. TODO\r\n\t * @param threshold Limit of the progress before awarded\r\n\t * @param progress Progress towards getting this\r\n\t * @param count number of times this was earned\r\n\t * @return ID of newly added entry, -1 on failure\r\n\t */\r\n\tpublic long insert(String name, String description, long achievement_type,\r\n\t\t\tint threshold, int progress, int count)\r\n\t{\r\n\t\tContentValues cv = new ContentValues();\r\n\t\tcv.put(COL_NAME, name);\r\n\t\tcv.put(COL_DESC, description);\r\n\t\tcv.put(COL_ACH_TYPE, achievement_type);\r\n\t\tcv.put(COL_THRESH, threshold);\r\n\t\tcv.put(COL_PROG, progress);\r\n\t\tcv.put(COL_COUNT, count);\r\n\t\treturn super.insert(cv);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Attempts to update a previously entered achievement. If the update fails,\r\n\t * or the achievement has not yet passed the threshold it returns null. If it \r\n\t * has passed the threshold it will return the description for a display toast.\r\n\t * \r\n\t * @param achievementType\r\n\t * Type of achievement to update\r\n\t * @return AchievementRow containing achievement if threshold\r\n\t * \t\t is passed, null if not, or failed.\r\n\t */\r\n\tpublic String getProgress(int achievementType) {\r\n\t\tAchievementRow[] achievement;\r\n\t\t\r\n\t\t// Check if the all workout achievements need to be updated.\n\t\tif(achievementType == AchievementModel.TYPE_HERO || achievementType == AchievementModel.TYPE_GIRL){\r\n\t\t\tAchievementRow[] all = this.getAllByType(AchievementModel.TYPE_ALL);\n\t\t\tAchievementRow[] other = this.getAllByType(achievementType);\r\n\t\t\tachievement = new AchievementRow[all.length + other.length];\r\n\t\t\tSystem.arraycopy(all, 0, achievement, 0, all.length);\r\n\t\t\tSystem.arraycopy(other, 0, achievement, all.length, other.length);\r\n\t\t}\r\n\t\telse{\r\n\t\t\tachievement = this.getAllByType(achievementType);\r\n\t\t}\r\n\t\t\r\n\t\tContentValues cv;\r\n\t\tString totalAchievement = null;\r\n\t\t\r\n\t\tfor(int i = 0; i < achievement.length; i++)\r\n\t\t{\r\n\t\t\tcv = new ContentValues();\r\n\t\t\tcv.put(COL_NAME, achievement[i].name);\r\n\t\t\r\n\t\t\t// Increment progress of achievement\r\n\t\t\tint newProgress = achievement[i].progress;\r\n\t\t\tnewProgress += 1;\r\n\t\t\tcv.put(COL_PROG, newProgress);\r\n\t\t\t\r\n\t\r\n\t\t\t\r\n\t\t\t// If the progress has passed the threshold, update the count\r\n\t\t\t// and return the name of the achievement\r\n\t\t\tif(newProgress >= (achievement[i].progress_thresh) &&\r\n\t\t\t achievement[i].count == 0){\r\n\t\t\t\tcv.put(COL_COUNT, 1);\r\n\t\t\t\tsuper.update(cv, \"name='\" + achievement[i].name + \"'\");\r\n\t\t\t\tif(totalAchievement == null){\r\n\t\t\t\t\ttotalAchievement = \"Achievement Earned: \" + achievement[i].name;\r\n\t\t\t\t}\r\n\t\t\t\telse{\r\n\t\t\t\ttotalAchievement += \"\\nAchievement Earned: \" + achievement[i].name;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse{\r\n\t\t\t\tsuper.update(cv, \"name='\" + achievement[i].name + \"'\");\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn totalAchievement;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Gets the total number of achievements earned\r\n\t * \r\n\t * @return Total achievements\r\n\t */\r\n\tpublic int getTotal()\r\n\t{\r\n\t\tString[] count = new String[1];\r\n\t\tcount[0] = \"count\";\r\n\t\tString[] one = new String[1];\r\n\t\tone[0] = \"1\";\r\n\t\treturn selectCount(count, one);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Fetch all achievements of a specific type (girl, hero, custom, all)\r\n\t * \r\n\t * @param type The achievement type; use constants (TYPE_GIRL, etc)\r\n\t * @return array of achievements, null on failure\r\n\t */\r\n\tpublic AchievementRow[] getAllByType(int type)\r\n\t{\r\n\t\tString[] col = { COL_ACH_TYPE };\r\n\t\tString[] val = { String.valueOf(type) };\r\n\t\tCursor cr = select(col, val);\r\n\t\treturn fetchAchievementRows(cr);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Fetch all achievements\r\n\t * \r\n\t * @return List of each profile attribute and value\r\n\t */\r\n\tpublic AchievementRow[] getAll() {\r\n\t\tCursor cr = select(new String[] {}, new String[] {});\r\n\r\n\t\treturn fetchAchievementRows(cr);\r\n\t}\r\n\t/**\r\n\t * Fetch a specific achievement by name\r\n\t * \r\n\t * @param name\r\n\t * Achievement name to retrieve\r\n\t * @return Associated entry or NULL on failure\r\n\t */\r\n\tpublic AchievementRow getByName(String name) {\r\n\t\tCursor cr = select(new String[] { COL_NAME }, new String[] { name});\r\n\r\n\t\t// Name should be unique\r\n\t\t/*\r\n\t\t * if (cr.getCount() > 1) { // TODO: Throw exception? }\r\n\t\t */\r\n\r\n\t\tAchievementRow[] rows = fetchAchievementRows(cr);\r\n\t\treturn (rows.length == 0) ? null : rows[0];\r\n\t}\r\n\t\r\n\t/**\r\n\t * Fetch an entry via the ID\r\n\t * \r\n\t * @param id\r\n\t * @return Associated entry or NULL on failure\r\n\t */\r\n\tpublic AchievementRow getByID(long id)\r\n\t{\r\n\t\tCursor cr = selectByID(id);\r\n\t\t\r\n\t\tif (cr.getCount() > 1) {\r\n\t\t\treturn null; // TODO: Throw exception\r\n\t\t}\r\n\t\t\r\n\t\tAchievementRow[] rows = fetchAchievementRows(cr);\r\n\t\treturn (rows.length == 0) ? null : rows[0];\r\n\t}\r\n}",
"public class WorkoutModel extends SQLiteDAO\n{\n\t//// Constants\n\t\n\t// Table-specific columns\n\tpublic static final String COL_WK_TYPE = \"workout_type_id\";\n\tpublic static final String COL_RECORD = \"record\";\n\tpublic static final String COL_REC_TYPE = \"record_type_id\";\n\t\n\tprivate Context context;\n\t\t\n\t\n\t/***** Constructors *****/\n\t\n\t/**\n\t * Init SQLiteDAO with table \"workout\"\n\t * \n\t * @param ctx In the example they passed \"this\" from the calling class..\n\t * I'm not really sure what this is yet.\n\t */\n\tpublic WorkoutModel(Context ctx)\n\t{\n\t\tsuper(\"workout\", ctx);\n\t\tcontext = ctx;\n\t}\n\t\n\t/***** Private *****/\n\t\n\t/**\n\t * Utility method to grab all the rows from a cursor\n\t * \n\t * @param cr result of a query\n\t * @return Array of entries\n\t */\n\tprivate WorkoutRow[] fetchWorkoutRows(Cursor cr)\n\t{\n\t\tif (cr == null) {\n\t\t\treturn null;\n\t\t}\n\t\tWorkoutRow[] result = new WorkoutRow[cr.getCount()];\n\t\tif (result.length == 0) {\n\t\t\tcr.close();\n\t\t\treturn result;\n\t\t}\n\t\t\n\t\tboolean valid = cr.moveToFirst();\n\t\tint ii = 0;\n\t\t\n\t\t// Grab the cursor's column indices\n\t\t// An error here indicates the COL constants aren't synced with the DB\n\t\tint ind_id = cr.getColumnIndexOrThrow(COL_ID);\n\t\tint ind_name = cr.getColumnIndexOrThrow(COL_NAME);\n\t\tint ind_desc = cr.getColumnIndexOrThrow(COL_DESC);\n\t\tint ind_wtid = cr.getColumnIndexOrThrow(COL_WK_TYPE);\n\t\tint ind_rec = cr.getColumnIndexOrThrow(COL_RECORD);\n\t\tint ind_rtid = cr.getColumnIndexOrThrow(COL_REC_TYPE);\n\t\tint ind_dm = cr.getColumnIndexOrThrow(COL_MDATE);\n\t\tint ind_dc = cr.getColumnIndexOrThrow(COL_CDATE);\n\t\t\n\t\t// Iterate over every row (move the cursor down the set)\n\t\twhile (valid) {\n\t\t\tresult[ii] = new WorkoutRow();\n\t\t\tfetchBaseData(cr, result[ii], ind_id, ind_dm, ind_dc);\n\t\t\tresult[ii].name = cr.getString(ind_name);\n\t\t\tresult[ii].description = cr.getString(ind_desc);\n\t\t\tresult[ii].workout_type_id = cr.getLong(ind_wtid);\n\t\t\tresult[ii].record = cr.getInt(ind_rec);\n\t\t\tresult[ii].record_type_id = cr.getLong(ind_rtid);\n\n\t\t\tvalid = cr.moveToNext();\n\t\t\tii++;\n\t\t}\n\t\t\n\t\tcr.close();\n\t\treturn result;\n\t}\n\t\n\t/***** Public *****/\n\t\n\t/**\n\t * Inserts a new entry into the workout table\n\t * TODO: does not work, violates unknown constraint\n\t * @param row\n\t * Add this entry to the DB\n\t * @return ID of newly added entry, -1 on failure\n\t */\n\tpublic long insert(WorkoutRow row)\n\t{\n\t\t// TODO: Fix this? Seemed to be funky\n\t\treturn super.insert(row.toContentValues());\n\t}\n\n\t/**\n\t * Inserts a new entry into the workout table, defaults record to 0\n\t * \n\t * @param name\n\t * @param desc\n\t * @param type Type of the workout (this.TYPE_GIRL, etc)\n\t * @param rec_type Type of scoring used (this.SCORE_TIME, etc)\n\t * @return ID of newly added entry, -1 on failure\n\t */\n\tpublic long insert(String name, String desc, int type, int rec_type) {\n\t\t// Default COL_RECORD to NOT_SCORED\n\t\treturn insert(name, desc, type, rec_type, NOT_SCORED);\n\t}\n\n\t/**\n\t * Inserts a new entry into the workout table\n\t * \n\t * @param name\n\t * @param desc\n\t * @param type Type of the workout (this.TYPE_GIRL, etc)\n\t * @param rec_type Type of scoring used (this.SCORE_TIME, etc)\n\t * @param record Best score received on this workout or this.NOT_SCORED\n\t * @return ID of newly added entry, -1 on failure\n\t */\n\tpublic long insert(String name, String desc, int type, int rec_type,\n\t int record)\n\t{\n\t\tInteger wtype = (type == TYPE_NONE) ? null : type;\n\t\tInteger rtype = (rec_type == SCORE_NONE) ? null : rec_type;\n\t\tInteger rec = (record == NOT_SCORED) ? null : record;\n\t\t\n\t\tContentValues cv = new ContentValues();\n\t\tcv.put(COL_NAME, name);\n\t\tcv.put(COL_DESC, desc);\n\t\tcv.put(COL_WK_TYPE, wtype);\n\t\tcv.put(COL_REC_TYPE, rtype);\n\t\tcv.put(COL_RECORD, rec);\n\t\treturn super.insert(cv);\n\t}\n\t\n\t/**\n\t * Call this to edit the properties of a workout entry\n\t * \n\t * @param row The new data to replace\n\t * @return Number of rows affected\n\t */\n\tpublic long edit(WorkoutRow row)\n\t{\n\t\treturn super.update(row.toContentValues(), COL_ID + \" = \" + row._id);\n\t}\n\t\n\t/**\n\t * Remove a workout definition. History for it will be removed\n\t * \n\t * @param id Workout definition ID to remove\n\t * @return Number of removed workouts\n\t */\n\tpublic long delete(long id)\n\t{\n\t\tWorkoutSessionModel model = new WorkoutSessionModel(context);\n\t\tmodel.deleteWorkoutHistory(id);\n\t\treturn super.delete(COL_ID + \" = \" + id);\n\t}\n\t\n\t/**\n\t * Recalculates the best record from existing sessions\n\t * \n\t * @param id Workout ID to recalculate\n\t * @param type Type of the Workout ID\n\t * @return Number of rows updated; -1 or 0 on failure\n\t */\n\tpublic int calculateRecord(long id, long type)\n\t{\n\t\tString cond;\n\t\tif (type == SCORE_TIME) {\n\t\t\tcond = \"MIN\";\n\t\t} else if (type == SCORE_WEIGHT || type == SCORE_REPS) {\n\t\t\tcond = \"MAX\";\n\t\t} else {\n\t\t\treturn -1;\n\t\t}\n\t\t\n\t\tWorkoutSessionModel model = new WorkoutSessionModel(context);\n\t\tContentValues cv = new ContentValues();\n\t\tcv.put(COL_RECORD, model.getWorkoutAggScore(id, cond));\n\t\t\n\t\treturn update(cv, COL_ID + \"=\" + id);\n\t}\n\n\t/**\n\t * Fetch an entry via the ID\n\t * \n\t * @param id\n\t * @return Associated entry or NULL on failure\n\t */\n\tpublic WorkoutRow getByID(long id)\n\t{\n\t\tCursor cr = selectByID(id);\n\n\t\tif (cr == null || cr.getCount() > 1) {\n\t\t\treturn null; // TODO: Throw exception\n\t\t}\n\n\t\tWorkoutRow[] rows = fetchWorkoutRows(cr);\n\t\treturn (rows.length == 0) ? null : rows[0];\n\t}\n\t\n\t/**\n\t * Finds a workout matching a given name\n\t * \n\t * @param name the name to search for\n\t * @return the row id containing that workout, -1 on failure;\n\t */\n\tpublic long getIDFromName(String name)\n\t{\n\t\treturn super.selectIDByName(DB_TABLE, name);\n\t}\n\n\t/**\n\t * Fetch all workouts of a specific type (girl, hero, custom, wod)\n\t * \n\t * @param type The workout type; use constants (TYPE_GIRL, etc)\n\t * @return array of workouts, null on failure\n\t */\n\tpublic WorkoutRow[] getAllByType(int type)\n\t{\n\t\tString[] col = { COL_WK_TYPE };\n\t\tString[] val = { String.valueOf(type) };\n\t\tCursor cr = select(col, val);\n\t\treturn fetchWorkoutRows(cr);\n\t}\n\t\n\t/**\n\t * Gets a workout_type's ID by its name\n\t * \n\t * @param name\n\t * @return ID of the workout type, -1 on failure\n\t */\n\tpublic long getTypeID(String name)\n\t{\n\t\treturn selectIDByName(\"workout_type\", name);\n\t}\n\t\n\t/**\n\t * Gets a workout_type's name by its ID\n\t * \n\t * @param id\n\t * @return name of the workout type, NULL on failure\n\t */\n\tpublic String getTypeName(long id)\n\t{\n\t\treturn selectNameByID(\"workout_type\", id);\n\t}\n\n}",
"public class WorkoutRow extends SQLiteRow\r\n{\r\n\t// Cols\r\n\tpublic String name;\r\n\tpublic String description;\r\n\tpublic long workout_type_id;\r\n\tpublic int record;\r\n\tpublic long record_type_id;\r\n\t\r\n\tpublic WorkoutRow() {}\r\n\t\r\n\tpublic WorkoutRow(ContentValues vals)\r\n\t{\r\n\t\tsuper(vals);\r\n\t\tname = vals.getAsString(SQLiteDAO.COL_NAME);\r\n\t\tdescription = vals.getAsString(SQLiteDAO.COL_DESC);\r\n\t\tworkout_type_id = vals.getAsLong(WorkoutModel.COL_WK_TYPE);\r\n\t\trecord = vals.getAsInteger(WorkoutModel.COL_RECORD);\r\n\t\trecord_type_id = vals.getAsLong(WorkoutModel.COL_REC_TYPE);\r\n\t}\r\n\r\n\t@Override\r\n\tpublic ContentValues toContentValues()\r\n\t{\r\n\t\tContentValues vals = super.toContentValues();\r\n\t\tvals.put(SQLiteDAO.COL_NAME, name);\r\n\t\tvals.put(SQLiteDAO.COL_DESC, description);\r\n\t\tvals.put(WorkoutModel.COL_WK_TYPE, workout_type_id);\r\n\t\tvals.put(WorkoutModel.COL_RECORD, record);\r\n\t\tvals.put(WorkoutModel.COL_REC_TYPE, record_type_id);\r\n\t\treturn vals;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Returns the String to represent the row item\r\n\t */\r\n\t@Override\r\n\tpublic String toString()\r\n\t{\r\n\t\treturn this.name;\r\n\t}\r\n\t\r\n\t/**\r\n\t * returns the hashcode for the object\r\n\t */\r\n\t\r\n\tpublic void setName( String name )\r\n\t{\r\n\t\tthis.name = name;\r\n\t}\r\n\t\r\n\tpublic void setDes( String des)\r\n\t{\r\n\t\tthis.description = des;\r\n\t}\r\n\t\r\n\tpublic void setRecord( int record )\r\n\t{\r\n\t\tthis.record = record;\r\n\t}\r\n\t@Override\r\n\tpublic int hashCode(){\r\n\t\treturn name.hashCode();\r\n\t}\r\n\t\r\n\t/** \r\n\t * check name of Workout to determine if equal\r\n\t */\r\n\t@Override\r\n\tpublic boolean equals(Object obj){\r\n if (obj.getClass() == getClass()){\r\n return this.name.equals(((WorkoutRow)obj).name);\r\n }\r\n\t\treturn false;\r\n\t}\r\n\r\n}",
"public class WorkoutSessionModel extends SQLiteDAO\r\n{\r\n\t//// Constants\r\n\t\r\n\t// Table-specific columns\r\n\tpublic static final String COL_WORKOUT = \"workout_id\";\r\n\tpublic static final String COL_SCORE = \"score\";\r\n\tpublic static final String COL_SCORE_TYPE = \"score_type_id\";\r\n\tpublic static final String COL_CMNT = \"comments\";\r\n\t\r\n\tprivate Context context;\r\n\t\r\n\t\r\n\t/***** Constructors *****/\r\n\t\r\n\t/**\r\n\t * Init SQLiteDAO with table \"workout_session\"\r\n\t * \r\n\t * @param ctx In the example they passed \"this\" from the calling class..\r\n\t * I'm not really sure what this is yet.\r\n\t */\r\n\tpublic WorkoutSessionModel(Context ctx)\r\n\t{\r\n\t\tsuper(\"workout_session\", ctx);\r\n\t\tcontext = ctx;\r\n\t}\r\n\t\r\n\t/***** Private *****/\r\n\t\r\n\t/**\r\n\t * Utility method to grab all the rows from a cursor\r\n\t * \r\n\t * @param cr result of a query\r\n\t * @return Array of entries\r\n\t */\r\n\tprivate WorkoutSessionRow[] fetchWorkoutSessionRows(Cursor cr)\r\n\t{\r\n\t\tif (cr == null) {\r\n\t\t\treturn null;\r\n\t\t}\r\n\t\tWorkoutSessionRow[] result = new WorkoutSessionRow[cr.getCount()];\r\n\t\tif (result.length == 0) {\r\n\t\t\tcr.close();\r\n\t\t\treturn result;\r\n\t\t}\r\n\t\t\r\n\t\tboolean valid = cr.moveToFirst();\r\n\t\tint ii = 0;\r\n\t\t\r\n\t\t// Grab the cursor's column indices\r\n\t\t// An error here indicates the COL constants aren't synced with the DB\r\n\t\tint ind_id = cr.getColumnIndexOrThrow(COL_ID);\r\n\t\tint ind_wid = cr.getColumnIndexOrThrow(COL_WORKOUT);\r\n\t\tint ind_score = cr.getColumnIndexOrThrow(COL_SCORE);\r\n\t\tint ind_stid = cr.getColumnIndexOrThrow(COL_SCORE_TYPE);\r\n\t\tint ind_dm = cr.getColumnIndexOrThrow(COL_MDATE);\r\n\t\tint ind_dc = cr.getColumnIndexOrThrow(COL_CDATE);\r\n\t\tint ind_cmnt = cr.getColumnIndexOrThrow(COL_CMNT);\r\n\t\t\r\n\t\t// Iterate over every row (move the cursor down the set)\r\n\t\twhile (valid) {\r\n\t\t\tresult[ii] = new WorkoutSessionRow();\r\n\t\t\tfetchBaseData(cr, result[ii], ind_id, ind_dm, ind_dc);\r\n\t\t\tresult[ii].workout_id = cr.getLong(ind_wid);\r\n\t\t\tresult[ii].score = cr.getInt(ind_score);\r\n\t\t\tresult[ii].score_type_id = cr.getLong(ind_stid);\r\n\t\t\tresult[ii].comments = cr.getString(ind_cmnt);\r\n\t\t\r\n\t\t\tvalid = cr.moveToNext();\r\n\t\t\tii ++;\r\n\t\t}\r\n\t\t\r\n\t\tcr.close();\r\n\t\treturn result;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Update the workout entry to reflect the new record\r\n\t * \r\n\t * @param workout_id ID of the workout\r\n\t * @param score The new session's score\r\n\t */\r\n\tprivate void checkUpdateRecord(long workout_id, int score)\r\n\t{\r\n\t\tWorkoutModel model = new WorkoutModel(context);\r\n\t\tWorkoutRow workout = model.getByID(workout_id);\r\n\t\tboolean update = false;\r\n\r\n\t\t// Check if this session is the new best record\r\n\t\tswitch ((int)workout.record_type_id) {\r\n\t\tcase SCORE_TIME:\r\n\t\t\tif (workout.record == 0 || score < workout.record) {\r\n\t\t\t\tworkout.record = score;\r\n\t\t\t\tupdate = true;\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\tcase SCORE_REPS:\r\n\t\tcase SCORE_WEIGHT:\r\n\t\t\tif (workout.record == 0 || score > workout.record) {\r\n\t\t\t\tworkout.record = score;\r\n\t\t\t\tupdate = true;\r\n\t\t\t}\r\n\t\t\tbreak;\r\n\t\t}\r\n\t\t\r\n\t\t// If so, update the workout\r\n\t\tif (update) {\r\n\t\t\tmodel.edit(workout);\r\n\t\t}\r\n\t}\r\n\t\r\n\t/***** Public *****/\r\n\t\r\n\t/**\r\n\t * Inserts a new entry into the workout table\r\n\t * \r\n\t * @param row Add this entry to the DB\r\n\t * @return ID of newly added entry, -1 on failure\r\n\t */\r\n\tpublic long insert(WorkoutSessionRow row)\r\n\t{\r\n\t\tcheckUpdateRecord(row.workout_id, row.score);\r\n\t\t// Insert this entry\r\n\t\treturn super.insert(row.toContentValues());\r\n\t}\r\n\t\r\n\t/**\r\n\t * Inserts a new entry into the workout table, defaults record to 0\r\n\t * \r\n\t * @param workout ID of the workout performed this session\r\n\t * @param score The entry's score (time, reps, etc) or this.NOT_SCORED\r\n\t * @param score_type Type of the score (this.SCORE_TIME, etc) or\r\n\t * this.SCORE_NONE if no score is recorded\r\n\t * @return ID of newly added entry, -1 on failure\r\n\t */\r\n\tpublic long insert(long workout, long score, long score_type)\r\n\t{\r\n\t\tInteger isc = (score == NOT_SCORED) ? null : (int)score;\r\n\t\tLong ist = (score_type == SCORE_NONE) ? null : score_type;\r\n\t\t\r\n\t\tif (isc != null) {\r\n\t\t\tcheckUpdateRecord(workout, isc);\r\n\t\t}\r\n\t\tContentValues cv = new ContentValues();\r\n\t\tcv.put(COL_WORKOUT, workout);\r\n\t\tcv.put(COL_SCORE, isc);\r\n\t\tcv.put(COL_SCORE_TYPE, ist);\r\n\t\treturn super.insert(cv);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Change the comment of a session\r\n\t * \r\n\t * @param id ID of the comment to edit\r\n\t * @param comment New comment; overwrites existing comment\r\n\t * @return 1 on success, -1 on failure, 0 if invalid ID\r\n\t */\r\n\tpublic int editComment(long id, String comment)\r\n\t{\r\n\t\tif (comment == null) comment = \"\";\r\n\t\t\r\n\t\tContentValues cv = new ContentValues();\r\n\t\tcv.put(COL_CMNT, comment);\r\n\t\treturn super.update(cv, COL_ID + \" = \" + id);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Removes all sessions of a particular workout\r\n\t * \r\n\t * @param id ID of the workout whose history to remove\r\n\t * @return Number of sessions removed\r\n\t */\r\n\tpublic int deleteWorkoutHistory(long id)\r\n\t{\r\n\t\treturn super.delete(COL_WORKOUT + \" = \" + id);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Remove a previously created session\r\n\t * \r\n\t * Currently used by ResultsActivity is you don't want to save. This\r\n\t * should be cleaned up so this method can be removed.\r\n\t * \r\n\t * @param id session_id to delete\r\n\t * @return result of deletion, -1 on failure\r\n\t */\r\n\tpublic int delete(long id)\r\n\t{\r\n\t\tWorkoutModel model = new WorkoutModel(context);\r\n\t\tWorkoutSessionRow session = getByID(id);\r\n\t\tif (session == null) {\r\n\t\t\treturn 0;\r\n\t\t}\r\n\t\tWorkoutRow workout = model.getByID(session.workout_id);\r\n\t\t\r\n\t\tint result = super.delete(COL_ID + \" = \" + id);\r\n\t\t\r\n\t\tif (workout.record == session.score) {\r\n\t\t\tmodel.calculateRecord(workout._id, workout.record_type_id);\r\n\t\t}\r\n\r\n\t\treturn result;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Fetch an entry via the ID\r\n\t * \r\n\t * @param id\r\n\t * @return Associated entry or NULL on failure\r\n\t */\r\n\tpublic WorkoutSessionRow getByID(long id)\r\n\t{\r\n\t\tCursor cr = selectByID(id);\r\n\t\t\r\n\t\tif (cr.getCount() > 1) {\r\n\t\t\treturn null; // TODO: Throw exception\r\n\t\t}\r\n\t\t\r\n\t\tWorkoutSessionRow[] rows = fetchWorkoutSessionRows(cr);\r\n\t\treturn (rows.length == 0) ? null : rows[0];\r\n\t}\r\n\t\r\n\t/**\r\n\t * Fetch all workouts within a given time period\r\n\t *\r\n\t * @param mintime Beginning time of interval (unix timestamp)\r\n\t * @param maxtime End time of interval (unix timestamp)\r\n\t * @return Sessions within the time period; NULL on failure\r\n\t */\r\n\tpublic WorkoutSessionRow[] getByTime(long mintime, long maxtime)\r\n\t{\r\n\t\tString sql = \"SELECT * FROM \" + DB_TABLE + \" WHERE \"\n\t\t\t+ COL_CDATE + \"> ? AND \" + COL_CDATE + \"< ?\";\r\n\t\t\r\n\t\tCursor cr = db.rawQuery(sql, new String[] {\r\n\t\t\tLong.toString(mintime), Long.toString(maxtime)\r\n\t\t});\n\t\treturn fetchWorkoutSessionRows(cr);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Fetch all workouts within a given time period of a given type\r\n\t *\r\n\t * @param mintime Beginning time of interval (unix timestamp)\r\n\t * @param maxtime End time of interval (unix timestamp)\r\n\t * @param type Workout type; use constants (TYPE_GIRL, etc)\r\n\t */\r\n\tpublic WorkoutSessionRow[] getByTime(long mintime, long maxtime, int type)\r\n\t{\r\n\t\tString sql = \"SELECT * FROM \" + DB_TABLE + \" ws WHERE \"\r\n\t\t\t+ COL_CDATE + \"> ? AND \" + COL_CDATE + \"< ? AND \"\r\n\t\t\t+ \"(SELECT \" + WorkoutModel.COL_WK_TYPE + \" FROM workout WHERE \"\r\n\t\t\t+ COL_ID + \"=ws.\" + COL_WORKOUT + \") = ?\";\r\n\t\t\r\n\t\tCursor cr = db.rawQuery(sql, new String[] {\r\n\t\t\t\tString.valueOf(mintime),\r\n\t\t\t\tString.valueOf(maxtime), \r\n\t\t\t\tString.valueOf(type)\r\n\t\t});\r\n\t\treturn fetchWorkoutSessionRows(cr);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Fetch all workout sessions by type\r\n\t *\r\n\t * @param type Workout type; use constants (TYPE_GIRL, etc)\r\n\t * @return Sessions of that workout type; null on failure\r\n\t */\r\n\tpublic WorkoutSessionRow[] getByType(int type)\r\n\t{\r\n\t\tString sql = \"SELECT * FROM \" + DB_TABLE + \" ws WHERE \"\r\n\t\t\t+ \"(SELECT \" + WorkoutModel.COL_WK_TYPE + \" FROM workout WHERE \"\r\n\t\t\t+ COL_ID + \"=ws.\" + COL_WORKOUT + \") = ?\";\r\n\t\t\r\n\t\tCursor cr = db.rawQuery(sql, new String[] { String.valueOf(type) });\r\n\t\treturn fetchWorkoutSessionRows(cr);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Fetch sessions of a particular workout\r\n\t * \r\n\t * @param id ID of the workout; obtain from WorkoutModel\r\n\t * @return Sessions of that workout; null on failure\r\n\t */\r\n\tpublic WorkoutSessionRow[] getByWorkout(long id)\r\n\t{\r\n\t\tString col[] = { COL_WORKOUT };\r\n\t\tString val[] = { String.valueOf(id) };\r\n\t\tCursor cr = select(col, val);\r\n\t\treturn fetchWorkoutSessionRows(cr);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Gets the total number of sessions performed\r\n\t * \r\n\t * @return Total sessions\r\n\t */\r\n\tpublic int getTotal()\r\n\t{\r\n\t\treturn selectCount(null, null);\r\n\t}\r\n\t\r\n\t/**\r\n\t * Get the most recent session\r\n\t * \r\n\t * @type Workout type, or NULL to search all sessions\r\n\t * @return Most recently created session; NULL on failure\r\n\t */\r\n\tpublic WorkoutSessionRow getMostRecent(Integer type)\r\n\t{\r\n\t\tString[] col = (type == null) ? null : new String[1];\r\n\t\tString[] val = (type == null) ? null : new String[1];\r\n\t\t\r\n\t\tif (type != null) {\r\n\t\t\tcol[0] = WorkoutModel.COL_WK_TYPE;\r\n\t\t\tval[0] = type.toString();\r\n\t\t}\r\n\t\t\r\n\t\tString order = COL_CDATE + \" DESC\";\r\n\t\t\r\n\t\tCursor cr = select(col, val, order, 1);\r\n\t\t\r\n\t\tWorkoutSessionRow[] rows = fetchWorkoutSessionRows(cr);\r\n\t\tif (rows == null || rows.length < 1) {\r\n\t\t\treturn null;\r\n\t\t}\r\n\t\treturn rows[0];\r\n\t}\r\n\t\r\n\t/**\r\n\t * Gets an aggregate value of the scores for a workout\r\n\t * \r\n\t * @param id Workout ID to calculate the scores\r\n\t * @param agg Type of aggregation (MIN, MAX, COUNT)\r\n\t * @return Calculated value\r\n\t */\r\n\tpublic int getWorkoutAggScore(long id, String agg)\r\n\t{\r\n\t\tif (agg != \"MIN\" && agg != \"MAX\" && agg != \"COUNT\")\r\n\t\t\treturn -1;\r\n\t\tString sql = \"SELECT \" + agg + \"(\" + COL_SCORE + \") as agg FROM \"\r\n\t\t\t+ DB_TABLE + \" WHERE \" + COL_WORKOUT + \"=\" + id;\r\n\t\t\r\n\t\tCursor cr = db.rawQuery(sql, null);\r\n\t\tif (cr == null || !cr.moveToFirst()) {\r\n\t\t\treturn -1;\r\n\t\t}\r\n\t\t\r\n\t\tint result = cr.getInt(cr.getColumnIndexOrThrow(\"agg\"));\r\n\t\tcr.close();\r\n\t\treturn result;\r\n\t}\r\n\r\n}",
"public class WorkoutSessionRow extends SQLiteRow\r\n{\r\n\t// Cols\r\n\tpublic long workout_id;\r\n\tpublic int score;\r\n\tpublic long score_type_id;\r\n\tpublic String comments;\r\n\t\r\n\tpublic WorkoutSessionRow() {}\r\n\t\r\n\tpublic WorkoutSessionRow(ContentValues vals)\r\n\t{\r\n\t\tsuper(vals);\r\n\t\tworkout_id = vals.getAsLong(WorkoutSessionModel.COL_WORKOUT);\r\n\t\tscore = vals.getAsInteger(WorkoutSessionModel.COL_SCORE);\r\n\t\tscore_type_id = vals.getAsLong(WorkoutSessionModel.COL_SCORE_TYPE);\r\n\t\tcomments = vals.getAsString(WorkoutSessionModel.COL_CMNT);\r\n\t}\r\n\r\n\t@Override\r\n\tpublic ContentValues toContentValues()\r\n\t{\r\n\t\tContentValues vals = super.toContentValues();\r\n\t\tvals.put(WorkoutSessionModel.COL_WORKOUT, workout_id);\r\n\t\tvals.put(WorkoutSessionModel.COL_SCORE, score);\r\n\t\tvals.put(WorkoutSessionModel.COL_SCORE_TYPE, score_type_id);\r\n\t\tvals.put(WorkoutSessionModel.COL_CMNT, comments);\r\n\t\treturn vals;\r\n\t}\r\n}"
] | import com.vorsk.crossfitr.models.AchievementModel;
import com.vorsk.crossfitr.models.WorkoutModel;
import com.vorsk.crossfitr.models.WorkoutRow;
import com.vorsk.crossfitr.models.WorkoutSessionModel;
import com.vorsk.crossfitr.models.WorkoutSessionRow;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
| package com.vorsk.crossfitr;
/**
* Creates and displays the Results view after completing a workout.
*
* When invoking this activity, the caller must provide the relevant
* workout session ID via the Intent. The results will be displayed for
* this session.
*
* @requires Intent->session_id
* @author Vivek
*/
public class ResultsActivity extends Activity implements OnClickListener
{
private long session_id;
private EditText commentTextField;
private InputMethodManager keyControl;
private WorkoutRow workout;
private Typeface font, regFont;
TextView screenName, tvname, tvdesc, tvbestRecord, tvscore, commentField;
| AchievementModel achievementModel = new AchievementModel(this);
| 0 |
100rabhkr/DownZLibrary | downzlibrary/src/main/java/com/example/downzlibrary/RequestTasks/JsonObjectTask.java | [
"public class DownZ {\n private static DownZ instance = null;\n private Context context;\n private String url;\n private Method method;\n private ArrayList<RequestParams> params = new ArrayList<>();\n private ArrayList<HeaderParams> headers = new ArrayList<>();\n\n /**\n * Constructor\n *\n * @param c it is the context\n */\n public DownZ(Context c) {\n this.context = c;\n }\n\n public static DownZ from(Context c) {\n return getInstance(c);\n }\n\n /**\n * Returns singleton instance for network call\n *\n * @param context it is the context of activity\n */\n public static DownZ getInstance(Context context) {\n if (context == null)\n throw new NullPointerException(\"Error\");\n\n\n synchronized (DownZ.class) {\n if (instance == null)\n instance = new DownZ(context);\n }\n\n return instance;\n }\n\n /**\n * Assigns Url to be loaded\n *\n * @param m, url\n * @return instance\n */\n public DownZ load(Method m, String url) {\n this.url = url;\n this.method = m;\n return this;\n }\n\n /**\n * Sets json datatype for request\n *\n * @return Json Type\n */\n public JsonObject asJsonObject() {\n return new JsonObject(method, url, params, headers);\n }\n\n /**\n * Sets json datatype for request\n *\n * @return Json Array Type\n */\n public JsonArray asJsonArray() {\n return new JsonArray(method, url, params, headers);\n }\n\n /**\n * Sets bitmap type for request\n *\n * @return Bitmap Type\n */\n\n public BitMap asBitmap() {\n return new BitMap(method, url, params, headers);\n }\n\n public XmlType asXml() {\n return new XmlType(method, url, params, headers);\n }\n\n /**\n * Sets request body parameters\n *\n * @param key Parameter key\n * @param value Parameter value\n * @return DownZ instance\n */\n\n public DownZ setRequestParameter(String key, String value) {\n RequestParams pram = new RequestParams();\n pram.setKey(key);\n pram.setValue(value);\n this.params.add(pram);\n return this;\n }\n\n /**\n * Sets request header parameters\n *\n * @param key Parameter key\n * @param value Parameter value\n * @return DownZ instance\n */\n\n public DownZ setHeaderParameter(String key, String value) {\n HeaderParams pram = new HeaderParams();\n pram.setKey(key);\n pram.setValue(value);\n this.headers.add(pram);\n return this;\n }\n\n\n public static enum Method {\n GET,\n POST,\n PUT,\n DELETE\n }\n\n\n}",
"public interface HttpListener<T> {\n /**\n * callback starts\n */\n public void onRequest();\n\n /**\n * Callback that's fired after response\n *\n * @param data of the type T holds the response\n */\n public void onResponse(T data);\n\n public void onError();\n\n public void onCancel();\n}",
"public class HeaderParams {\n private String key;\n private String value;\n\n public String getKey() {\n return key;\n }\n\n public HeaderParams setKey(String key) {\n this.key = key;\n return this;\n }\n\n public String getValue() {\n return value;\n }\n\n public HeaderParams setValue(String value) {\n this.value = value;\n return this;\n }\n}",
"public class RequestParams {\n private String key;\n private String value;\n\n public String getKey() {\n return key;\n }\n\n public RequestParams setKey(String key) {\n this.key = key;\n return this;\n }\n\n public String getValue() {\n return value;\n }\n\n public RequestParams setValue(String value) {\n this.value = value;\n return this;\n }\n}",
"public class Response {\n private int code;\n private InputStream inputStream;\n\n public int getCode() {\n return code;\n }\n\n public Response setCode(int code) {\n this.code = code;\n return this;\n }\n\n public InputStream getData() {\n return inputStream;\n }\n\n public Response setData(InputStream data) {\n this.inputStream = data;\n return this;\n }\n\n /**\n * Reads an InputStream and converts it to a String.\n *\n * @return String\n * @throws IOException\n */\n public String getDataAsString() throws IOException {\n final int bufferSize = 1024;\n final char[] buffer = new char[bufferSize];\n final StringBuilder out = new StringBuilder();\n Reader in = new InputStreamReader(inputStream, \"UTF-8\");\n for (; ; ) {\n int i = in.read(buffer, 0, buffer.length);\n if (i < 0)\n break;\n out.append(buffer, 0, i);\n }\n if (inputStream != null) {\n inputStream.close();\n }\n return out.toString();\n\n }\n\n /**\n * Converts input Stream to bitmap\n *\n * @return Bitmap\n */\n public Bitmap getAsBitmap() {\n Bitmap bitmap = BitmapFactory.decodeStream(this.inputStream);\n if (inputStream != null) {\n try {\n inputStream.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n return bitmap;\n }\n\n}"
] | import com.example.downzlibrary.DownZ;
import com.example.downzlibrary.ListnerInterface.HttpListener;
import com.example.downzlibrary.Parameters.HeaderParams;
import com.example.downzlibrary.Parameters.RequestParams;
import com.example.downzlibrary.Response;
import org.json.JSONObject;
import java.util.ArrayList; | package com.example.downzlibrary.RequestTasks;
/**
* Created by saurabhkumar on 06/08/17.
*/
public class JsonObjectTask extends Task<String, Void, JSONObject> {
private DownZ.Method method;
private String mUrl;
private HttpListener<JSONObject> callback;
private boolean error = false;
private ArrayList<RequestParams> params;
private ArrayList<HeaderParams> headers;
public JsonObjectTask(DownZ.Method method, String url, ArrayList<RequestParams> params, ArrayList<HeaderParams> headers, HttpListener<JSONObject> callback) {
this.mUrl = url;
this.method = method;
this.callback = callback;
this.params = params;
this.headers = headers;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected JSONObject doInBackground(String... urls) {
try { | Response response = makeRequest(mUrl, method, params, headers); | 4 |
ground-context/ground | modules/postgres/app/edu/berkeley/ground/postgres/controllers/StructureController.java | [
"public class GroundException extends Exception {\n\n private static final long serialVersionUID = 1L;\n\n private final String message;\n private final ExceptionType exceptionType;\n\n public enum ExceptionType {\n DB(\"Database Exception:\", \"%s\"),\n ITEM_NOT_FOUND(\"GroundItemNotFoundException\", \"No %s \\'%s\\' found.\"),\n VERSION_NOT_FOUND(\"GroundVersionNotFoundException\", \"No %s \\'%s\\' found.\"),\n ITEM_ALREADY_EXISTS(\"GroundItemAlreadyExistsException\", \"%s %s already exists.\"),\n OTHER(\"GroundException\", \"%s\");\n\n String name;\n String description;\n\n ExceptionType(String name, String description) {\n this.name = name;\n this.description = description;\n }\n\n public String format(String... values) {\n return String.format(this.description, values);\n }\n }\n\n public GroundException(ExceptionType exceptionType, String... values) {\n this.exceptionType = exceptionType;\n this.message = this.exceptionType.format(values);\n }\n\n public GroundException(Exception exception) {\n this.exceptionType = ExceptionType.OTHER;\n this.message = this.exceptionType.format(exception.getMessage());\n }\n\n @Override\n public String getMessage() {\n return this.message;\n }\n\n public ExceptionType getExceptionType() {\n return this.exceptionType;\n }\n}",
"public class Structure extends Item {\n\n // the name of this Structure\n @JsonProperty(\"name\")\n private final String name;\n\n // the source key for this Node\n @JsonProperty(\"sourceKey\")\n private final String sourceKey;\n\n /**\n * Create a new structure.\n *\n * @param id the id of the structure\n * @param name the name of the structure\n * @param sourceKey the user-generated unique key for the structure\n * @param tags the tags associated with this structure\n */\n @JsonCreator\n public Structure(\n @JsonProperty(\"itemId\") long id,\n @JsonProperty(\"name\") String name,\n @JsonProperty(\"sourceKey\") String sourceKey,\n @JsonProperty(\"tags\") Map<String, Tag> tags) {\n super(id, tags);\n\n this.name = name;\n this.sourceKey = sourceKey;\n }\n\n public Structure(long id, Structure other) {\n super(id, other.getTags());\n\n this.name = other.name;\n this.sourceKey = other.sourceKey;\n }\n\n public String getName() {\n return this.name;\n }\n\n public String getSourceKey() {\n return this.sourceKey;\n }\n\n @Override\n public boolean equals(Object other) {\n if (!(other instanceof Structure)) {\n return false;\n }\n\n Structure otherStructure = (Structure) other;\n\n return this.name.equals(otherStructure.name)\n && this.getId() == otherStructure.getId()\n && this.sourceKey.equals(otherStructure.sourceKey)\n && this.getTags().equals(otherStructure.getTags());\n }\n}",
"public class StructureVersion extends Version {\n\n // the id of the Structure containing this Version\n @JsonProperty(\"structureId\")\n private final long structureId;\n\n // the map of attribute names to types\n @JsonProperty(\"attributes\")\n private final Map<String, GroundType> attributes;\n\n /**\n * Create a new structure version.\n *\n * @param id the id of the structure version\n * @param structureId the id of the structure containing this version\n * @param attributes the attributes required by this structure version\n */\n @JsonCreator\n public StructureVersion(\n @JsonProperty(\"id\") long id,\n @JsonProperty(\"structureId\") long structureId,\n @JsonProperty(\"attributes\") Map<String, GroundType> attributes) {\n super(id);\n\n this.structureId = structureId;\n this.attributes = attributes;\n }\n\n public StructureVersion(long id, StructureVersion other) {\n super(id);\n\n this.structureId = other.structureId;\n this.attributes = other.attributes;\n }\n\n public long getStructureId() {\n return this.structureId;\n }\n\n public Map<String, GroundType> getAttributes() {\n return this.attributes;\n }\n\n @Override\n public boolean equals(Object other) {\n if (!(other instanceof StructureVersion)) {\n return false;\n }\n\n StructureVersion otherStructureVersion = (StructureVersion) other;\n\n return this.structureId == otherStructureVersion.structureId\n && this.attributes.equals(otherStructureVersion.attributes)\n && this.getId() == otherStructureVersion.getId();\n }\n}",
"@Singleton\npublic class IdGenerator {\n\n private final long prefix;\n private long versionCounter;\n private long successorCounter;\n private long itemCounter;\n\n // If true, only one counter will be used. If false, all three counters will be used.\n private final boolean globallyUnique;\n\n public IdGenerator() {\n this.prefix = 0;\n this.versionCounter = 1;\n this.successorCounter = 1;\n this.itemCounter = 1;\n this.globallyUnique = true;\n }\n\n /**\n * Create a unique id generator.\n *\n * @param machineId the id of this machine\n * @param numMachines the total number of machines\n * @param globallyUnique if true, only one counter will be used for all version\n */\n public IdGenerator(long machineId, long numMachines, boolean globallyUnique) {\n long machineBits = 1;\n long fence = 2;\n\n while (fence < numMachines) {\n fence = fence * 2;\n machineBits++;\n }\n\n this.prefix = machineId << (64 - machineBits);\n\n // NOTE: Do not change this. The version counter is set to start a 1 because 0 is the default\n // empty version.\n this.versionCounter = 1;\n this.successorCounter = 1;\n this.itemCounter = 1;\n\n this.globallyUnique = globallyUnique;\n }\n\n public synchronized long generateVersionId() {\n return prefix | this.versionCounter++;\n }\n\n /**\n * Generate an id for version successors.\n *\n * @return a new id\n */\n public synchronized long generateSuccessorId() {\n if (this.globallyUnique) {\n return prefix | this.versionCounter++;\n } else {\n return prefix | this.successorCounter++;\n }\n }\n\n /**\n * Generate an id for items.\n *\n * @return a new id\n */\n public synchronized long generateItemId() {\n if (this.globallyUnique) {\n return prefix | this.versionCounter++;\n } else {\n return prefix | this.itemCounter++;\n }\n }\n}",
"public class PostgresStructureDao extends PostgresItemDao<Structure> implements StructureDao {\n\n public PostgresStructureDao(Database dbSource, IdGenerator idGenerator) {\n super(dbSource, idGenerator);\n }\n\n @Override\n public Class<Structure> getType() {\n return Structure.class;\n }\n\n @Override\n public Structure create(Structure structure) throws GroundException {\n super.verifyItemNotExists(structure.getSourceKey());\n\n PostgresStatements postgresStatements;\n long uniqueId = idGenerator.generateItemId();\n\n Structure newStructure = new Structure(uniqueId, structure);\n\n try {\n postgresStatements = super.insert(newStructure);\n\n String name = structure.getName();\n\n if (name != null) {\n postgresStatements.append(String.format(SqlConstants.INSERT_GENERIC_ITEM_WITH_NAME, \"structure\", uniqueId, structure.getSourceKey(), name));\n } else {\n postgresStatements.append(String.format(SqlConstants.INSERT_GENERIC_ITEM_WITHOUT_NAME, \"structure\", uniqueId, structure.getSourceKey()));\n }\n } catch (GroundException e) {\n throw e;\n } catch (Exception e) {\n throw new GroundException(e);\n }\n\n PostgresUtils.executeSqlList(dbSource, postgresStatements);\n return newStructure;\n }\n\n @Override\n public List<Long> getLeaves(String sourceKey) throws GroundException {\n Structure structure = retrieveFromDatabase(sourceKey);\n return super.getLeaves(structure.getId());\n }\n\n @Override\n public Map<Long, Long> getHistory(String sourceKey) throws GroundException {\n Structure structure = retrieveFromDatabase(sourceKey);\n return super.getHistory(structure.getId());\n }\n\n @Override\n public void truncate(long itemId, int numLevels) throws GroundException {\n super.truncate(itemId, numLevels);\n }\n}",
"public class PostgresStructureVersionDao extends PostgresVersionDao<StructureVersion> implements StructureVersionDao {\n\n private PostgresStructureDao postgresStructureDao;\n\n public PostgresStructureVersionDao(Database dbSource, IdGenerator idGenerator) {\n super(dbSource, idGenerator);\n this.postgresStructureDao = new PostgresStructureDao(dbSource, idGenerator);\n }\n\n @Override\n public final StructureVersion create(final StructureVersion structureVersion, List<Long> parentIds) throws GroundException {\n\n long uniqueId = idGenerator.generateItemId();\n StructureVersion newStructureVersion = new StructureVersion(uniqueId, structureVersion);\n PostgresStatements updateVersionList = this.postgresStructureDao\n .update(newStructureVersion.getStructureId(), newStructureVersion.getId(), parentIds);\n\n try {\n PostgresStatements statements = super.insert(newStructureVersion);\n statements.append(String.format(SqlConstants.INSERT_STRUCTURE_VERSION, uniqueId, structureVersion.getStructureId()));\n\n for (Map.Entry<String, GroundType> attribute : structureVersion.getAttributes().entrySet()) {\n statements.append(String.format(SqlConstants.INSERT_STRUCTURE_VERSION_ATTRIBUTE, uniqueId, attribute.getKey(), attribute.getValue()));\n }\n\n statements.merge(updateVersionList);\n\n PostgresUtils.executeSqlList(dbSource, statements);\n } catch (Exception e) {\n throw new GroundException(e);\n }\n\n return newStructureVersion;\n }\n\n @Override\n public PostgresStatements delete(long id) {\n PostgresStatements statements = new PostgresStatements();\n statements.append(String.format(SqlConstants.DELETE_STRUCTURE_VERSION_ATTRIBUTES, id));\n statements.append(String.format(SqlConstants.DELETE_BY_ID, \"structure_version\", id));\n\n PostgresStatements superStatements = super.delete(id);\n superStatements.merge(statements);\n return superStatements;\n }\n\n @Override\n public StructureVersion retrieveFromDatabase(final long id) throws GroundException {\n HashMap<String, GroundType> attributes;\n try {\n String resultQuery = String.format(SqlConstants.SELECT_STAR_BY_ID, \"structure_version\", id);\n JsonNode resultJson = Json.parse(PostgresUtils.executeQueryToJson(dbSource, resultQuery));\n\n if (resultJson.size() == 0) {\n throw new GroundException(ExceptionType.VERSION_NOT_FOUND, this.getType().getSimpleName(), String.format(\"%d\", id));\n }\n\n StructureVersion structureVersion = Json.fromJson(resultJson.get(0), StructureVersion.class);\n\n String attributeQuery = String.format(SqlConstants.SELECT_STRUCTURE_VERSION_ATTRIBUTES, id);\n JsonNode attributeJson = Json.parse(PostgresUtils.executeQueryToJson(dbSource, attributeQuery));\n\n attributes = new HashMap<>();\n\n for (JsonNode attribute : attributeJson) {\n GroundType type = GroundType.fromString(attribute.get(\"type\").asText());\n attributes.put(attribute.get(\"key\").asText(), type);\n }\n\n structureVersion = new StructureVersion(structureVersion.getId(), structureVersion.getStructureId(), attributes);\n return structureVersion;\n } catch (Exception e) {\n throw new GroundException(e);\n }\n }\n}",
"public final class GroundUtils {\n\n private GroundUtils() {\n }\n\n public static Result handleException(Throwable e, Request request) {\n if (e.getCause().getCause() instanceof GroundException) {\n return badRequest(GroundUtils.getClientError(request, e.getCause().getCause(), ExceptionType.ITEM_NOT_FOUND));\n } else {\n return internalServerError(GroundUtils.getServerError(request, e.getCause().getCause()));\n }\n }\n\n private static ObjectNode getServerError(final Request request, final Throwable e) {\n Logger.error(\"Error! Request Path: {}\\nError Message: {}\\n Stack Trace: {}\", request.path(), e.getMessage(), e.getStackTrace());\n\n ObjectNode result = Json.newObject();\n result.put(\"Error\", \"Unexpected error while processing request.\");\n result.put(\"Request Path\", request.path());\n\n StringWriter sw = new StringWriter();\n e.printStackTrace(new PrintWriter(sw));\n result.put(\"Stack Trace\", sw.toString());\n return result;\n }\n\n private static ObjectNode getClientError(final Request request, final Throwable e, ExceptionType type) {\n Logger.error(\"Error! Request Path: {}\\nError Message: {}\\n Stack Trace: {}\", request.path(), e.getMessage(), e.getStackTrace());\n\n ObjectNode result = Json.newObject();\n\n result.put(\"Error\", String.format(\"The request to %s was invalid.\", request.path()));\n result.put(\"Message\", String.format(\"%s\", e.getMessage()));\n\n return result;\n }\n\n static String listToJson(final List<Map<String, Object>> objList) {\n try {\n return new ObjectMapper().writeValueAsString(objList);\n } catch (IOException e) {\n throw new RuntimeException(\"ERROR : listToJson Converting List to JSON.\" + e.getMessage(), e);\n }\n }\n\n public static List<Long> getListFromJson(JsonNode jsonNode, String fieldName) {\n List<Long> parents = new ArrayList<>();\n JsonNode listNode = jsonNode.get(fieldName);\n\n if (listNode != null) {\n listNode.forEach(node -> parents.add(node.asLong()));\n }\n\n return parents;\n }\n\n public static VersionDao<?> getVersionDaoFromItemType(Class<?> klass, Database dbSource, IdGenerator idGenerator) throws GroundException {\n if (klass.equals(Node.class)) {\n return new PostgresNodeVersionDao(dbSource, idGenerator);\n } else if (klass.equals(Edge.class)) {\n return new PostgresEdgeVersionDao(dbSource, idGenerator);\n } else if (klass.equals(Graph.class)) {\n return new PostgresGraphVersionDao(dbSource, idGenerator);\n } else if (klass.equals(Structure.class)) {\n return new PostgresStructureVersionDao(dbSource, idGenerator);\n } else if (klass.equals(LineageEdge.class)) {\n return new PostgresLineageEdgeVersionDao(dbSource, idGenerator);\n } else if (klass.equals(LineageGraph.class)) {\n return new PostgresLineageGraphVersionDao(dbSource, idGenerator);\n } else {\n throw new GroundException(ExceptionType.OTHER, String.format(\"Unknown class :%s.\", klass.getSimpleName()));\n }\n }\n}",
"public final class PostgresUtils {\n\n private PostgresUtils() {\n }\n\n public static Executor getDbSourceHttpContext(final ActorSystem actorSystem) {\n return HttpExecution.fromThread((Executor) actorSystem.dispatchers().lookup(\"ground.db.context\"));\n }\n\n public static String executeQueryToJson(Database dbSource, String sql) throws GroundException {\n Logger.debug(\"executeQueryToJson: {}\", sql);\n\n try {\n Connection con = dbSource.getConnection();\n Statement stmt = con.createStatement();\n\n final ResultSet resultSet = stmt.executeQuery(sql);\n final long columnCount = resultSet.getMetaData().getColumnCount();\n final List<Map<String, Object>> objList = new ArrayList<>();\n\n while (resultSet.next()) {\n final Map<String, Object> rowData = new HashMap<>();\n\n for (int column = 1; column <= columnCount; column++) {\n String key = CaseFormat.LOWER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, resultSet.getMetaData().getColumnLabel(column));\n rowData.put(key, resultSet.getObject(column));\n }\n\n objList.add(rowData);\n }\n\n stmt.close();\n con.close();\n return GroundUtils.listToJson(objList);\n } catch (SQLException e) {\n Logger.error(\"ERROR: executeQueryToJson SQL : {} Message: {} Trace: {}\", sql, e.getMessage(), e.getStackTrace());\n throw new GroundException(e);\n }\n }\n\n public static void executeSqlList(final Database dbSource, final PostgresStatements statements) throws GroundException {\n try {\n Connection con = dbSource.getConnection();\n con.setAutoCommit(false);\n Statement stmt = con.createStatement();\n\n for (final String sql : statements.getAllStatements()) {\n Logger.debug(\"executeSqlList sql : {}\", sql);\n\n try {\n stmt.execute(sql);\n } catch (final SQLException e) {\n con.rollback();\n Logger.error(\"error: Message: {} Trace: {}\", e.getMessage(), e.getStackTrace());\n\n throw new GroundException(e);\n }\n }\n\n stmt.close();\n con.commit();\n con.close();\n } catch (SQLException e) {\n Logger.error(\"error: executeSqlList SQL : {} Message: {} Trace: {}\", statements.getAllStatements(), e.getMessage(), e.getStackTrace());\n\n throw new GroundException(e);\n }\n }\n}"
] | import akka.actor.ActorSystem;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import edu.berkeley.ground.common.exception.GroundException;
import edu.berkeley.ground.common.model.core.Structure;
import edu.berkeley.ground.common.model.core.StructureVersion;
import edu.berkeley.ground.common.util.IdGenerator;
import edu.berkeley.ground.postgres.dao.core.PostgresStructureDao;
import edu.berkeley.ground.postgres.dao.core.PostgresStructureVersionDao;
import edu.berkeley.ground.postgres.util.GroundUtils;
import edu.berkeley.ground.postgres.util.PostgresUtils;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CompletionStage;
import javax.inject.Inject;
import play.cache.CacheApi;
import play.db.Database;
import play.libs.Json;
import play.mvc.BodyParser;
import play.mvc.Controller;
import play.mvc.Result;
import play.mvc.Results; | /**
* 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
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>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 edu.berkeley.ground.postgres.controllers;
public class StructureController extends Controller {
private CacheApi cache;
private ActorSystem actorSystem;
private PostgresStructureDao postgresStructureDao;
private PostgresStructureVersionDao postgresStructureVersionDao;
@Inject
final void injectUtils(final CacheApi cache, final Database dbSource, final ActorSystem actorSystem, final IdGenerator idGenerator) {
this.actorSystem = actorSystem;
this.cache = cache;
this.postgresStructureDao = new PostgresStructureDao(dbSource, idGenerator);
this.postgresStructureVersionDao = new PostgresStructureVersionDao(dbSource, idGenerator);
}
public final CompletionStage<Result> getStructure(String sourceKey) {
return CompletableFuture.supplyAsync(
() -> {
try {
return this.cache.getOrElse(
"structures." + sourceKey,
() -> Json.toJson(this.postgresStructureDao.retrieveFromDatabase(sourceKey)),
Integer.parseInt(System.getProperty("ground.cache.expire.secs")));
} catch (Exception e) {
throw new CompletionException(e);
}
}, PostgresUtils.getDbSourceHttpContext(this.actorSystem))
.thenApply(Results::ok)
.exceptionally(e -> GroundUtils.handleException(e, request()));
}
public final CompletionStage<Result> getStructureVersion(Long id) {
return CompletableFuture.supplyAsync(
() -> {
try {
return this.cache.getOrElse(
"structure_versions." + id,
() -> Json.toJson(this.postgresStructureVersionDao.retrieveFromDatabase(id)),
Integer.parseInt(System.getProperty("ground.cache.expire.secs")));
} catch (Exception e) {
throw new CompletionException(e);
}
}, PostgresUtils.getDbSourceHttpContext(this.actorSystem))
.thenApply(Results::ok)
.exceptionally(e -> GroundUtils.handleException(e, request()));
}
@BodyParser.Of(BodyParser.Json.class)
public final CompletionStage<Result> addStructure() {
return CompletableFuture.supplyAsync(
() -> {
JsonNode json = request().body().asJson();
Structure structure = Json.fromJson(json, Structure.class);
try {
structure = this.postgresStructureDao.create(structure); | } catch (GroundException e) { | 0 |
Cheemion/algorithms | src/com/algorithms/graph/BellmanFordQueueBasedShortestPath.java | [
"public class ArrayBag<T> implements Bag<T>{\n\t\n\tpublic static void main(String[] args) {\n\t\tBag<Integer> bag = new LinkedBag<>();\n\t\tbag.add(1);\n\t\tbag.add(2);\n\t\tbag.add(3);\n\t\tbag.add(4);\n\t\tbag.add(5);\n\t\tfor (Integer a : bag)\n\t\t\tSystem.out.println(a);\n\t}\n\t\n\t\n\tprivate static int DEFAULT_CAPACITY = 16;\n\tprivate int capacity;\n\tprivate T[] base;\n\tprivate int index;//ÔªËصÄÊýÁ¿\n\t\n\tpublic ArrayBag() {\n\t\tthis.capacity = DEFAULT_CAPACITY;\n\t\tbase = (T[]) new Object[capacity];\n\t}\n\t\n\tpublic ArrayBag(int capacity) {\n\t\tthis.capacity = capacity;\n\t\tbase = (T[]) new Object[capacity];\n\t}\n\t\n\tprivate class ArrayBagIterator implements Iterator<T> {\n\t\t\n\t\tint amount = index;\n\t\t\n\t\t@Override\n\t\tpublic boolean hasNext() {\n\t\t\treturn amount > 0;\n\t\t}\n\n\t\t@Override\n\t\tpublic T next() {\n\t\t\treturn base[--amount];\n\t\t}\n\t\t\n\t}\n\t\n\t@Override\n\tpublic Iterator<T> iterator() {\n\t\treturn new ArrayBagIterator();\n\t}\n\n\t@SuppressWarnings(\"unchecked\")\n\tprivate void resize(int newSize) {\n\t\tT[] oldBase = base;\n\t\tbase = (T[]) new Object[newSize];\n\t\tfor (int i = 0; i < index; i++) \n\t\t\tbase[i] = oldBase[i];\n\t}\n\t\n\t@Override\n\tpublic void add(T t) {\n\t\tif(base.length == index) {\n\t\t\tcapacity = capacity * 2;\n\t\t\tresize(capacity);\n\t\t}\n\t\tbase[index++] = t;\n\t}\n\n\t@Override\n\tpublic boolean isEmpty() {\n\t\treturn index == 0;\n\t}\n\n\t@Override\n\tpublic int size() {\n\t\treturn index;\n\t}\n\t\n\t@Override\n\tpublic String toString() {\n\t\tStringBuilder sb = new StringBuilder();\n\t\tfor(T t : this)\n\t\t\tsb.append(t + \" \");\n\t\treturn sb.toString();\n\t}\n}",
"public class ArrayQueue<T> implements Queue<T>{\n\t\n\t\n\tpublic static void main(String[] args) {\n\t\tQueue<Integer> queue = new ArrayQueue();\n\t\tqueue.enqueue(1);\n\t\tqueue.enqueue(1);\n\t\tqueue.enqueue(1);\n\t\tqueue.dequeue();\n\t\tqueue.enqueue(2);\n\t\tqueue.enqueue(2);\n\t\tqueue.enqueue(3);\n\t\tqueue.enqueue(3);\n\t\tqueue.enqueue(3);\n\t\tqueue.dequeue();\n\t\tfor(int s : queue)\n\t\t\tSystem.out.println(s);\n\t}\n\n\tprivate static int DEFAULT_CAPACITY = 10;\n\tprivate int head = 0;\n\tprivate int tail = 0;\n\tprivate int capacity;\n\tprivate T[] base;\n\t\n\tpublic ArrayQueue(int capacity) {\n\t\tthis.capacity = capacity;\n\t\tbase = (T[]) new Object[capacity];\n\t}\n\t\n\tpublic ArrayQueue() {\n\t\tthis.capacity = DEFAULT_CAPACITY;\n\t\tbase = (T[]) new Object[capacity];\n\t}\n\t\n\t@Override\n\tpublic Iterator<T> iterator() {\n\t\treturn new ArrayQueueIterator();\n\t}\n\t\n\t//²¢Ã»ÓпØÖƶàÏß³ÌÎÊÌâ\n\tprivate class ArrayQueueIterator implements Iterator<T> {\n\t\t\n\t\tint first = head;\n\t\tint last = tail;\n\t\t@Override\n\t\tpublic boolean hasNext() {\n\t\t\treturn last - first > 0;\n\t\t}\n\n\t\t@Override\n\t\tpublic T next() {\n\t\t\treturn base[first++];\n\t\t}\n\t\t\n\t}\n\t\n\t@Override\n\tpublic void enqueue(T t) {\n\t\tif (tail == capacity) {\n\t\t\tif (head == 0) {\n\t\t\t\tcapacity = capacity * 2;\n\t\t\t\tresize(capacity);\n\t\t\t} else {\n\t\t\t\treset();\n\t\t\t}\n\t\t}\n\t\tbase[tail++] = t;\n\t}\n\n\t@Override\n\tpublic T dequeue() {\n\t\treturn base[head++];\n\t}\n\n\t@Override\n\tpublic boolean isEmpty() {\n\t\treturn (tail - head) <= 0;\n\t}\n\n\t@Override\n\tpublic int size() {\n\t\treturn tail - head;\n\t}\n\n\tprivate void reset() {\n\t\tfor(int i = head, j = 0; i < tail; i++, j++) {\n\t\t\tbase[j] = base[i];\n\t\t}\n\t\ttail = size();\n\t\thead = 0;\n\t}\n\t\n\t@SuppressWarnings(\"unchecked\")\n\tprivate void resize(int newSize) {\n\t\tT[] oldBase = base;\n\t\tbase = (T[]) new Object[newSize];\n\t\tfor (int i = 0; i < oldBase.length; i++) \n\t\t\tbase[i] = oldBase[i];\n\t}\n\t\n\t@Override\n\tpublic String toString() {\n\t\tStringBuilder sb = new StringBuilder();\n\t\tfor(T t : this)\n\t\t\tsb.append(t + \" \");\n\t\treturn sb.toString();\n\t}\n}",
"public class ArrayStack<T> implements Stack<T>{\n\t\n\tpublic static void main(String[] args) {\n\t}\n\t\n\tprivate int capacity;\n\tprivate static int DEFAULT_CAPACITY = 10;\n\tprivate T[] base;\n\tprivate int index = 0; // Êý×éµÄÔªËصÄÊýÁ¿\n\t\n\t@SuppressWarnings(\"unchecked\")\n\tpublic ArrayStack(int capacity) {\n\t\tthis.capacity = capacity;\n\t\tbase = (T[]) new Object[capacity];\n\t}\n\t\n\t@SuppressWarnings(\"unchecked\")\n\tpublic ArrayStack() {\n\t\tthis.capacity = DEFAULT_CAPACITY;\n\t\tbase = (T[]) new Object[capacity];\n\t}\n\t\n\t@Override\n\tpublic void push(T t) {\n\t\tif(index == capacity) {\n\t\t\tcapacity = capacity * 2;\n\t\t\tresize(capacity);\n\t\t}\n\t\tbase[index++] = t;\n\t}\n\n\t@Override\n\tpublic T pop() {\n\t\tT t = base[--index];\n\t\tbase[index] = null;\n\t\tif (index > 0 && index == capacity / 4) {\n\t\t\tcapacity = capacity / 2;\n\t\t\tresize(capacity);\n\t\t}\n\t\treturn t;\n\t}\n\n\t@Override\n\tpublic boolean isEmpty() {\n\t\treturn index == 0;\n\t}\n\n\t@Override\n\tpublic int size() {\n\t\treturn index;\n\t}\n\t\n\t@Override\n\tpublic Iterator<T> iterator() {\n\t\treturn new StackIterator();\n\t}\n\tprivate class StackIterator implements Iterator<T> {\n\t\t\n\t\tprivate int i = ArrayStack.this.index;\n\t\t\n\t\t@Override\n\t\tpublic boolean hasNext() {\n\t\t\treturn i > 0;\n\t\t}\n\n\t\t@Override\n\t\tpublic T next() {\n\t\t\treturn base[--i];\n\t\t}\n\n\t}\n\t\n\t@SuppressWarnings(\"unchecked\")\n\tprivate void resize(int newSize) {\n\t\tT[] oldBase = base;\n\t\tbase = (T[]) new Object[newSize];\n\t\tfor (int i = 0; i < index; i++) \n\t\t\tbase[i] = oldBase[i];\n\t}\n\t\n\t@Override\n\tpublic String toString() {\n\t\tStringBuffer sb = new StringBuffer();\n\t\tfor(T t : this) {\n\t\t\tsb.append(t);\n\t\t\tsb.append(' ');\n\t\t}\n\t\treturn sb.toString();\n\t}\n\t\n}",
"public interface Bag<T> extends Iterable<T>{\n\tvoid add (T t);\n\tboolean isEmpty();\n\tint size();\n}",
"public interface Queue<T> extends Iterable<T>{\n\tvoid enqueue(T t);\n\tT dequeue();\n\tboolean isEmpty();\n\tint size();\n}",
"public interface Stack<T> extends Iterable<T> {\n\tvoid push(T t);\n\tT pop();\n\tboolean isEmpty();\n\tint size();\n}"
] | import com.algorithms.elementary.ArrayBag;
import com.algorithms.elementary.ArrayQueue;
import com.algorithms.elementary.ArrayStack;
import com.algorithms.elementary.Bag;
import com.algorithms.elementary.Queue;
import com.algorithms.elementary.Stack; | package com.algorithms.graph;
/**
* can not have negative cyclic
* @author altro
*
*/
public class BellmanFordQueueBasedShortestPath {
private double[] distTo;
private DirectedEdge[] edgeTo;
private int source;
private Queue<Integer> changed;
private boolean hasNegativeCycle;
private Bag<DirectedEdge> negativeCycleEdges;
public static void main(String[] args) {
EdgeWeightedDigraph graph = new EdgeWeightedDigraph(8);
graph.addEdge(new DirectedEdge(4, 5, 0.35));
graph.addEdge(new DirectedEdge(5, 6, -1));
graph.addEdge(new DirectedEdge(6, 4, 0.37));
graph.addEdge(new DirectedEdge(5, 7, 0.28));
graph.addEdge(new DirectedEdge(7, 5, 0.28));
graph.addEdge(new DirectedEdge(5, 1, 0.32));
graph.addEdge(new DirectedEdge(0, 4, 0.38));
graph.addEdge(new DirectedEdge(0, 2, 0.26));
graph.addEdge(new DirectedEdge(7, 3, 0.39));
graph.addEdge(new DirectedEdge(1, 3, 0.29));
graph.addEdge(new DirectedEdge(2, 7, 0.34));
graph.addEdge(new DirectedEdge(6, 2, -1.20));
graph.addEdge(new DirectedEdge(3, 6, 0.52));
graph.addEdge(new DirectedEdge(6, 0, -1.40));
graph.addEdge(new DirectedEdge(6, 4, -1.25));
BellmanFordQueueBasedShortestPath b = new BellmanFordQueueBasedShortestPath(graph, 0);
System.out.println(b.hasNegativeCycle());
System.out.println(b.negativeCycle());
}
public BellmanFordQueueBasedShortestPath(EdgeWeightedDigraph g, int s) {
this.source = s;
distTo = new double[g.vertices()];
edgeTo = new DirectedEdge[g.vertices()];
changed = new ArrayQueue<>();
for (int i = 0; i < distTo.length; i++)
distTo[i] = Double.POSITIVE_INFINITY;
distTo[s] = 0.0;
changed.enqueue(s);
start(g);
}
private void start(EdgeWeightedDigraph g) {
int pass = 0;
for (; pass < g.vertices() && !changed.isEmpty(); pass++) {
Queue<Integer> temp = new ArrayQueue<>();
for (Integer changedPosition : changed) {
for (DirectedEdge e : g.adj(changedPosition))
relax(e, temp);
}
changed = temp;
if (changed.isEmpty()) break;
}
if (pass == g.vertices() && !changed.isEmpty()) {
hasNegativeCycle = true;
negativeCycleEdges = new ArrayBag<>();
int changePos = changed.dequeue();
for (int i = edgeTo[changePos].from(); i != changePos; i = edgeTo[i].from())
negativeCycleEdges.add(edgeTo[i]);
negativeCycleEdges.add(edgeTo[changePos]);
}
}
public boolean hasPathTo(int v) {
return distTo[v] != Double.POSITIVE_INFINITY;
}
public double distTo(int v) {
return distTo[v];
}
public Iterable<DirectedEdge> pathTo(int v) { | Stack<DirectedEdge> path = new ArrayStack<>(); | 5 |
CyclopsMC/ColossalChests | src/main/java/org/cyclops/colossalchests/item/ItemUpgradeTool.java | [
"public class Advancements {\n\n public static final ChestFormedTrigger CHEST_FORMED = AdvancementHelpers\n .registerCriteriaTrigger(new ChestFormedTrigger());\n\n public static void load() {}\n\n}",
"public class ChestMaterial extends ForgeRegistryEntry<ChestMaterial> {\n\n public static final List<ChestMaterial> VALUES = Lists.newArrayList();\n public static final Map<String, ChestMaterial> KEYED_VALUES = Maps.newHashMap();\n\n public static final ChestMaterial WOOD = new ChestMaterial(\"wood\", 1);\n public static final ChestMaterial COPPER = new ChestMaterial(\"copper\", 1.666);\n public static final ChestMaterial IRON = new ChestMaterial(\"iron\", 2);\n public static final ChestMaterial SILVER = new ChestMaterial(\"silver\", 2.666);\n public static final ChestMaterial GOLD = new ChestMaterial(\"gold\", 3);\n public static final ChestMaterial DIAMOND = new ChestMaterial(\"diamond\", 4);\n public static final ChestMaterial OBSIDIAN = new ChestMaterial(\"obsidian\", 4);\n\n private final String name;\n private final double inventoryMultiplier;\n private final int index;\n\n private ColossalChest blockCore;\n private Interface blockInterface;\n private ChestWall blockWall;\n private CubeDetector chestDetector = null;\n private ContainerType<ContainerColossalChest> container;\n\n public ChestMaterial(String name, double inventoryMultiplier) {\n this.name = name;\n this.inventoryMultiplier = inventoryMultiplier;\n this.index = ChestMaterial.VALUES.size();\n ChestMaterial.VALUES.add(this);\n ChestMaterial.KEYED_VALUES.put(getName(), this);\n }\n\n public static ChestMaterial valueOf(String materialString) {\n return KEYED_VALUES.get(materialString.toLowerCase());\n }\n\n public String getName() {\n return name;\n }\n\n public double getInventoryMultiplier() {\n return this.inventoryMultiplier;\n }\n\n public String getUnlocalizedName() {\n return \"material.\" + Reference.MOD_ID + \".\" + getName();\n }\n\n public boolean isExplosionResistant() {\n return this == OBSIDIAN;\n }\n\n public int ordinal() {\n return this.index;\n }\n\n public ColossalChest getBlockCore() {\n return blockCore;\n }\n\n public void setBlockCore(ColossalChest blockCore) {\n if (this.blockCore != null) {\n throw new IllegalStateException(\"Tried registering multiple core blocks for \" + this.getName());\n }\n this.blockCore = blockCore;\n }\n\n public Interface getBlockInterface() {\n return blockInterface;\n }\n\n public void setBlockInterface(Interface blockInterface) {\n if (this.blockInterface != null) {\n throw new IllegalStateException(\"Tried registering multiple core blocks for \" + this.getName());\n }\n this.blockInterface = blockInterface;\n }\n\n public ChestWall getBlockWall() {\n return blockWall;\n }\n\n public void setBlockWall(ChestWall blockWall) {\n if (this.blockWall != null) {\n throw new IllegalStateException(\"Tried registering multiple core blocks for \" + this.getName());\n }\n this.blockWall = blockWall;\n }\n\n public void setContainer(ContainerType<ContainerColossalChest> container) {\n if (this.container != null) {\n throw new IllegalStateException(\"Tried registering multiple containers for \" + this.getName());\n }\n this.container = container;\n }\n\n public ContainerType<ContainerColossalChest> getContainer() {\n return container;\n }\n\n public CubeDetector getChestDetector() {\n if (chestDetector == null) {\n chestDetector = new HollowCubeDetector(\n new AllowedBlock[]{\n new AllowedBlock(getBlockWall()),\n new AllowedBlock(getBlockCore()).addCountValidator(new ExactBlockCountValidator(1)),\n new AllowedBlock(getBlockInterface())\n },\n Lists.newArrayList(getBlockCore(), getBlockWall(), getBlockInterface())\n )\n .addSizeValidator(new MinimumSizeValidator(new Vector3i(1, 1, 1)))\n .addSizeValidator(new CubeSizeValidator())\n .addSizeValidator(new MaximumSizeValidator(TileColossalChest.getMaxSize()) {\n @Override\n public Vector3i getMaximumSize() {\n return TileColossalChest.getMaxSize();\n }\n });\n }\n return chestDetector;\n }\n\n}",
"public class ChestWall extends Block implements CubeDetector.IDetectionListener, IBlockChestMaterial {\n\n public static final BooleanProperty ENABLED = ColossalChest.ENABLED;\n\n private final ChestMaterial material;\n\n public ChestWall(Block.Properties properties, ChestMaterial material) {\n super(properties);\n this.material = material;\n\n material.setBlockWall(this);\n\n this.setDefaultState(this.stateContainer.getBaseState()\n .with(ENABLED, false));\n }\n\n @Override\n public String getTranslationKey() {\n String baseKey = super.getTranslationKey();\n return baseKey.substring(0, baseKey.lastIndexOf('_'));\n }\n\n @Override\n public ChestMaterial getMaterial() {\n return material;\n }\n\n @Override\n protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder) {\n builder.add(ENABLED);\n }\n\n @Override\n public boolean isToolEffective(BlockState state, ToolType tool) {\n return ColossalChest.isToolEffectiveShared(this.material, state, tool);\n }\n\n @Override\n public BlockRenderType getRenderType(BlockState blockState) {\n return blockState.get(ENABLED) ? BlockRenderType.ENTITYBLOCK_ANIMATED : super.getRenderType(blockState);\n }\n\n @Override\n public boolean propagatesSkylightDown(BlockState blockState, IBlockReader blockReader, BlockPos blockPos) {\n return blockState.get(ENABLED);\n }\n\n @Override\n public boolean canCreatureSpawn(BlockState state, IBlockReader world, BlockPos pos,\n EntitySpawnPlacementRegistry.PlacementType type, @Nullable EntityType<?> entityType) {\n return false;\n }\n\n @Override\n public boolean shouldDisplayFluidOverlay(BlockState blockState, IBlockDisplayReader world, BlockPos pos, FluidState fluidState) {\n return true;\n }\n\n @Override\n public void onBlockPlacedBy(World world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack) {\n super.onBlockPlacedBy(world, pos, state, placer, stack);\n ColossalChest.triggerDetector(this.material, world, pos, true, placer instanceof PlayerEntity ? (PlayerEntity) placer : null);\n }\n\n @Override\n public void onBlockAdded(BlockState blockStateNew, World world, BlockPos blockPos, BlockState blockStateOld, boolean isMoving) {\n super.onBlockAdded(blockStateNew, world, blockPos, blockStateOld, isMoving);\n if(!world.captureBlockSnapshots && blockStateNew.getBlock() != blockStateOld.getBlock() && !blockStateNew.get(ENABLED)) {\n ColossalChest.triggerDetector(this.material, world, blockPos, true, null);\n }\n }\n\n @Override\n public void onPlayerDestroy(IWorld world, BlockPos blockPos, BlockState blockState) {\n if(blockState.get(ENABLED)) ColossalChest.triggerDetector(material, world, blockPos, false, null);\n super.onPlayerDestroy(world, blockPos, blockState);\n }\n\n @Override\n public void onBlockExploded(BlockState state, World world, BlockPos pos, Explosion explosion) {\n if(world.getBlockState(pos).get(ENABLED)) ColossalChest.triggerDetector(material, world, pos, false, null);\n // IForgeBlock.super.onBlockExploded(state, world, pos, explosion);\n world.setBlockState(pos, Blocks.AIR.getDefaultState(), 3);\n getBlock().onExplosionDestroy(world, pos, explosion);\n }\n\n @Override\n public void onDetect(IWorldReader world, BlockPos location, Vector3i size, boolean valid, BlockPos originCorner) {\n Block block = world.getBlockState(location).getBlock();\n if(block == this) {\n boolean change = !world.getBlockState(location).get(ENABLED);\n ((IWorldWriter) world).setBlockState(location, world.getBlockState(location).with(ENABLED, valid), MinecraftHelpers.BLOCK_NOTIFY_CLIENT);\n if(change) {\n TileColossalChest.detectStructure(world, location, size, valid, originCorner);\n }\n }\n }\n\n @Override\n public ActionResultType onBlockActivated(BlockState blockState, World world, BlockPos blockPos, PlayerEntity player, Hand hand, BlockRayTraceResult rayTraceResult) {\n if(blockState.get(ENABLED)) {\n BlockPos tileLocation = ColossalChest.getCoreLocation(material, world, blockPos);\n if(tileLocation != null) {\n return world.getBlockState(tileLocation).getBlock().\n onBlockActivated(blockState, world, tileLocation, player, hand, rayTraceResult);\n }\n } else {\n ColossalChest.addPlayerChatError(material, world, blockPos, player, hand);\n return ActionResultType.FAIL;\n }\n return super.onBlockActivated(blockState, world, blockPos, player, hand, rayTraceResult);\n }\n\n @Override\n public boolean isValidPosition(BlockState blockState, IWorldReader world, BlockPos blockPos) {\n return super.isValidPosition(blockState, world, blockPos) && ColossalChest.canPlace(world, blockPos);\n }\n\n @Override\n public float getExplosionResistance(BlockState state, IBlockReader world, BlockPos pos, Explosion explosion) {\n if (this.material.isExplosionResistant()) {\n return 10000F;\n }\n return 0;\n }\n\n}",
"public class ColossalChest extends BlockTileGui implements CubeDetector.IDetectionListener, IBlockChestMaterial {\n\n public static final BooleanProperty ENABLED = BlockStateProperties.ENABLED;\n\n private final ChestMaterial material;\n\n public ColossalChest(Properties properties, ChestMaterial material) {\n super(properties, TileColossalChest::new);\n this.material = material;\n\n material.setBlockCore(this);\n\n this.setDefaultState(this.stateContainer.getBaseState()\n .with(ENABLED, false));\n }\n\n @Override\n public String getTranslationKey() {\n String baseKey = super.getTranslationKey();\n return baseKey.substring(0, baseKey.lastIndexOf('_'));\n }\n\n @Override\n public ChestMaterial getMaterial() {\n return material;\n }\n\n @Override\n protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder) {\n builder.add(ENABLED);\n }\n\n public static boolean isToolEffectiveShared(ChestMaterial material, BlockState state, ToolType tool) {\n if(material == ChestMaterial.WOOD) {\n return tool == ToolType.AXE;\n }\n return tool == ToolType.PICKAXE;\n }\n\n public static boolean canPlace(IWorldReader world, BlockPos pos) {\n for(Direction side : Direction.values()) {\n BlockState blockState = world.getBlockState(pos.offset(side));\n Block block = blockState.getBlock();\n if((block instanceof ColossalChest || block instanceof ChestWall || block instanceof Interface)\n && blockState.getProperties().contains(ENABLED) && blockState.get(ENABLED)) {\n return false;\n }\n }\n return true;\n }\n\n @Override\n public boolean isToolEffective(BlockState state, ToolType tool) {\n return isToolEffectiveShared(this.material, state, tool);\n }\n\n @Override\n public BlockRenderType getRenderType(BlockState blockState) {\n return blockState.get(ENABLED) ? BlockRenderType.ENTITYBLOCK_ANIMATED : super.getRenderType(blockState);\n }\n\n @Override\n public boolean propagatesSkylightDown(BlockState blockState, IBlockReader blockReader, BlockPos blockPos) {\n return blockState.get(ENABLED);\n }\n\n @Override\n public boolean canCreatureSpawn(BlockState state, IBlockReader world, BlockPos pos,\n EntitySpawnPlacementRegistry.PlacementType type, @Nullable EntityType<?> entityType) {\n return false;\n }\n\n @Override\n public boolean shouldDisplayFluidOverlay(BlockState blockState, IBlockDisplayReader world, BlockPos pos, FluidState fluidState) {\n return true;\n }\n\n public static DetectionResult triggerDetector(ChestMaterial material, IWorld world, BlockPos blockPos, boolean valid, @Nullable PlayerEntity player) {\n DetectionResult detectionResult = material.getChestDetector().detect(world, blockPos, valid ? null : blockPos, new MaterialValidationAction(), true);\n if (player instanceof ServerPlayerEntity && detectionResult.getError() == null) {\n BlockState blockState = world.getBlockState(blockPos);\n if (blockState.get(ENABLED)) {\n TileColossalChest tile = TileHelpers.getSafeTile(world, blockPos, TileColossalChest.class).orElse(null);\n if (tile == null) {\n BlockPos corePos = getCoreLocation(material, world, blockPos);\n tile = TileHelpers.getSafeTile(world, corePos, TileColossalChest.class).orElse(null);\n }\n\n Advancements.CHEST_FORMED.test((ServerPlayerEntity) player, material, tile.getSizeSingular());\n }\n }\n return detectionResult;\n }\n\n @Override\n public void onBlockPlacedBy(World world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack) {\n super.onBlockPlacedBy(world, pos, state, placer, stack);\n if (stack.hasDisplayName()) {\n TileColossalChest tile = TileHelpers.getSafeTile(world, pos, TileColossalChest.class).orElse(null);\n if (tile != null) {\n tile.setCustomName(stack.getDisplayName());\n tile.setSize(Vector3i.NULL_VECTOR);\n }\n }\n triggerDetector(this.material, world, pos, true, placer instanceof PlayerEntity ? (PlayerEntity) placer : null);\n }\n\n @Override\n public void onBlockAdded(BlockState blockStateNew, World world, BlockPos blockPos, BlockState blockStateOld, boolean isMoving) {\n super.onBlockAdded(blockStateNew, world, blockPos, blockStateOld, isMoving);\n if(!world.captureBlockSnapshots && blockStateNew.getBlock() != blockStateOld.getBlock() && !blockStateNew.get(ENABLED)) {\n triggerDetector(this.material, world, blockPos, true, null);\n }\n }\n\n @Override\n public void onDetect(IWorldReader world, BlockPos location, Vector3i size, boolean valid, BlockPos originCorner) {\n Block block = world.getBlockState(location).getBlock();\n if(block == this) {\n ((IWorldWriter) world).setBlockState(location, world.getBlockState(location).with(ENABLED, valid), MinecraftHelpers.BLOCK_NOTIFY_CLIENT);\n TileColossalChest tile = TileHelpers.getSafeTile(world, location, TileColossalChest.class).orElse(null);\n if(tile != null) {\n tile.setMaterial(this.material);\n tile.setSize(valid ? size : Vector3i.NULL_VECTOR);\n tile.setCenter(new Vector3d(\n originCorner.getX() + ((double) size.getX()) / 2,\n originCorner.getY() + ((double) size.getY()) / 2,\n originCorner.getZ() + ((double) size.getZ()) / 2\n ));\n tile.addInterface(location);\n }\n }\n }\n\n /**\n * Get the core block location.\n * @param material The chest material.\n * @param world The world.\n * @param blockPos The start position to search from.\n * @return The found location.\n */\n public static @Nullable BlockPos getCoreLocation(ChestMaterial material, IWorldReader world, BlockPos blockPos) {\n final Wrapper<BlockPos> tileLocationWrapper = new Wrapper<BlockPos>();\n material.getChestDetector().detect(world, blockPos, null, (location, blockState) -> {\n if (blockState.getBlock() instanceof ColossalChest) {\n tileLocationWrapper.set(location);\n }\n return null;\n }, false);\n return tileLocationWrapper.get();\n }\n\n /**\n * Show the structure forming error in the given player chat window.\n * @param material The chest material.\n * @param world The world.\n * @param blockPos The start position.\n * @param player The player.\n * @param hand The used hand.\n */\n public static void addPlayerChatError(ChestMaterial material, World world, BlockPos blockPos, PlayerEntity player, Hand hand) {\n if(!world.isRemote && player.getHeldItem(hand).isEmpty()) {\n DetectionResult result = material.getChestDetector().detect(world, blockPos, null, new MaterialValidationAction(), false);\n if (result != null && result.getError() != null) {\n addPlayerChatError(player, result.getError());\n } else {\n player.sendMessage(new TranslationTextComponent(\"multiblock.colossalchests.error.unexpected\"), Util.DUMMY_UUID);\n }\n }\n }\n\n public static void addPlayerChatError(PlayerEntity player, ITextComponent error) {\n IFormattableTextComponent chat = new StringTextComponent(\"\");\n ITextComponent prefix = new StringTextComponent(\"[\")\n .append(new TranslationTextComponent(\"multiblock.colossalchests.error.prefix\"))\n .append(new StringTextComponent(\"]: \"))\n .setStyle(Style.EMPTY.\n setColor(Color.fromTextFormatting(TextFormatting.GRAY)).\n setHoverEvent(new HoverEvent(\n HoverEvent.Action.SHOW_TEXT,\n new TranslationTextComponent(\"multiblock.colossalchests.error.prefix.info\")\n ))\n );\n chat.append(prefix);\n chat.append(error);\n player.sendMessage(chat, Util.DUMMY_UUID);\n }\n\n @Override\n public void writeExtraGuiData(PacketBuffer packetBuffer, World world, PlayerEntity player, BlockPos blockPos, Hand hand, BlockRayTraceResult rayTraceResult) {\n TileHelpers.getSafeTile(world, blockPos, TileColossalChest.class).ifPresent(tile -> packetBuffer.writeInt(tile.getInventory().getSizeInventory()));\n }\n\n @Override\n public ActionResultType onBlockActivated(BlockState blockState, World world, BlockPos blockPos, PlayerEntity player, Hand hand, BlockRayTraceResult rayTraceResult) {\n if(!(blockState.get(ENABLED))) {\n ColossalChest.addPlayerChatError(material, world, blockPos, player, hand);\n return ActionResultType.FAIL;\n }\n return super.onBlockActivated(blockState, world, blockPos, player, hand, rayTraceResult);\n }\n\n @Override\n public void onPlayerDestroy(IWorld world, BlockPos blockPos, BlockState blockState) {\n if(blockState.get(ENABLED)) ColossalChest.triggerDetector(material, world, blockPos, false, null);\n super.onPlayerDestroy(world, blockPos, blockState);\n }\n\n @Override\n public void onBlockExploded(BlockState state, World world, BlockPos pos, Explosion explosion) {\n if(world.getBlockState(pos).get(ENABLED)) ColossalChest.triggerDetector(material, world, pos, false, null);\n // IForgeBlock.super.onBlockExploded(state, world, pos, explosion);\n world.setBlockState(pos, Blocks.AIR.getDefaultState(), 3);\n getBlock().onExplosionDestroy(world, pos, explosion);\n }\n\n @Override\n public float getExplosionResistance(BlockState state, IBlockReader world, BlockPos pos, Explosion explosion) {\n if (this.material.isExplosionResistant()) {\n return 10000F;\n }\n return 0;\n }\n\n @Override\n public boolean isValidPosition(BlockState blockState, IWorldReader world, BlockPos blockPos) {\n return super.isValidPosition(blockState, world, blockPos) && ColossalChest.canPlace(world, blockPos);\n }\n\n @Override\n public void onReplaced(BlockState oldState, World world, BlockPos blockPos, BlockState newState, boolean isMoving) {\n if (oldState.getBlock().getClass() != newState.getBlock().getClass()) {\n TileHelpers.getSafeTile(world, blockPos, TileColossalChest.class)\n .ifPresent(tile -> {\n // Last inventory overrides inventory when the chest is in a disabled state.\n SimpleInventory lastInventory = tile.getLastValidInventory();\n InventoryHelpers.dropItems(world, lastInventory != null ? lastInventory : tile.getInventory(), blockPos);\n });\n super.onReplaced(oldState, world, blockPos, newState, isMoving);\n }\n }\n\n private static class MaterialValidationAction implements CubeDetector.IValidationAction {\n private final Wrapper<ChestMaterial> requiredMaterial;\n\n public MaterialValidationAction() {\n this.requiredMaterial = new Wrapper<ChestMaterial>(null);\n }\n\n @Override\n public ITextComponent onValidate(BlockPos blockPos, BlockState blockState) {\n ChestMaterial material = null;\n if (blockState.getBlock() instanceof IBlockChestMaterial) {\n material = ((IBlockChestMaterial) blockState.getBlock()).getMaterial();\n }\n if(requiredMaterial.get() == null) {\n requiredMaterial.set(material);\n return null;\n }\n return requiredMaterial.get() == material ? null : new TranslationTextComponent(\n \"multiblock.colossalchests.error.material\", new TranslationTextComponent(material.getUnlocalizedName()),\n LocationHelpers.toCompactString(blockPos),\n new TranslationTextComponent(requiredMaterial.get().getUnlocalizedName()));\n }\n }\n}",
"public interface IBlockChestMaterial {\n\n public ChestMaterial getMaterial();\n\n}",
"public class Interface extends BlockTile implements CubeDetector.IDetectionListener, IBlockChestMaterial {\n\n public static final BooleanProperty ENABLED = ColossalChest.ENABLED;\n\n private final ChestMaterial material;\n\n public Interface(Block.Properties properties, ChestMaterial material) {\n super(properties, TileInterface::new);\n this.material = material;\n\n material.setBlockInterface(this);\n\n this.setDefaultState(this.stateContainer.getBaseState()\n .with(ENABLED, false));\n }\n\n @Override\n public String getTranslationKey() {\n String baseKey = super.getTranslationKey();\n return baseKey.substring(0, baseKey.lastIndexOf('_'));\n }\n\n @Override\n public ChestMaterial getMaterial() {\n return material;\n }\n\n @Override\n protected void fillStateContainer(StateContainer.Builder<Block, BlockState> builder) {\n builder.add(ENABLED);\n }\n\n @Override\n public boolean isToolEffective(BlockState state, ToolType tool) {\n return ColossalChest.isToolEffectiveShared(this.material, state, tool);\n }\n\n @Override\n public BlockRenderType getRenderType(BlockState blockState) {\n return blockState.get(ENABLED) ? BlockRenderType.ENTITYBLOCK_ANIMATED : super.getRenderType(blockState);\n }\n\n @Override\n public boolean propagatesSkylightDown(BlockState blockState, IBlockReader blockReader, BlockPos blockPos) {\n return blockState.get(ENABLED);\n }\n\n @Override\n public boolean canCreatureSpawn(BlockState state, IBlockReader world, BlockPos pos,\n EntitySpawnPlacementRegistry.PlacementType type, @Nullable EntityType<?> entityType) {\n return false;\n }\n\n @Override\n public boolean shouldDisplayFluidOverlay(BlockState blockState, IBlockDisplayReader world, BlockPos pos, FluidState fluidState) {\n return true;\n }\n\n @Override\n public void onBlockPlacedBy(World world, BlockPos pos, BlockState state, LivingEntity placer, ItemStack stack) {\n super.onBlockPlacedBy(world, pos, state, placer, stack);\n ColossalChest.triggerDetector(this.material, world, pos, true, placer instanceof PlayerEntity ? (PlayerEntity) placer : null);\n }\n\n @Override\n public void onBlockAdded(BlockState blockStateNew, World world, BlockPos blockPos, BlockState blockStateOld, boolean isMoving) {\n super.onBlockAdded(blockStateNew, world, blockPos, blockStateOld, isMoving);\n if(!world.captureBlockSnapshots && blockStateNew.getBlock() != blockStateOld.getBlock() && !blockStateNew.get(ENABLED)) {\n ColossalChest.triggerDetector(this.material, world, blockPos, true, null);\n }\n }\n\n @Override\n public void onPlayerDestroy(IWorld world, BlockPos blockPos, BlockState blockState) {\n if(blockState.get(ENABLED)) ColossalChest.triggerDetector(material, world, blockPos, false, null);\n super.onPlayerDestroy(world, blockPos, blockState);\n }\n\n @Override\n public void onBlockExploded(BlockState state, World world, BlockPos pos, Explosion explosion) {\n if(world.getBlockState(pos).get(ENABLED)) ColossalChest.triggerDetector(material, world, pos, false, null);\n // IForgeBlock.super.onBlockExploded(state, world, pos, explosion);\n world.setBlockState(pos, Blocks.AIR.getDefaultState(), 3);\n getBlock().onExplosionDestroy(world, pos, explosion);\n }\n\n @Override\n public void onDetect(IWorldReader world, BlockPos location, Vector3i size, boolean valid, BlockPos originCorner) {\n Block block = world.getBlockState(location).getBlock();\n if(block == this) {\n boolean change = !(Boolean) world.getBlockState(location).get(ENABLED);\n ((IWorldWriter) world).setBlockState(location, world.getBlockState(location).with(ENABLED, valid), MinecraftHelpers.BLOCK_NOTIFY_CLIENT);\n if(change) {\n BlockPos tileLocation = ColossalChest.getCoreLocation(material, world, location);\n TileInterface tile = TileHelpers.getSafeTile(world, location, TileInterface.class).orElse(null);\n if(tile != null && tileLocation != null) {\n tile.setCorePosition(tileLocation);\n TileColossalChest core = TileHelpers.getSafeTile(world, tileLocation, TileColossalChest.class).orElse(null);\n if (core != null) {\n core.addInterface(location);\n }\n }\n }\n }\n }\n\n @Override\n public ActionResultType onBlockActivated(BlockState blockState, World world, BlockPos blockPos, PlayerEntity player, Hand hand, BlockRayTraceResult rayTraceResult) {\n if(blockState.get(ENABLED)) {\n BlockPos tileLocation = ColossalChest.getCoreLocation(material, world, blockPos);\n if(tileLocation != null) {\n return world.getBlockState(tileLocation).getBlock().\n onBlockActivated(blockState, world, tileLocation, player, hand, rayTraceResult);\n }\n } else {\n ColossalChest.addPlayerChatError(material, world, blockPos, player, hand);\n return ActionResultType.FAIL;\n }\n return super.onBlockActivated(blockState, world, blockPos, player, hand, rayTraceResult);\n }\n\n @Override\n public boolean isValidPosition(BlockState blockState, IWorldReader world, BlockPos blockPos) {\n return super.isValidPosition(blockState, world, blockPos) && ColossalChest.canPlace(world, blockPos);\n }\n\n @Override\n public float getExplosionResistance(BlockState state, IBlockReader world, BlockPos pos, Explosion explosion) {\n if (this.material.isExplosionResistant()) {\n return 10000F;\n }\n return 0;\n }\n\n}",
"@OnlyIn(value = Dist.CLIENT, _interface = IChestLid.class)\npublic class TileColossalChest extends CyclopsTileEntity implements CyclopsTileEntity.ITickingTile, INamedContainerProvider, IChestLid {\n\n private static final int TICK_MODULUS = 200;\n\n @Delegate\n private final ITickingTile tickingTileComponent = new TickingTileComponent(this);\n\n private SimpleInventory lastValidInventory = null;\n private SimpleInventory inventory = null;\n private LazyOptional<IItemHandler> capabilityItemHandler = LazyOptional.empty();\n\n @NBTPersist\n private Vector3i size = LocationHelpers.copyLocation(Vector3i.NULL_VECTOR);\n @NBTPersist\n private Vector3d renderOffset = new Vector3d(0, 0, 0);\n private ITextComponent customName = null;\n @NBTPersist\n private int materialId = 0;\n @NBTPersist\n private int rotation = 0;\n @NBTPersist(useDefaultValue = false)\n private List<Vector3i> interfaceLocations = Lists.newArrayList();\n\n /**\n * The previous angle of the lid.\n */\n public float prevLidAngle;\n /**\n * The current angle of the lid.\n */\n public float lidAngle;\n private int playersUsing;\n private boolean recreateNullInventory = true;\n\n private EnumFacingMap<int[]> facingSlots = EnumFacingMap.newMap();\n\n public TileColossalChest() {\n super(RegistryEntries.TILE_ENTITY_COLOSSAL_CHEST);\n }\n\n /**\n * @return the size\n */\n public Vector3i getSize() {\n return size;\n }\n\n /**\n * Set the size.\n * This will also handle the change in inventory size.\n * @param size the size to set\n */\n public void setSize(Vector3i size) {\n this.size = size;\n facingSlots.clear();\n if(isStructureComplete()) {\n setInventory(constructInventory());\n this.inventory.addDirtyMarkListener(this);\n\n // Move all items from the last valid inventory into the new one\n // If the new inventory would be smaller than the old one, the remaining\n // items will be ejected into the world for slot index larger than the new size.\n if(this.lastValidInventory != null) {\n int slot = 0;\n while(slot < Math.min(this.lastValidInventory.getSizeInventory(), this.inventory.getSizeInventory())) {\n ItemStack contents = this.lastValidInventory.getStackInSlot(slot);\n if (!contents.isEmpty()) {\n this.inventory.setInventorySlotContents(slot, contents);\n this.lastValidInventory.setInventorySlotContents(slot, ItemStack.EMPTY);\n }\n slot++;\n }\n if(slot < this.lastValidInventory.getSizeInventory()) {\n InventoryHelpers.dropItems(getWorld(), this.lastValidInventory, getPos());\n }\n this.lastValidInventory = null;\n }\n } else {\n interfaceLocations.clear();\n if(this.inventory != null) {\n if(GeneralConfig.ejectItemsOnDestroy) {\n InventoryHelpers.dropItems(getWorld(), this.inventory, getPos());\n this.lastValidInventory = null;\n } else {\n this.lastValidInventory = this.inventory;\n }\n }\n setInventory(new LargeInventory(0, 0));\n }\n sendUpdate();\n }\n\n public void setMaterial(ChestMaterial material) {\n this.materialId = material.ordinal();\n }\n\n public ChestMaterial getMaterial() {\n return ChestMaterial.VALUES.get(this.materialId);\n }\n\n public SimpleInventory getLastValidInventory() {\n return lastValidInventory;\n }\n\n public void setLastValidInventory(SimpleInventory lastValidInventory) {\n this.lastValidInventory = lastValidInventory;\n }\n\n public int getSizeSingular() {\n return getSize().getX() + 1;\n }\n\n protected boolean isClientSide() {\n return getWorld() != null && getWorld().isRemote;\n }\n\n protected LargeInventory constructInventory() {\n if (!isClientSide() && GeneralConfig.creativeChests) {\n return constructInventoryDebug();\n }\n return !isClientSide() ? new IndexedInventory(calculateInventorySize(), 64) {\n @Override\n public void openInventory(PlayerEntity entityPlayer) {\n if (!entityPlayer.isSpectator()) {\n super.openInventory(entityPlayer);\n triggerPlayerUsageChange(1);\n }\n }\n\n @Override\n public void closeInventory(PlayerEntity entityPlayer) {\n if (!entityPlayer.isSpectator()) {\n super.closeInventory(entityPlayer);\n triggerPlayerUsageChange(-1);\n }\n }\n } : new LargeInventory(calculateInventorySize(), 64);\n }\n\n protected LargeInventory constructInventoryDebug() {\n LargeInventory inv = !isClientSide() ? new IndexedInventory(calculateInventorySize(), 64)\n : new LargeInventory(calculateInventorySize(), 64);\n Random random = new Random();\n for (int i = 0; i < inv.getSizeInventory(); i++) {\n inv.setInventorySlotContents(i, new ItemStack(Iterables.get(ForgeRegistries.ITEMS.getValues(),\n random.nextInt(ForgeRegistries.ITEMS.getValues().size()))));\n }\n return inv;\n }\n\n @Override\n public CompoundNBT getUpdateTag() {\n // Don't send the inventory to the client.\n // The client will receive the data once the gui is opened.\n SimpleInventory oldInventory = this.inventory;\n SimpleInventory oldLastInventory = this.lastValidInventory;\n this.inventory = null;\n this.lastValidInventory = null;\n this.recreateNullInventory = false;\n CompoundNBT tag = super.getUpdateTag();\n this.inventory = oldInventory;\n this.lastValidInventory = oldLastInventory;\n this.recreateNullInventory = true;\n return tag;\n }\n\n @Override\n public void read(CompoundNBT tag) {\n SimpleInventory oldInventory = this.inventory;\n SimpleInventory oldLastInventory = this.lastValidInventory;\n\n if (getWorld() != null && getWorld().isRemote) {\n // Don't read the inventory on the client.\n // The client will receive the data once the gui is opened.\n this.inventory = null;\n this.lastValidInventory = null;\n this.recreateNullInventory = false;\n }\n super.read(tag);\n if (getWorld() != null && getWorld().isRemote) {\n this.inventory = oldInventory;\n this.lastValidInventory = oldLastInventory;\n this.recreateNullInventory = true;\n } else {\n getInventory().read(tag.getCompound(\"inventory\"));\n if (tag.contains(\"lastValidInventory\", Constants.NBT.TAG_COMPOUND)) {\n this.lastValidInventory = new LargeInventory(tag.getInt(\"lastValidInventorySize\"), this.inventory.getInventoryStackLimit());\n this.lastValidInventory.read(tag.getCompound(\"lastValidInventory\"));\n }\n }\n\n if (tag.contains(\"CustomName\", Constants.NBT.TAG_STRING)) {\n this.customName = ITextComponent.Serializer.getComponentFromJson(tag.getString(\"CustomName\"));\n }\n }\n\n @Override\n public CompoundNBT write(CompoundNBT tag) {\n if (this.customName != null) {\n tag.putString(\"CustomName\", ITextComponent.Serializer.toJson(this.customName));\n }\n if (this.inventory != null) {\n CompoundNBT subTag = new CompoundNBT();\n this.inventory.write(subTag);\n tag.put(\"inventory\", subTag);\n }\n if (this.lastValidInventory != null) {\n CompoundNBT subTag = new CompoundNBT();\n this.lastValidInventory.write(subTag);\n tag.put(\"lastValidInventory\", subTag);\n tag.putInt(\"lastValidInventorySize\", this.lastValidInventory.getSizeInventory());\n }\n return super.write(tag);\n }\n\n @Override\n public SUpdateTileEntityPacket getUpdatePacket() {\n return new SUpdateTileEntityPacket(getPos(), 1, getUpdateTag());\n }\n\n protected int calculateInventorySize() {\n int size = getSizeSingular();\n if (size == 1) {\n return 0;\n }\n return (int) Math.ceil((Math.pow(size, 3) * 27) * getMaterial().getInventoryMultiplier() / 9) * 9;\n }\n\n @Override\n public void updateTileEntity() {\n super.updateTileEntity();\n\n // Resynchronize clients with the server state, the last condition makes sure\n // not all chests are synced at the same time.\n if(world != null\n && !this.world.isRemote\n && this.playersUsing != 0\n && WorldHelpers.efficientTick(world, TICK_MODULUS, getPos().hashCode())) {\n this.playersUsing = 0;\n float range = 5.0F;\n @SuppressWarnings(\"unchecked\")\n List<PlayerEntity> entities = this.world.getEntitiesWithinAABB(\n PlayerEntity.class,\n new AxisAlignedBB(\n getPos().add(new Vector3i(-range, -range, -range)),\n getPos().add(new Vector3i(1 + range, 1 + range, 1 + range))\n )\n );\n\n for(PlayerEntity player : entities) {\n if (player.openContainer instanceof ContainerColossalChest) {\n ++this.playersUsing;\n }\n }\n\n world.addBlockEvent(getPos(), getBlockState().getBlock(), 1, playersUsing);\n }\n\n prevLidAngle = lidAngle;\n float increaseAngle = 0.15F / Math.min(5, getSizeSingular());\n if (playersUsing > 0 && lidAngle == 0.0F) {\n world.playSound(\n (double) getPos().getX() + 0.5D,\n (double) getPos().getY() + 0.5D,\n (double) getPos().getZ() + 0.5D,\n SoundEvents.BLOCK_CHEST_OPEN,\n SoundCategory.BLOCKS,\n (float) (0.5F + (0.5F * Math.log(getSizeSingular()))),\n world.rand.nextFloat() * 0.1F + 0.45F + increaseAngle,\n true\n );\n }\n if (playersUsing == 0 && lidAngle > 0.0F || playersUsing > 0 && lidAngle < 1.0F) {\n float preIncreaseAngle = lidAngle;\n if (playersUsing > 0) {\n lidAngle += increaseAngle;\n } else {\n lidAngle -= increaseAngle;\n }\n if (lidAngle > 1.0F) {\n lidAngle = 1.0F;\n }\n float closedAngle = 0.5F;\n if (lidAngle < closedAngle && preIncreaseAngle >= closedAngle) {\n world.playSound(\n (double) getPos().getX() + 0.5D,\n (double) getPos().getY() + 0.5D,\n (double) getPos().getZ() + 0.5D,\n SoundEvents.BLOCK_CHEST_CLOSE,\n SoundCategory.BLOCKS,\n (float) (0.5F + (0.5F * Math.log(getSizeSingular()))),\n world.rand.nextFloat() * 0.05F + 0.45F + increaseAngle,\n true\n );\n }\n if (lidAngle < 0.0F) {\n lidAngle = 0.0F;\n }\n }\n }\n\n @Override\n public boolean receiveClientEvent(int i, int j) {\n if (i == 1) {\n playersUsing = j;\n }\n return true;\n }\n\n private void triggerPlayerUsageChange(int change) {\n if (world != null) {\n playersUsing += change;\n world.addBlockEvent(getPos(), getBlockState().getBlock(), 1, playersUsing);\n }\n }\n\n public void setInventory(SimpleInventory inventory) {\n this.capabilityItemHandler.invalidate();\n this.inventory = inventory;\n if (this.inventory.getSizeInventory() > 0) {\n IItemHandler itemHandler = new InvWrapper(this.inventory);\n this.capabilityItemHandler = LazyOptional.of(() -> itemHandler);\n } else {\n this.capabilityItemHandler = LazyOptional.empty();\n }\n }\n\n protected void ensureInventoryInitialized() {\n if (getWorld() != null && getWorld().isRemote && (inventory == null || inventory.getSizeInventory() != calculateInventorySize())) {\n setInventory(constructInventory());\n }\n }\n\n public INBTInventory getInventory() {\n if(lastValidInventory != null) {\n return new IndexedInventory();\n }\n ensureInventoryInitialized();\n if(inventory == null && this.recreateNullInventory) {\n setInventory(constructInventory());\n }\n return inventory;\n }\n\n @Override\n public <T> LazyOptional<T> getCapability(Capability<T> capability, Direction facing) {\n ensureInventoryInitialized();\n if (this.capabilityItemHandler.isPresent() && capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) {\n return this.capabilityItemHandler.cast();\n }\n return super.getCapability(capability, facing);\n }\n\n @Override\n public boolean canInteractWith(PlayerEntity entityPlayer) {\n return getSizeSingular() > 1 && super.canInteractWith(entityPlayer);\n }\n\n @Override\n @OnlyIn(Dist.CLIENT)\n public AxisAlignedBB getRenderBoundingBox() {\n int size = getSizeSingular();\n return new AxisAlignedBB(getPos().subtract(new Vector3i(size, size, size)), getPos().add(size, size * 2, size));\n }\n\n public void setCenter(Vector3d center) {\n Direction rotation;\n double dx = Math.abs(center.x - getPos().getX());\n double dz = Math.abs(center.z - getPos().getZ());\n boolean equal = (center.x - getPos().getX()) == (center.z - getPos().getZ());\n if(dx > dz || (!equal && getSizeSingular() == 2)) {\n rotation = DirectionHelpers.getEnumFacingFromXSign((int) Math.round(center.x - getPos().getX()));\n } else {\n rotation = DirectionHelpers.getEnumFacingFromZSing((int) Math.round(center.z - getPos().getZ()));\n }\n this.setRotation(rotation);\n this.renderOffset = new Vector3d(getPos().getX() - center.x, getPos().getY() - center.y, getPos().getZ() - center.z);\n }\n\n public void setRotation(Direction rotation) {\n this.rotation = rotation.ordinal();\n }\n\n @Override\n public Direction getRotation() {\n return Direction.byIndex(this.rotation);\n }\n\n public Vector3d getRenderOffset() {\n return this.renderOffset;\n }\n\n public void setRenderOffset(Vector3d renderOffset) {\n this.renderOffset = renderOffset;\n }\n\n /**\n * Callback for when a structure has been detected for a spirit furnace block.\n * @param world The world.\n * @param location The location of one block of the structure.\n * @param size The size of the structure.\n * @param valid If the structure is being validated(/created), otherwise invalidated.\n * @param originCorner The origin corner\n */\n public static void detectStructure(IWorldReader world, BlockPos location, Vector3i size, boolean valid, BlockPos originCorner) {\n\n }\n\n /**\n * @return If the structure is valid.\n */\n public boolean isStructureComplete() {\n return !getSize().equals(Vector3i.NULL_VECTOR);\n }\n\n public static Vector3i getMaxSize() {\n int size = ColossalChestConfig.maxSize - 1;\n return new Vector3i(size, size, size);\n }\n\n public boolean hasCustomName() {\n return customName != null;\n }\n\n public void setCustomName(ITextComponent name) {\n this.customName = name;\n }\n\n public void addInterface(Vector3i blockPos) {\n interfaceLocations.add(blockPos);\n }\n\n public List<Vector3i> getInterfaceLocations() {\n return Collections.unmodifiableList(interfaceLocations);\n }\n\n @Override\n public ITextComponent getDisplayName() {\n return hasCustomName() ? customName : new TranslationTextComponent(\"general.colossalchests.colossalchest\",\n new TranslationTextComponent(getMaterial().getUnlocalizedName()), getSizeSingular());\n }\n\n @Nullable\n @Override\n public Container createMenu(int id, PlayerInventory playerInventory, PlayerEntity playerEntity) {\n return new ContainerColossalChest(id, playerInventory, this.getInventory());\n }\n\n @Override\n @OnlyIn(Dist.CLIENT)\n public float getLidAngle(float partialTicks) {\n return ColossalChestConfig.chestAnimation ? MathHelper.lerp(partialTicks, this.prevLidAngle, this.lidAngle) : 0F;\n }\n}",
"public class TileInterface extends CyclopsTileEntity {\n\n @Delegate\n private final ITickingTile tickingTileComponent = new TickingTileComponent(this);\n\n @NBTPersist\n @Getter\n private Vector3i corePosition = null;\n private WeakReference<TileColossalChest> coreReference = new WeakReference<TileColossalChest>(null);\n\n public TileInterface() {\n super(RegistryEntries.TILE_ENTITY_INTERFACE);\n }\n\n @Override\n public <T> LazyOptional<T> getCapability(@Nonnull Capability<T> capability, Direction facing) {\n TileColossalChest core = getCore();\n if (core != null) {\n LazyOptional<T> t = core.getCapability(capability, facing);\n if (t.isPresent()) {\n return t;\n }\n }\n return super.getCapability(capability, facing);\n }\n\n public void setCorePosition(Vector3i corePosition) {\n this.corePosition = corePosition;\n coreReference = new WeakReference<TileColossalChest>(null);\n }\n\n protected TileColossalChest getCore() {\n if(corePosition == null) {\n return null;\n }\n if (coreReference.get() == null) {\n coreReference = new WeakReference<TileColossalChest>(\n TileHelpers.getSafeTile(getWorld(), new BlockPos(corePosition), TileColossalChest.class).orElse(null));\n }\n return coreReference.get();\n }\n\n}"
] | import com.google.common.collect.Lists;
import lombok.Data;
import lombok.EqualsAndHashCode;
import net.minecraft.block.BlockState;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemUseContext;
import net.minecraft.util.ActionResultType;
import net.minecraft.util.Direction;
import net.minecraft.util.Hand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.vector.Vector3d;
import net.minecraft.util.math.vector.Vector3i;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TranslationTextComponent;
import net.minecraft.world.World;
import org.apache.commons.lang3.tuple.Pair;
import org.cyclops.colossalchests.Advancements;
import org.cyclops.colossalchests.block.ChestMaterial;
import org.cyclops.colossalchests.block.ChestWall;
import org.cyclops.colossalchests.block.ColossalChest;
import org.cyclops.colossalchests.block.IBlockChestMaterial;
import org.cyclops.colossalchests.block.Interface;
import org.cyclops.colossalchests.tileentity.TileColossalChest;
import org.cyclops.colossalchests.tileentity.TileInterface;
import org.cyclops.cyclopscore.block.multi.DetectionResult;
import org.cyclops.cyclopscore.datastructure.Wrapper;
import org.cyclops.cyclopscore.helper.BlockHelpers;
import org.cyclops.cyclopscore.helper.InventoryHelpers;
import org.cyclops.cyclopscore.helper.MinecraftHelpers;
import org.cyclops.cyclopscore.helper.TileHelpers;
import org.cyclops.cyclopscore.inventory.PlayerInventoryIterator;
import org.cyclops.cyclopscore.inventory.SimpleInventory;
import java.util.List; | package org.cyclops.colossalchests.item;
/**
* An item to upgrade chests to the next tier.
* @author rubensworks
*/
@EqualsAndHashCode(callSuper = false)
@Data
public class ItemUpgradeTool extends Item {
private final boolean upgrade;
public ItemUpgradeTool(Properties properties, boolean upgrade) {
super(properties);
this.upgrade = upgrade;
}
@Override
public ActionResultType onItemUseFirst(ItemStack itemStack, ItemUseContext context) {
BlockState blockState = context.getWorld().getBlockState(context.getPos());
if (blockState.getBlock() instanceof IBlockChestMaterial
&& BlockHelpers.getSafeBlockStateProperty(blockState, ColossalChest.ENABLED, false)) {
// Determine the chest core location
BlockPos tileLocation = ColossalChest.getCoreLocation(((IBlockChestMaterial) blockState.getBlock()).getMaterial(), context.getWorld(), context.getPos());
final TileColossalChest tile = TileHelpers.getSafeTile(context.getWorld(), tileLocation, TileColossalChest.class).orElse(null);
// Determine the new material type | ChestMaterial newType = transformType(itemStack, tile.getMaterial()); | 1 |
CagataySonmez/EdgeCloudSim | src/edu/boun/edgecloudsim/applications/sample_app4/FuzzyEdgeOrchestrator.java | [
"public class CloudVM extends Vm {\r\n\tprivate SimSettings.VM_TYPES type;\r\n\r\n\tpublic CloudVM(int id, int userId, double mips, int numberOfPes, int ram,\r\n\t\t\tlong bw, long size, String vmm, CloudletScheduler cloudletScheduler) {\r\n\t\tsuper(id, userId, mips, numberOfPes, ram, bw, size, vmm, cloudletScheduler);\r\n\r\n\t\ttype = SimSettings.VM_TYPES.CLOUD_VM;\r\n\t}\r\n\r\n\tpublic SimSettings.VM_TYPES getVmType(){\r\n\t\treturn type;\r\n\t}\r\n\r\n\t/**\r\n\t * dynamically reconfigures the mips value of a VM in CloudSim\r\n\t * \r\n\t * @param mips new mips value for this VM.\r\n\t */\r\n\tpublic void reconfigureMips(double mips){\r\n\t\tsuper.setMips(mips);\r\n\t\tsuper.getHost().getVmScheduler().deallocatePesForVm(this);\r\n\r\n\t\tList<Double> mipsShareAllocated = new ArrayList<Double>();\r\n\t\tfor(int i= 0; i<getNumberOfPes(); i++)\r\n\t\t\tmipsShareAllocated.add(mips);\r\n\r\n\t\tsuper.getHost().getVmScheduler().allocatePesForVm(this, mipsShareAllocated);\r\n\t}\r\n}\r",
"public class SimManager extends SimEntity {\r\n\tprivate static final int CREATE_TASK = 0;\r\n\tprivate static final int CHECK_ALL_VM = 1;\r\n\tprivate static final int GET_LOAD_LOG = 2;\r\n\tprivate static final int PRINT_PROGRESS = 3;\r\n\tprivate static final int STOP_SIMULATION = 4;\r\n\t\r\n\tprivate String simScenario;\r\n\tprivate String orchestratorPolicy;\r\n\tprivate int numOfMobileDevice;\r\n\tprivate NetworkModel networkModel;\r\n\tprivate MobilityModel mobilityModel;\r\n\tprivate ScenarioFactory scenarioFactory;\r\n\tprivate EdgeOrchestrator edgeOrchestrator;\r\n\tprivate EdgeServerManager edgeServerManager;\r\n\tprivate CloudServerManager cloudServerManager;\r\n\tprivate MobileServerManager mobileServerManager;\r\n\tprivate LoadGeneratorModel loadGeneratorModel;\r\n\tprivate MobileDeviceManager mobileDeviceManager;\r\n\t\r\n\tprivate static SimManager instance = null;\r\n\t\r\n\tpublic SimManager(ScenarioFactory _scenarioFactory, int _numOfMobileDevice, String _simScenario, String _orchestratorPolicy) throws Exception {\r\n\t\tsuper(\"SimManager\");\r\n\t\tsimScenario = _simScenario;\r\n\t\tscenarioFactory = _scenarioFactory;\r\n\t\tnumOfMobileDevice = _numOfMobileDevice;\r\n\t\torchestratorPolicy = _orchestratorPolicy;\r\n\r\n\t\tSimLogger.print(\"Creating tasks...\");\r\n\t\tloadGeneratorModel = scenarioFactory.getLoadGeneratorModel();\r\n\t\tloadGeneratorModel.initializeModel();\r\n\t\tSimLogger.printLine(\"Done, \");\r\n\t\t\r\n\t\tSimLogger.print(\"Creating device locations...\");\r\n\t\tmobilityModel = scenarioFactory.getMobilityModel();\r\n\t\tmobilityModel.initialize();\r\n\t\tSimLogger.printLine(\"Done.\");\r\n\r\n\t\t//Generate network model\r\n\t\tnetworkModel = scenarioFactory.getNetworkModel();\r\n\t\tnetworkModel.initialize();\r\n\t\t\r\n\t\t//Generate edge orchestrator\r\n\t\tedgeOrchestrator = scenarioFactory.getEdgeOrchestrator();\r\n\t\tedgeOrchestrator.initialize();\r\n\t\t\r\n\t\t//Create Physical Servers\r\n\t\tedgeServerManager = scenarioFactory.getEdgeServerManager();\r\n\t\tedgeServerManager.initialize();\r\n\t\t\r\n\t\t//Create Physical Servers on cloud\r\n\t\tcloudServerManager = scenarioFactory.getCloudServerManager();\r\n\t\tcloudServerManager.initialize();\r\n\t\t\r\n\t\t//Create Physical Servers on mobile devices\r\n\t\tmobileServerManager = scenarioFactory.getMobileServerManager();\r\n\t\tmobileServerManager.initialize();\r\n\r\n\t\t//Create Client Manager\r\n\t\tmobileDeviceManager = scenarioFactory.getMobileDeviceManager();\r\n\t\tmobileDeviceManager.initialize();\r\n\t\t\r\n\t\tinstance = this;\r\n\t}\r\n\t\r\n\tpublic static SimManager getInstance(){\r\n\t\treturn instance;\r\n\t}\r\n\t\r\n\t/**\r\n\t * Triggering CloudSim to start simulation\r\n\t */\r\n\tpublic void startSimulation() throws Exception{\r\n\t\t//Starts the simulation\r\n\t\tSimLogger.print(super.getName()+\" is starting...\");\r\n\t\t\r\n\t\t//Start Edge Datacenters & Generate VMs\r\n\t\tedgeServerManager.startDatacenters();\r\n\t\tedgeServerManager.createVmList(mobileDeviceManager.getId());\r\n\t\t\r\n\t\t//Start Edge Datacenters & Generate VMs\r\n\t\tcloudServerManager.startDatacenters();\r\n\t\tcloudServerManager.createVmList(mobileDeviceManager.getId());\r\n\t\t\r\n\t\t//Start Mobile Datacenters & Generate VMs\r\n\t\tmobileServerManager.startDatacenters();\r\n\t\tmobileServerManager.createVmList(mobileDeviceManager.getId());\r\n\t\t\r\n\t\tCloudSim.startSimulation();\r\n\t}\r\n\r\n\tpublic String getSimulationScenario(){\r\n\t\treturn simScenario;\r\n\t}\r\n\r\n\tpublic String getOrchestratorPolicy(){\r\n\t\treturn orchestratorPolicy;\r\n\t}\r\n\t\r\n\tpublic ScenarioFactory getScenarioFactory(){\r\n\t\treturn scenarioFactory;\r\n\t}\r\n\t\r\n\tpublic int getNumOfMobileDevice(){\r\n\t\treturn numOfMobileDevice;\r\n\t}\r\n\t\r\n\tpublic NetworkModel getNetworkModel(){\r\n\t\treturn networkModel;\r\n\t}\r\n\r\n\tpublic MobilityModel getMobilityModel(){\r\n\t\treturn mobilityModel;\r\n\t}\r\n\t\r\n\tpublic EdgeOrchestrator getEdgeOrchestrator(){\r\n\t\treturn edgeOrchestrator;\r\n\t}\r\n\t\r\n\tpublic EdgeServerManager getEdgeServerManager(){\r\n\t\treturn edgeServerManager;\r\n\t}\r\n\t\r\n\tpublic CloudServerManager getCloudServerManager(){\r\n\t\treturn cloudServerManager;\r\n\t}\r\n\t\r\n\tpublic MobileServerManager getMobileServerManager(){\r\n\t\treturn mobileServerManager;\r\n\t}\r\n\r\n\tpublic LoadGeneratorModel getLoadGeneratorModel(){\r\n\t\treturn loadGeneratorModel;\r\n\t}\r\n\t\r\n\tpublic MobileDeviceManager getMobileDeviceManager(){\r\n\t\treturn mobileDeviceManager;\r\n\t}\r\n\t\r\n\t@Override\r\n\tpublic void startEntity() {\r\n\t\tint hostCounter=0;\r\n\r\n\t\tfor(int i= 0; i<edgeServerManager.getDatacenterList().size(); i++) {\r\n\t\t\tList<? extends Host> list = edgeServerManager.getDatacenterList().get(i).getHostList();\r\n\t\t\tfor (int j=0; j < list.size(); j++) {\r\n\t\t\t\tmobileDeviceManager.submitVmList(edgeServerManager.getVmList(hostCounter));\r\n\t\t\t\thostCounter++;\r\n\t\t\t}\r\n\t\t}\r\n\t\t\r\n\t\tfor(int i = 0; i<SimSettings.getInstance().getNumOfCloudHost(); i++) {\r\n\t\t\tmobileDeviceManager.submitVmList(cloudServerManager.getVmList(i));\r\n\t\t}\r\n\r\n\t\tfor(int i=0; i<numOfMobileDevice; i++){\r\n\t\t\tif(mobileServerManager.getVmList(i) != null)\r\n\t\t\t\tmobileDeviceManager.submitVmList(mobileServerManager.getVmList(i));\r\n\t\t}\r\n\t\t\r\n\t\t//Creation of tasks are scheduled here!\r\n\t\tfor(int i=0; i< loadGeneratorModel.getTaskList().size(); i++)\r\n\t\t\tschedule(getId(), loadGeneratorModel.getTaskList().get(i).getStartTime(), CREATE_TASK, loadGeneratorModel.getTaskList().get(i));\r\n\t\t\r\n\t\t//Periodic event loops starts from here!\r\n\t\tschedule(getId(), 5, CHECK_ALL_VM);\r\n\t\tschedule(getId(), SimSettings.getInstance().getSimulationTime()/100, PRINT_PROGRESS);\r\n\t\tschedule(getId(), SimSettings.getInstance().getVmLoadLogInterval(), GET_LOAD_LOG);\r\n\t\tschedule(getId(), SimSettings.getInstance().getSimulationTime(), STOP_SIMULATION);\r\n\t\t\r\n\t\tSimLogger.printLine(\"Done.\");\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void processEvent(SimEvent ev) {\r\n\t\tsynchronized(this){\r\n\t\t\tswitch (ev.getTag()) {\r\n\t\t\tcase CREATE_TASK:\r\n\t\t\t\ttry {\r\n\t\t\t\t\tTaskProperty edgeTask = (TaskProperty) ev.getData();\r\n\t\t\t\t\tmobileDeviceManager.submitTask(edgeTask);\t\t\t\t\t\t\r\n\t\t\t\t} catch (Exception e) {\r\n\t\t\t\t\te.printStackTrace();\r\n\t\t\t\t\tSystem.exit(1);\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\t\t\tcase CHECK_ALL_VM:\r\n\t\t\t\tint totalNumOfVm = SimSettings.getInstance().getNumOfEdgeVMs();\r\n\t\t\t\tif(EdgeVmAllocationPolicy_Custom.getCreatedVmNum() != totalNumOfVm){\r\n\t\t\t\t\tSimLogger.printLine(\"All VMs cannot be created! Terminating simulation...\");\r\n\t\t\t\t\tSystem.exit(1);\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\t\t\tcase GET_LOAD_LOG:\r\n\t\t\t\tSimLogger.getInstance().addVmUtilizationLog(\r\n\t\t\t\t\t\tCloudSim.clock(),\r\n\t\t\t\t\t\tedgeServerManager.getAvgUtilization(),\r\n\t\t\t\t\t\tcloudServerManager.getAvgUtilization(),\r\n\t\t\t\t\t\tmobileServerManager.getAvgUtilization());\r\n\t\t\t\t\r\n\t\t\t\tschedule(getId(), SimSettings.getInstance().getVmLoadLogInterval(), GET_LOAD_LOG);\r\n\t\t\t\tbreak;\r\n\t\t\tcase PRINT_PROGRESS:\r\n\t\t\t\tint progress = (int)((CloudSim.clock()*100)/SimSettings.getInstance().getSimulationTime());\r\n\t\t\t\tif(progress % 10 == 0)\r\n\t\t\t\t\tSimLogger.print(Integer.toString(progress));\r\n\t\t\t\telse\r\n\t\t\t\t\tSimLogger.print(\".\");\r\n\t\t\t\tif(CloudSim.clock() < SimSettings.getInstance().getSimulationTime())\r\n\t\t\t\t\tschedule(getId(), SimSettings.getInstance().getSimulationTime()/100, PRINT_PROGRESS);\r\n\r\n\t\t\t\tbreak;\r\n\t\t\tcase STOP_SIMULATION:\r\n\t\t\t\tSimLogger.printLine(\"100\");\r\n\t\t\t\tCloudSim.terminateSimulation();\r\n\t\t\t\ttry {\r\n\t\t\t\t\tSimLogger.getInstance().simStopped();\r\n\t\t\t\t} catch (IOException e) {\r\n\t\t\t\t\te.printStackTrace();\r\n\t\t\t\t\tSystem.exit(1);\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\t\t\tdefault:\r\n\t\t\t\tSimLogger.printLine(getName() + \": unknown event type\");\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void shutdownEntity() {\r\n\t\tedgeServerManager.terminateDatacenters();\r\n\t\tcloudServerManager.terminateDatacenters();\r\n\t\tmobileServerManager.terminateDatacenters();\r\n\t}\r\n}\r",
"public class SimSettings {\r\n\tprivate static SimSettings instance = null;\r\n\tprivate Document edgeDevicesDoc = null;\r\n\r\n\tpublic static final double CLIENT_ACTIVITY_START_TIME = 10;\r\n\r\n\t//enumarations for the VM types\r\n\tpublic static enum VM_TYPES { MOBILE_VM, EDGE_VM, CLOUD_VM }\r\n\r\n\t//enumarations for the VM types\r\n\tpublic static enum NETWORK_DELAY_TYPES { WLAN_DELAY, MAN_DELAY, WAN_DELAY, GSM_DELAY }\r\n\r\n\t//predifined IDs for the components.\r\n\tpublic static final int CLOUD_DATACENTER_ID = 1000;\r\n\tpublic static final int MOBILE_DATACENTER_ID = 1001;\r\n\tpublic static final int EDGE_ORCHESTRATOR_ID = 1002;\r\n\tpublic static final int GENERIC_EDGE_DEVICE_ID = 1003;\r\n\r\n\t//delimiter for output file.\r\n\tpublic static final String DELIMITER = \";\";\r\n\r\n\tprivate double SIMULATION_TIME; //minutes unit in properties file\r\n\tprivate double WARM_UP_PERIOD; //minutes unit in properties file\r\n\tprivate double INTERVAL_TO_GET_VM_LOAD_LOG; //minutes unit in properties file\r\n\tprivate double INTERVAL_TO_GET_LOCATION_LOG; //minutes unit in properties file\r\n\tprivate double INTERVAL_TO_GET_AP_DELAY_LOG; //minutes unit in properties file\r\n\tprivate boolean FILE_LOG_ENABLED; //boolean to check file logging option\r\n\tprivate boolean DEEP_FILE_LOG_ENABLED; //boolean to check deep file logging option\r\n\r\n\tprivate int MIN_NUM_OF_MOBILE_DEVICES;\r\n\tprivate int MAX_NUM_OF_MOBILE_DEVICES;\r\n\tprivate int MOBILE_DEVICE_COUNTER_SIZE;\r\n\tprivate int WLAN_RANGE;\r\n\r\n\tprivate int NUM_OF_EDGE_DATACENTERS;\r\n\tprivate int NUM_OF_EDGE_HOSTS;\r\n\tprivate int NUM_OF_EDGE_VMS;\r\n\tprivate int NUM_OF_PLACE_TYPES;\r\n\r\n\tprivate double WAN_PROPAGATION_DELAY; //seconds unit in properties file\r\n\tprivate double GSM_PROPAGATION_DELAY; //seconds unit in properties file\r\n\tprivate double LAN_INTERNAL_DELAY; //seconds unit in properties file\r\n\tprivate int BANDWITH_WLAN; //Mbps unit in properties file\r\n\tprivate int BANDWITH_MAN; //Mbps unit in properties file\r\n\tprivate int BANDWITH_WAN; //Mbps unit in properties file\r\n\tprivate int BANDWITH_GSM; //Mbps unit in properties file\r\n\r\n\tprivate int NUM_OF_HOST_ON_CLOUD_DATACENTER;\r\n\tprivate int NUM_OF_VM_ON_CLOUD_HOST;\r\n\tprivate int CORE_FOR_CLOUD_VM;\r\n\tprivate int MIPS_FOR_CLOUD_VM; //MIPS\r\n\tprivate int RAM_FOR_CLOUD_VM; //MB\r\n\tprivate int STORAGE_FOR_CLOUD_VM; //Byte\r\n\r\n\tprivate int CORE_FOR_VM;\r\n\tprivate int MIPS_FOR_VM; //MIPS\r\n\tprivate int RAM_FOR_VM; //MB\r\n\tprivate int STORAGE_FOR_VM; //Byte\r\n\r\n\tprivate String[] SIMULATION_SCENARIOS;\r\n\tprivate String[] ORCHESTRATOR_POLICIES;\r\n\r\n\tprivate double NORTHERN_BOUND;\r\n\tprivate double EASTERN_BOUND;\r\n\tprivate double SOUTHERN_BOUND;\r\n\tprivate double WESTERN_BOUND;\r\n\r\n\t// mean waiting time (minute) is stored for each place types\r\n\tprivate double[] mobilityLookUpTable;\r\n\r\n\t// following values are stored for each applications defined in applications.xml\r\n\t// [0] usage percentage (%)\r\n\t// [1] prob. of selecting cloud (%)\r\n\t// [2] poisson mean (sec)\r\n\t// [3] active period (sec)\r\n\t// [4] idle period (sec)\r\n\t// [5] avg data upload (KB)\r\n\t// [6] avg data download (KB)\r\n\t// [7] avg task length (MI)\r\n\t// [8] required # of cores\r\n\t// [9] vm utilization on edge (%)\r\n\t// [10] vm utilization on cloud (%)\r\n\t// [11] vm utilization on mobile (%)\r\n\t// [12] delay sensitivity [0-1]\r\n\tprivate double[][] taskLookUpTable = null;\r\n\r\n\tprivate String[] taskNames = null;\r\n\r\n\tprivate SimSettings() {\r\n\t\tNUM_OF_PLACE_TYPES = 0;\r\n\t}\r\n\r\n\tpublic static SimSettings getInstance() {\r\n\t\tif(instance == null) {\r\n\t\t\tinstance = new SimSettings();\r\n\t\t}\r\n\t\treturn instance;\r\n\t}\r\n\r\n\t/**\r\n\t * Reads configuration file and stores information to local variables\r\n\t * @param propertiesFile\r\n\t * @return\r\n\t */\r\n\tpublic boolean initialize(String propertiesFile, String edgeDevicesFile, String applicationsFile){\r\n\t\tboolean result = false;\r\n\t\tInputStream input = null;\r\n\t\ttry {\r\n\t\t\tinput = new FileInputStream(propertiesFile);\r\n\r\n\t\t\t// load a properties file\r\n\t\t\tProperties prop = new Properties();\r\n\t\t\tprop.load(input);\r\n\r\n\t\t\tSIMULATION_TIME = (double)60 * Double.parseDouble(prop.getProperty(\"simulation_time\")); //seconds\r\n\t\t\tWARM_UP_PERIOD = (double)60 * Double.parseDouble(prop.getProperty(\"warm_up_period\")); //seconds\r\n\t\t\tINTERVAL_TO_GET_VM_LOAD_LOG = (double)60 * Double.parseDouble(prop.getProperty(\"vm_load_check_interval\")); //seconds\r\n\t\t\tINTERVAL_TO_GET_LOCATION_LOG = (double)60 * Double.parseDouble(prop.getProperty(\"location_check_interval\")); //seconds\r\n\t\t\tINTERVAL_TO_GET_AP_DELAY_LOG = (double)60 * Double.parseDouble(prop.getProperty(\"ap_delay_check_interval\", \"0\")); //seconds\t\t\r\n\t\t\tFILE_LOG_ENABLED = Boolean.parseBoolean(prop.getProperty(\"file_log_enabled\"));\r\n\t\t\tDEEP_FILE_LOG_ENABLED = Boolean.parseBoolean(prop.getProperty(\"deep_file_log_enabled\"));\r\n\r\n\t\t\tMIN_NUM_OF_MOBILE_DEVICES = Integer.parseInt(prop.getProperty(\"min_number_of_mobile_devices\"));\r\n\t\t\tMAX_NUM_OF_MOBILE_DEVICES = Integer.parseInt(prop.getProperty(\"max_number_of_mobile_devices\"));\r\n\t\t\tMOBILE_DEVICE_COUNTER_SIZE = Integer.parseInt(prop.getProperty(\"mobile_device_counter_size\"));\r\n\t\t\tWLAN_RANGE = Integer.parseInt(prop.getProperty(\"wlan_range\", \"0\"));\r\n\r\n\t\t\tWAN_PROPAGATION_DELAY = Double.parseDouble(prop.getProperty(\"wan_propagation_delay\", \"0\"));\r\n\t\t\tGSM_PROPAGATION_DELAY = Double.parseDouble(prop.getProperty(\"gsm_propagation_delay\", \"0\"));\r\n\t\t\tLAN_INTERNAL_DELAY = Double.parseDouble(prop.getProperty(\"lan_internal_delay\", \"0\"));\r\n\t\t\tBANDWITH_WLAN = 1000 * Integer.parseInt(prop.getProperty(\"wlan_bandwidth\"));\r\n\t\t\tBANDWITH_MAN = 1000 * Integer.parseInt(prop.getProperty(\"man_bandwidth\", \"0\"));\r\n\t\t\tBANDWITH_WAN = 1000 * Integer.parseInt(prop.getProperty(\"wan_bandwidth\", \"0\"));\r\n\t\t\tBANDWITH_GSM = 1000 * Integer.parseInt(prop.getProperty(\"gsm_bandwidth\", \"0\"));\r\n\r\n\t\t\tNUM_OF_HOST_ON_CLOUD_DATACENTER = Integer.parseInt(prop.getProperty(\"number_of_host_on_cloud_datacenter\"));\r\n\t\t\tNUM_OF_VM_ON_CLOUD_HOST = Integer.parseInt(prop.getProperty(\"number_of_vm_on_cloud_host\"));\r\n\t\t\tCORE_FOR_CLOUD_VM = Integer.parseInt(prop.getProperty(\"core_for_cloud_vm\"));\r\n\t\t\tMIPS_FOR_CLOUD_VM = Integer.parseInt(prop.getProperty(\"mips_for_cloud_vm\"));\r\n\t\t\tRAM_FOR_CLOUD_VM = Integer.parseInt(prop.getProperty(\"ram_for_cloud_vm\"));\r\n\t\t\tSTORAGE_FOR_CLOUD_VM = Integer.parseInt(prop.getProperty(\"storage_for_cloud_vm\"));\r\n\r\n\t\t\tRAM_FOR_VM = Integer.parseInt(prop.getProperty(\"ram_for_mobile_vm\"));\r\n\t\t\tCORE_FOR_VM = Integer.parseInt(prop.getProperty(\"core_for_mobile_vm\"));\r\n\t\t\tMIPS_FOR_VM = Integer.parseInt(prop.getProperty(\"mips_for_mobile_vm\"));\r\n\t\t\tSTORAGE_FOR_VM = Integer.parseInt(prop.getProperty(\"storage_for_mobile_vm\"));\r\n\r\n\t\t\tORCHESTRATOR_POLICIES = prop.getProperty(\"orchestrator_policies\").split(\",\");\r\n\r\n\t\t\tSIMULATION_SCENARIOS = prop.getProperty(\"simulation_scenarios\").split(\",\");\r\n\r\n\t\t\tNORTHERN_BOUND = Double.parseDouble(prop.getProperty(\"northern_bound\", \"0\"));\r\n\t\t\tSOUTHERN_BOUND = Double.parseDouble(prop.getProperty(\"southern_bound\", \"0\"));\r\n\t\t\tEASTERN_BOUND = Double.parseDouble(prop.getProperty(\"eastern_bound\", \"0\"));\r\n\t\t\tWESTERN_BOUND = Double.parseDouble(prop.getProperty(\"western_bound\", \"0\"));\r\n\r\n\t\t\t//avg waiting time in a place (min)\r\n\t\t\tdouble place1_mean_waiting_time = Double.parseDouble(prop.getProperty(\"attractiveness_L1_mean_waiting_time\"));\r\n\t\t\tdouble place2_mean_waiting_time = Double.parseDouble(prop.getProperty(\"attractiveness_L2_mean_waiting_time\"));\r\n\t\t\tdouble place3_mean_waiting_time = Double.parseDouble(prop.getProperty(\"attractiveness_L3_mean_waiting_time\"));\r\n\r\n\t\t\t//mean waiting time (minute)\r\n\t\t\tmobilityLookUpTable = new double[]{\r\n\t\t\t\t\tplace1_mean_waiting_time, //ATTRACTIVENESS_L1\r\n\t\t\t\t\tplace2_mean_waiting_time, //ATTRACTIVENESS_L2\r\n\t\t\t\t\tplace3_mean_waiting_time //ATTRACTIVENESS_L3\r\n\t\t\t};\r\n\r\n\r\n\t\t} catch (IOException ex) {\r\n\t\t\tex.printStackTrace();\r\n\t\t} finally {\r\n\t\t\tif (input != null) {\r\n\t\t\t\ttry {\r\n\t\t\t\t\tinput.close();\r\n\t\t\t\t\tresult = true;\r\n\t\t\t\t} catch (IOException e) {\r\n\t\t\t\t\te.printStackTrace();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\tparseApplicationsXML(applicationsFile);\r\n\t\tparseEdgeDevicesXML(edgeDevicesFile);\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the parsed XML document for edge_devices.xml\r\n\t */\r\n\tpublic Document getEdgeDevicesDocument(){\r\n\t\treturn edgeDevicesDoc;\r\n\t}\r\n\r\n\r\n\t/**\r\n\t * returns simulation time (in seconds unit) from properties file\r\n\t */\r\n\tpublic double getSimulationTime()\r\n\t{\r\n\t\treturn SIMULATION_TIME;\r\n\t}\r\n\r\n\t/**\r\n\t * returns warm up period (in seconds unit) from properties file\r\n\t */\r\n\tpublic double getWarmUpPeriod()\r\n\t{\r\n\t\treturn WARM_UP_PERIOD; \r\n\t}\r\n\r\n\t/**\r\n\t * returns VM utilization log collection interval (in seconds unit) from properties file\r\n\t */\r\n\tpublic double getVmLoadLogInterval()\r\n\t{\r\n\t\treturn INTERVAL_TO_GET_VM_LOAD_LOG; \r\n\t}\r\n\r\n\t/**\r\n\t * returns VM location log collection interval (in seconds unit) from properties file\r\n\t */\r\n\tpublic double getLocationLogInterval()\r\n\t{\r\n\t\treturn INTERVAL_TO_GET_LOCATION_LOG; \r\n\t}\r\n\r\n\t/**\r\n\t * returns VM location log collection interval (in seconds unit) from properties file\r\n\t */\r\n\tpublic double getApDelayLogInterval()\r\n\t{\r\n\t\treturn INTERVAL_TO_GET_AP_DELAY_LOG; \r\n\t}\r\n\r\n\t/**\r\n\t * returns deep statistics logging status from properties file\r\n\t */\r\n\tpublic boolean getDeepFileLoggingEnabled()\r\n\t{\r\n\t\treturn FILE_LOG_ENABLED && DEEP_FILE_LOG_ENABLED; \r\n\t}\r\n\r\n\t/**\r\n\t * returns deep statistics logging status from properties file\r\n\t */\r\n\tpublic boolean getFileLoggingEnabled()\r\n\t{\r\n\t\treturn FILE_LOG_ENABLED; \r\n\t}\r\n\r\n\t/**\r\n\t * returns WAN propagation delay (in second unit) from properties file\r\n\t */\r\n\tpublic double getWanPropagationDelay()\r\n\t{\r\n\t\treturn WAN_PROPAGATION_DELAY;\r\n\t}\r\n\r\n\t/**\r\n\t * returns GSM propagation delay (in second unit) from properties file\r\n\t */\r\n\tpublic double getGsmPropagationDelay()\r\n\t{\r\n\t\treturn GSM_PROPAGATION_DELAY;\r\n\t}\r\n\r\n\t/**\r\n\t * returns internal LAN propagation delay (in second unit) from properties file\r\n\t */\r\n\tpublic double getInternalLanDelay()\r\n\t{\r\n\t\treturn LAN_INTERNAL_DELAY;\r\n\t}\r\n\r\n\t/**\r\n\t * returns WLAN bandwidth (in Mbps unit) from properties file\r\n\t */\r\n\tpublic int getWlanBandwidth()\r\n\t{\r\n\t\treturn BANDWITH_WLAN;\r\n\t}\r\n\r\n\t/**\r\n\t * returns MAN bandwidth (in Mbps unit) from properties file\r\n\t */\r\n\tpublic int getManBandwidth()\r\n\t{\r\n\t\treturn BANDWITH_MAN;\r\n\t}\r\n\r\n\t/**\r\n\t * returns WAN bandwidth (in Mbps unit) from properties file\r\n\t */\r\n\tpublic int getWanBandwidth()\r\n\t{\r\n\t\treturn BANDWITH_WAN; \r\n\t}\r\n\r\n\t/**\r\n\t * returns GSM bandwidth (in Mbps unit) from properties file\r\n\t */\r\n\tpublic int getGsmBandwidth()\r\n\t{\r\n\t\treturn BANDWITH_GSM;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the minimum number of the mobile devices used in the simulation\r\n\t */\r\n\tpublic int getMinNumOfMobileDev()\r\n\t{\r\n\t\treturn MIN_NUM_OF_MOBILE_DEVICES;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the maximum number of the mobile devices used in the simulation\r\n\t */\r\n\tpublic int getMaxNumOfMobileDev()\r\n\t{\r\n\t\treturn MAX_NUM_OF_MOBILE_DEVICES;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the number of increase on mobile devices\r\n\t * while iterating from min to max mobile device\r\n\t */\r\n\tpublic int getMobileDevCounterSize()\r\n\t{\r\n\t\treturn MOBILE_DEVICE_COUNTER_SIZE;\r\n\t}\r\n\r\n\t/**\r\n\t * returns edge device range in meter\r\n\t */\r\n\tpublic int getWlanRange()\r\n\t{\r\n\t\treturn WLAN_RANGE;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the number of edge datacenters\r\n\t */\r\n\tpublic int getNumOfEdgeDatacenters()\r\n\t{\r\n\t\treturn NUM_OF_EDGE_DATACENTERS;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the number of edge hosts running on the datacenters\r\n\t */\r\n\tpublic int getNumOfEdgeHosts()\r\n\t{\r\n\t\treturn NUM_OF_EDGE_HOSTS;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the number of edge VMs running on the hosts\r\n\t */\r\n\tpublic int getNumOfEdgeVMs()\r\n\t{\r\n\t\treturn NUM_OF_EDGE_VMS;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the number of different place types\r\n\t */\r\n\tpublic int getNumOfPlaceTypes()\r\n\t{\r\n\t\treturn NUM_OF_PLACE_TYPES;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the number of cloud datacenters\r\n\t */\r\n\tpublic int getNumOfCloudHost()\r\n\t{\r\n\t\treturn NUM_OF_HOST_ON_CLOUD_DATACENTER;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the number of cloud VMs per Host\r\n\t */\r\n\tpublic int getNumOfCloudVMsPerHost()\r\n\t{\r\n\t\treturn NUM_OF_VM_ON_CLOUD_HOST;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the total number of cloud VMs\r\n\t */\r\n\tpublic int getNumOfCloudVMs()\r\n\t{\r\n\t\treturn NUM_OF_VM_ON_CLOUD_HOST * NUM_OF_HOST_ON_CLOUD_DATACENTER;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the number of cores for cloud VMs\r\n\t */\r\n\tpublic int getCoreForCloudVM()\r\n\t{\r\n\t\treturn CORE_FOR_CLOUD_VM;\r\n\t}\r\n\r\n\t/**\r\n\t * returns MIPS of the central cloud VMs\r\n\t */\r\n\tpublic int getMipsForCloudVM()\r\n\t{\r\n\t\treturn MIPS_FOR_CLOUD_VM;\r\n\t}\r\n\r\n\t/**\r\n\t * returns RAM of the central cloud VMs\r\n\t */\r\n\tpublic int getRamForCloudVM()\r\n\t{\r\n\t\treturn RAM_FOR_CLOUD_VM;\r\n\t}\r\n\r\n\t/**\r\n\t * returns Storage of the central cloud VMs\r\n\t */\r\n\tpublic int getStorageForCloudVM()\r\n\t{\r\n\t\treturn STORAGE_FOR_CLOUD_VM;\r\n\t}\r\n\r\n\t/**\r\n\t * returns RAM of the mobile (processing unit) VMs\r\n\t */\r\n\tpublic int getRamForMobileVM()\r\n\t{\r\n\t\treturn RAM_FOR_VM;\r\n\t}\r\n\r\n\t/**\r\n\t * returns the number of cores for mobile VMs\r\n\t */\r\n\tpublic int getCoreForMobileVM()\r\n\t{\r\n\t\treturn CORE_FOR_VM;\r\n\t}\r\n\r\n\t/**\r\n\t * returns MIPS of the mobile (processing unit) VMs\r\n\t */\r\n\tpublic int getMipsForMobileVM()\r\n\t{\r\n\t\treturn MIPS_FOR_VM;\r\n\t}\r\n\r\n\t/**\r\n\t * returns Storage of the mobile (processing unit) VMs\r\n\t */\r\n\tpublic int getStorageForMobileVM()\r\n\t{\r\n\t\treturn STORAGE_FOR_VM;\r\n\t}\r\n\r\n\t/**\r\n\t * returns simulation screnarios as string\r\n\t */\r\n\tpublic String[] getSimulationScenarios()\r\n\t{\r\n\t\treturn SIMULATION_SCENARIOS;\r\n\t}\r\n\r\n\t/**\r\n\t * returns orchestrator policies as string\r\n\t */\r\n\tpublic String[] getOrchestratorPolicies()\r\n\t{\r\n\t\treturn ORCHESTRATOR_POLICIES;\r\n\t}\r\n\r\n\r\n\tpublic double getNorthernBound() {\r\n\t\treturn NORTHERN_BOUND;\r\n\t}\r\n\r\n\tpublic double getEasternBound() {\r\n\t\treturn EASTERN_BOUND;\r\n\t}\r\n\r\n\tpublic double getSouthernBound() {\r\n\t\treturn SOUTHERN_BOUND;\r\n\t}\r\n\r\n\tpublic double getWesternBound() {\r\n\t\treturn WESTERN_BOUND;\r\n\t}\r\n\r\n\t/**\r\n\t * returns mobility characteristic within an array\r\n\t * the result includes mean waiting time (minute) or each place type\r\n\t */ \r\n\tpublic double[] getMobilityLookUpTable()\r\n\t{\r\n\t\treturn mobilityLookUpTable;\r\n\t}\r\n\r\n\t/**\r\n\t * returns application characteristic within two dimensional array\r\n\t * the result includes the following values for each application type\r\n\t * [0] usage percentage (%)\r\n\t * [1] prob. of selecting cloud (%)\r\n\t * [2] poisson mean (sec)\r\n\t * [3] active period (sec)\r\n\t * [4] idle period (sec)\r\n\t * [5] avg data upload (KB)\r\n\t * [6] avg data download (KB)\r\n\t * [7] avg task length (MI)\r\n\t * [8] required # of cores\r\n\t * [9] vm utilization on edge (%)\r\n\t * [10] vm utilization on cloud (%)\r\n\t * [11] vm utilization on mobile (%)\r\n\t * [12] delay sensitivity [0-1]\r\n\t * [13] maximum delay requirement (sec)\r\n\t */ \r\n\tpublic double[][] getTaskLookUpTable()\r\n\t{\r\n\t\treturn taskLookUpTable;\r\n\t}\r\n\r\n\tpublic double[] getTaskProperties(String taskName) {\r\n\t\tdouble[] result = null;\r\n\t\tint index = -1;\r\n\t\tfor (int i=0;i<taskNames.length;i++) {\r\n\t\t\tif (taskNames[i].equals(taskName)) {\r\n\t\t\t\tindex = i;\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif(index >= 0 && index < taskLookUpTable.length)\r\n\t\t\tresult = taskLookUpTable[index];\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tpublic String getTaskName(int taskType)\r\n\t{\r\n\t\treturn taskNames[taskType];\r\n\t}\r\n\r\n\tprivate void isAttributePresent(Element element, String key) {\r\n\t\tString value = element.getAttribute(key);\r\n\t\tif (value.isEmpty() || value == null){\r\n\t\t\tthrow new IllegalArgumentException(\"Attribute '\" + key + \"' is not found in '\" + element.getNodeName() +\"'\");\r\n\t\t}\r\n\t}\r\n\r\n\tprivate void isElementPresent(Element element, String key) {\r\n\t\ttry {\r\n\t\t\tString value = element.getElementsByTagName(key).item(0).getTextContent();\r\n\t\t\tif (value.isEmpty() || value == null){\r\n\t\t\t\tthrow new IllegalArgumentException(\"Element '\" + key + \"' is not found in '\" + element.getNodeName() +\"'\");\r\n\t\t\t}\r\n\t\t} catch (Exception e) {\r\n\t\t\tthrow new IllegalArgumentException(\"Element '\" + key + \"' is not found in '\" + element.getNodeName() +\"'\");\r\n\t\t}\r\n\t}\r\n\r\n\tprivate Boolean checkElement(Element element, String key) {\r\n\t\tBoolean result = true;\r\n\t\ttry {\r\n\t\t\tString value = element.getElementsByTagName(key).item(0).getTextContent();\r\n\t\t\tif (value.isEmpty() || value == null){\r\n\t\t\t\tresult = false;\r\n\t\t\t}\r\n\t\t} catch (Exception e) {\r\n\t\t\tresult = false;\r\n\t\t}\r\n\r\n\t\treturn result;\r\n\t}\r\n\r\n\tprivate void parseApplicationsXML(String filePath)\r\n\t{\r\n\t\tDocument doc = null;\r\n\t\ttry {\t\r\n\t\t\tFile devicesFile = new File(filePath);\r\n\t\t\tDocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();\r\n\t\t\tDocumentBuilder dBuilder = dbFactory.newDocumentBuilder();\r\n\t\t\tdoc = dBuilder.parse(devicesFile);\r\n\t\t\tdoc.getDocumentElement().normalize();\r\n\r\n\t\t\tString mandatoryAttributes[] = {\r\n\t\t\t\t\t\"usage_percentage\", //usage percentage [0-100]\r\n\t\t\t\t\t\"prob_cloud_selection\", //prob. of selecting cloud [0-100]\r\n\t\t\t\t\t\"poisson_interarrival\", //poisson mean (sec)\r\n\t\t\t\t\t\"active_period\", //active period (sec)\r\n\t\t\t\t\t\"idle_period\", //idle period (sec)\r\n\t\t\t\t\t\"data_upload\", //avg data upload (KB)\r\n\t\t\t\t\t\"data_download\", //avg data download (KB)\r\n\t\t\t\t\t\"task_length\", //avg task length (MI)\r\n\t\t\t\t\t\"required_core\", //required # of core\r\n\t\t\t\t\t\"vm_utilization_on_edge\", //vm utilization on edge vm [0-100]\r\n\t\t\t\t\t\"vm_utilization_on_cloud\", //vm utilization on cloud vm [0-100]\r\n\t\t\t\t\t\"vm_utilization_on_mobile\", //vm utilization on mobile vm [0-100]\r\n\t\t\t\"delay_sensitivity\"}; //delay_sensitivity [0-1]\r\n\r\n\t\t\tString optionalAttributes[] = {\r\n\t\t\t\"max_delay_requirement\"}; //maximum delay requirement (sec)\r\n\r\n\t\t\tNodeList appList = doc.getElementsByTagName(\"application\");\r\n\t\t\ttaskLookUpTable = new double[appList.getLength()]\r\n\t\t\t\t\t[mandatoryAttributes.length + optionalAttributes.length];\r\n\r\n\t\t\ttaskNames = new String[appList.getLength()];\r\n\t\t\tfor (int i = 0; i < appList.getLength(); i++) {\r\n\t\t\t\tNode appNode = appList.item(i);\r\n\r\n\t\t\t\tElement appElement = (Element) appNode;\r\n\t\t\t\tisAttributePresent(appElement, \"name\");\r\n\t\t\t\tString taskName = appElement.getAttribute(\"name\");\r\n\t\t\t\ttaskNames[i] = taskName;\r\n\r\n\t\t\t\tfor(int m=0; m<mandatoryAttributes.length; m++){\r\n\t\t\t\t\tisElementPresent(appElement, mandatoryAttributes[m]);\r\n\t\t\t\t\ttaskLookUpTable[i][m] = Double.parseDouble(appElement.\r\n\t\t\t\t\t\t\tgetElementsByTagName(mandatoryAttributes[m]).item(0).getTextContent());\r\n\t\t\t\t}\r\n\r\n\t\t\t\tfor(int o=0; o<optionalAttributes.length; o++){\r\n\t\t\t\t\tdouble value = 0;\r\n\t\t\t\t\tif(checkElement(appElement, optionalAttributes[o]))\r\n\t\t\t\t\t\tvalue = Double.parseDouble(appElement.getElementsByTagName(optionalAttributes[o]).item(0).getTextContent());\r\n\r\n\t\t\t\t\ttaskLookUpTable[i][mandatoryAttributes.length + o] = value;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t} catch (Exception e) {\r\n\t\t\tSimLogger.printLine(\"Edge Devices XML cannot be parsed! Terminating simulation...\");\r\n\t\t\te.printStackTrace();\r\n\t\t\tSystem.exit(1);\r\n\t\t}\r\n\t}\r\n\r\n\tprivate void parseEdgeDevicesXML(String filePath)\r\n\t{\r\n\t\ttry {\t\r\n\t\t\tFile devicesFile = new File(filePath);\r\n\t\t\tDocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();\r\n\t\t\tDocumentBuilder dBuilder = dbFactory.newDocumentBuilder();\r\n\t\t\tedgeDevicesDoc = dBuilder.parse(devicesFile);\r\n\t\t\tedgeDevicesDoc.getDocumentElement().normalize();\r\n\r\n\t\t\tNodeList datacenterList = edgeDevicesDoc.getElementsByTagName(\"datacenter\");\r\n\t\t\tfor (int i = 0; i < datacenterList.getLength(); i++) {\r\n\t\t\t\tNUM_OF_EDGE_DATACENTERS++;\r\n\t\t\t\tNode datacenterNode = datacenterList.item(i);\r\n\r\n\t\t\t\tElement datacenterElement = (Element) datacenterNode;\r\n\t\t\t\tisAttributePresent(datacenterElement, \"arch\");\r\n\t\t\t\tisAttributePresent(datacenterElement, \"os\");\r\n\t\t\t\tisAttributePresent(datacenterElement, \"vmm\");\r\n\t\t\t\tisElementPresent(datacenterElement, \"costPerBw\");\r\n\t\t\t\tisElementPresent(datacenterElement, \"costPerSec\");\r\n\t\t\t\tisElementPresent(datacenterElement, \"costPerMem\");\r\n\t\t\t\tisElementPresent(datacenterElement, \"costPerStorage\");\r\n\r\n\t\t\t\tElement location = (Element)datacenterElement.getElementsByTagName(\"location\").item(0);\r\n\t\t\t\tisElementPresent(location, \"attractiveness\");\r\n\t\t\t\tisElementPresent(location, \"wlan_id\");\r\n\t\t\t\tisElementPresent(location, \"x_pos\");\r\n\t\t\t\tisElementPresent(location, \"y_pos\");\r\n\r\n\t\t\t\tString attractiveness = location.getElementsByTagName(\"attractiveness\").item(0).getTextContent();\r\n\t\t\t\tint placeTypeIndex = Integer.parseInt(attractiveness);\r\n\t\t\t\tif(NUM_OF_PLACE_TYPES < placeTypeIndex+1)\r\n\t\t\t\t\tNUM_OF_PLACE_TYPES = placeTypeIndex+1;\r\n\r\n\t\t\t\tNodeList hostList = datacenterElement.getElementsByTagName(\"host\");\r\n\t\t\t\tfor (int j = 0; j < hostList.getLength(); j++) {\r\n\t\t\t\t\tNUM_OF_EDGE_HOSTS++;\r\n\t\t\t\t\tNode hostNode = hostList.item(j);\r\n\r\n\t\t\t\t\tElement hostElement = (Element) hostNode;\r\n\t\t\t\t\tisElementPresent(hostElement, \"core\");\r\n\t\t\t\t\tisElementPresent(hostElement, \"mips\");\r\n\t\t\t\t\tisElementPresent(hostElement, \"ram\");\r\n\t\t\t\t\tisElementPresent(hostElement, \"storage\");\r\n\r\n\t\t\t\t\tNodeList vmList = hostElement.getElementsByTagName(\"VM\");\r\n\t\t\t\t\tfor (int k = 0; k < vmList.getLength(); k++) {\r\n\t\t\t\t\t\tNUM_OF_EDGE_VMS++;\r\n\t\t\t\t\t\tNode vmNode = vmList.item(k);\r\n\r\n\t\t\t\t\t\tElement vmElement = (Element) vmNode;\r\n\t\t\t\t\t\tisAttributePresent(vmElement, \"vmm\");\r\n\t\t\t\t\t\tisElementPresent(vmElement, \"core\");\r\n\t\t\t\t\t\tisElementPresent(vmElement, \"mips\");\r\n\t\t\t\t\t\tisElementPresent(vmElement, \"ram\");\r\n\t\t\t\t\t\tisElementPresent(vmElement, \"storage\");\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t} catch (Exception e) {\r\n\t\t\tSimLogger.printLine(\"Edge Devices XML cannot be parsed! Terminating simulation...\");\r\n\t\t\te.printStackTrace();\r\n\t\t\tSystem.exit(1);\r\n\t\t}\r\n\t}\r\n}\r",
"public abstract class EdgeOrchestrator extends SimEntity{\r\n\tprotected String policy;\r\n\tprotected String simScenario;\r\n\t\r\n\tpublic EdgeOrchestrator(String _policy, String _simScenario){\r\n\t\tsuper(\"EdgeOrchestrator\");\r\n\t\tpolicy = _policy;\r\n\t\tsimScenario = _simScenario;\r\n\t}\r\n\r\n\t/*\r\n\t * Default Constructor: Creates an empty EdgeOrchestrator\r\n\t */\r\n\tpublic EdgeOrchestrator() {\r\n \tsuper(\"EdgeOrchestrator\");\r\n\t}\r\n\r\n\t/*\r\n\t * initialize edge orchestrator if needed\r\n\t */\r\n\tpublic abstract void initialize();\r\n\t\r\n\t/*\r\n\t * decides where to offload\r\n\t */\r\n\tpublic abstract int getDeviceToOffload(Task task);\r\n\t\r\n\t/*\r\n\t * returns proper VM from the edge orchestrator point of view\r\n\t */\r\n\tpublic abstract Vm getVmToOffload(Task task, int deviceId);\r\n}\r",
"public class EdgeHost extends Host {\r\n\tprivate Location location;\r\n\t\r\n\tpublic EdgeHost(int id, RamProvisioner ramProvisioner,\r\n\t\t\tBwProvisioner bwProvisioner, long storage,\r\n\t\t\tList<? extends Pe> peList, VmScheduler vmScheduler) {\r\n\t\tsuper(id, ramProvisioner, bwProvisioner, storage, peList, vmScheduler);\r\n\r\n\t}\r\n\t\r\n\tpublic void setPlace(Location _location){\r\n\t\tlocation=_location;\r\n\t}\r\n\t\r\n\tpublic Location getLocation(){\r\n\t\treturn location;\r\n\t}\r\n}\r",
"public class EdgeVM extends Vm {\r\n\tprivate SimSettings.VM_TYPES type;\r\n\t\r\n\tpublic EdgeVM(int id, int userId, double mips, int numberOfPes, int ram,\r\n\t\t\tlong bw, long size, String vmm, CloudletScheduler cloudletScheduler) {\r\n\t\tsuper(id, userId, mips, numberOfPes, ram, bw, size, vmm, cloudletScheduler);\r\n\r\n\t\ttype = SimSettings.VM_TYPES.EDGE_VM;\r\n\t}\r\n\r\n\tpublic SimSettings.VM_TYPES getVmType(){\r\n\t\treturn type;\r\n\t}\r\n\r\n\t/**\r\n\t * dynamically reconfigures the mips value of a VM in CloudSim\r\n\t * \r\n\t * @param mips new mips value for this VM.\r\n\t */\r\n\tpublic void reconfigureMips(double mips){\r\n\t\tsuper.setMips(mips);\r\n\t\tsuper.getHost().getVmScheduler().deallocatePesForVm(this);\r\n\t\t\r\n\t\tList<Double> mipsShareAllocated = new ArrayList<Double>();\r\n\t\tfor(int i= 0; i<getNumberOfPes(); i++)\r\n\t\t\tmipsShareAllocated.add(mips);\r\n\r\n\t\tsuper.getHost().getVmScheduler().allocatePesForVm(this, mipsShareAllocated);\r\n\t}\r\n}\r",
"public class CpuUtilizationModel_Custom implements UtilizationModel {\r\n\tprivate Task task;\r\n\t\r\n\tpublic CpuUtilizationModel_Custom(){\r\n\t}\r\n\t\r\n\t/*\r\n\t * (non-Javadoc)\r\n\t * @see cloudsim.power.UtilizationModel#getUtilization(double)\r\n\t */\r\n\t@Override\r\n\tpublic double getUtilization(double time) {\r\n\t\tint index = 9;\r\n\t\tif(task.getAssociatedDatacenterId() == SimSettings.CLOUD_DATACENTER_ID)\r\n\t\t\tindex = 10;\r\n\t\telse if(task.getAssociatedDatacenterId() == SimSettings.MOBILE_DATACENTER_ID)\r\n\t\t\tindex = 11;\r\n\r\n\t\treturn SimSettings.getInstance().getTaskLookUpTable()[task.getTaskType()][index];\r\n\t}\r\n\t\r\n\tpublic void setTask(Task _task){\r\n\t\ttask=_task;\r\n\t}\r\n\t\r\n\tpublic double predictUtilization(SimSettings.VM_TYPES _vmType){\r\n\t\tint index = 0;\r\n\t\tif(_vmType == SimSettings.VM_TYPES.EDGE_VM)\r\n\t\t\tindex = 9;\r\n\t\telse if(_vmType == SimSettings.VM_TYPES.CLOUD_VM)\r\n\t\t\tindex = 10;\r\n\t\telse if(_vmType == SimSettings.VM_TYPES.MOBILE_VM)\r\n\t\t\tindex = 11;\r\n\t\telse{\r\n\t\t\tSimLogger.printLine(\"Unknown VM Type! Terminating simulation...\");\r\n\t\t\tSystem.exit(1);\r\n\t\t}\r\n\t\treturn SimSettings.getInstance().getTaskLookUpTable()[task.getTaskType()][index];\r\n\t}\r\n}\r",
"public class Task extends Cloudlet {\r\n\tprivate Location submittedLocation;\r\n\tprivate double creationTime;\r\n\tprivate int type;\r\n\tprivate int mobileDeviceId;\r\n\tprivate int hostIndex;\r\n\tprivate int vmIndex;\r\n\tprivate int datacenterId;\r\n\r\n\tpublic Task(int _mobileDeviceId, int cloudletId, long cloudletLength, int pesNumber,\r\n\t\t\tlong cloudletFileSize, long cloudletOutputSize,\r\n\t\t\tUtilizationModel utilizationModelCpu,\r\n\t\t\tUtilizationModel utilizationModelRam,\r\n\t\t\tUtilizationModel utilizationModelBw) {\r\n\t\tsuper(cloudletId, cloudletLength, pesNumber, cloudletFileSize,\r\n\t\t\t\tcloudletOutputSize, utilizationModelCpu, utilizationModelRam,\r\n\t\t\t\tutilizationModelBw);\r\n\t\t\r\n\t\tmobileDeviceId = _mobileDeviceId;\r\n\t\tcreationTime = CloudSim.clock();\r\n\t}\r\n\r\n\t\r\n\tpublic void setSubmittedLocation(Location _submittedLocation){\r\n\t\tsubmittedLocation =_submittedLocation;\r\n\t}\r\n\r\n\tpublic void setAssociatedDatacenterId(int _datacenterId){\r\n\t\tdatacenterId=_datacenterId;\r\n\t}\r\n\t\r\n\tpublic void setAssociatedHostId(int _hostIndex){\r\n\t\thostIndex=_hostIndex;\r\n\t}\r\n\r\n\tpublic void setAssociatedVmId(int _vmIndex){\r\n\t\tvmIndex=_vmIndex;\r\n\t}\r\n\t\r\n\tpublic void setTaskType(int _type){\r\n\t\ttype=_type;\r\n\t}\r\n\r\n\tpublic int getMobileDeviceId(){\r\n\t\treturn mobileDeviceId;\r\n\t}\r\n\t\r\n\tpublic Location getSubmittedLocation(){\r\n\t\treturn submittedLocation;\r\n\t}\r\n\t\r\n\tpublic int getAssociatedDatacenterId(){\r\n\t\treturn datacenterId;\r\n\t}\r\n\t\r\n\tpublic int getAssociatedHostId(){\r\n\t\treturn hostIndex;\r\n\t}\r\n\r\n\tpublic int getAssociatedVmId(){\r\n\t\treturn vmIndex;\r\n\t}\r\n\t\r\n\tpublic int getTaskType(){\r\n\t\treturn type;\r\n\t}\r\n\t\r\n\tpublic double getCreationTime() {\r\n\t\treturn creationTime;\r\n\t}\r\n}\r",
"public class SimLogger {\r\n\tpublic static enum TASK_STATUS {\r\n\t\tCREATED, UPLOADING, PROCESSING, DOWNLOADING, COMLETED,\r\n\t\tREJECTED_DUE_TO_VM_CAPACITY, REJECTED_DUE_TO_BANDWIDTH,\r\n\t\tUNFINISHED_DUE_TO_BANDWIDTH, UNFINISHED_DUE_TO_MOBILITY,\r\n\t\tREJECTED_DUE_TO_WLAN_COVERAGE\r\n\t}\r\n\t\r\n\tpublic static enum NETWORK_ERRORS {\r\n\t\tLAN_ERROR, MAN_ERROR, WAN_ERROR, GSM_ERROR, NONE\r\n\t}\r\n\r\n\tprivate long startTime;\r\n\tprivate long endTime;\r\n\tprivate static boolean fileLogEnabled;\r\n\tprivate static boolean printLogEnabled;\r\n\tprivate String filePrefix;\r\n\tprivate String outputFolder;\r\n\tprivate Map<Integer, LogItem> taskMap;\r\n\tprivate LinkedList<VmLoadLogItem> vmLoadList;\r\n\tprivate LinkedList<ApDelayLogItem> apDelayList;\r\n\r\n\tprivate static SimLogger singleton = new SimLogger();\r\n\t\r\n\tprivate int numOfAppTypes;\r\n\t\r\n\tprivate File successFile = null, failFile = null;\r\n\tprivate FileWriter successFW = null, failFW = null;\r\n\tprivate BufferedWriter successBW = null, failBW = null;\r\n\r\n\t// extract following values for each app type.\r\n\t// last index is average of all app types\r\n\tprivate int[] uncompletedTask = null;\r\n\tprivate int[] uncompletedTaskOnCloud = null;\r\n\tprivate int[] uncompletedTaskOnEdge = null;\r\n\tprivate int[] uncompletedTaskOnMobile = null;\r\n\r\n\tprivate int[] completedTask = null;\r\n\tprivate int[] completedTaskOnCloud = null;\r\n\tprivate int[] completedTaskOnEdge = null;\r\n\tprivate int[] completedTaskOnMobile = null;\r\n\r\n\tprivate int[] failedTask = null;\r\n\tprivate int[] failedTaskOnCloud = null;\r\n\tprivate int[] failedTaskOnEdge = null;\r\n\tprivate int[] failedTaskOnMobile = null;\r\n\r\n\tprivate double[] networkDelay = null;\r\n\tprivate double[] gsmDelay = null;\r\n\tprivate double[] wanDelay = null;\r\n\tprivate double[] manDelay = null;\r\n\tprivate double[] lanDelay = null;\r\n\t\r\n\tprivate double[] gsmUsage = null;\r\n\tprivate double[] wanUsage = null;\r\n\tprivate double[] manUsage = null;\r\n\tprivate double[] lanUsage = null;\r\n\r\n\tprivate double[] serviceTime = null;\r\n\tprivate double[] serviceTimeOnCloud = null;\r\n\tprivate double[] serviceTimeOnEdge = null;\r\n\tprivate double[] serviceTimeOnMobile = null;\r\n\r\n\tprivate double[] processingTime = null;\r\n\tprivate double[] processingTimeOnCloud = null;\r\n\tprivate double[] processingTimeOnEdge = null;\r\n\tprivate double[] processingTimeOnMobile = null;\r\n\r\n\tprivate int[] failedTaskDueToVmCapacity = null;\r\n\tprivate int[] failedTaskDueToVmCapacityOnCloud = null;\r\n\tprivate int[] failedTaskDueToVmCapacityOnEdge = null;\r\n\tprivate int[] failedTaskDueToVmCapacityOnMobile = null;\r\n\t\r\n\tprivate double[] cost = null;\r\n\tprivate double[] QoE = null;\r\n\tprivate int[] failedTaskDuetoBw = null;\r\n\tprivate int[] failedTaskDuetoLanBw = null;\r\n\tprivate int[] failedTaskDuetoManBw = null;\r\n\tprivate int[] failedTaskDuetoWanBw = null;\r\n\tprivate int[] failedTaskDuetoGsmBw = null;\r\n\tprivate int[] failedTaskDuetoMobility = null;\r\n\tprivate int[] refectedTaskDuetoWlanRange = null;\r\n\t\r\n\tprivate double[] orchestratorOverhead = null;\r\n\r\n\t/*\r\n\t * A private Constructor prevents any other class from instantiating.\r\n\t */\r\n\tprivate SimLogger() {\r\n\t\tfileLogEnabled = false;\r\n\t\tprintLogEnabled = false;\r\n\t}\r\n\r\n\t/* Static 'instance' method */\r\n\tpublic static SimLogger getInstance() {\r\n\t\treturn singleton;\r\n\t}\r\n\r\n\tpublic static void enableFileLog() {\r\n\t\tfileLogEnabled = true;\r\n\t}\r\n\r\n\tpublic static void enablePrintLog() {\r\n\t\tprintLogEnabled = true;\r\n\t}\r\n\r\n\tpublic static boolean isFileLogEnabled() {\r\n\t\treturn fileLogEnabled;\r\n\t}\r\n\r\n\tpublic static void disableFileLog() {\r\n\t\tfileLogEnabled = false;\r\n\t}\r\n\t\r\n\tpublic static void disablePrintLog() {\r\n\t\tprintLogEnabled = false;\r\n\t}\r\n\t\r\n\tpublic String getOutputFolder() {\r\n\t\treturn outputFolder;\r\n\t}\r\n\r\n\tprivate void appendToFile(BufferedWriter bw, String line) throws IOException {\r\n\t\tbw.write(line);\r\n\t\tbw.newLine();\r\n\t}\r\n\r\n\tpublic static void printLine(String msg) {\r\n\t\tif (printLogEnabled)\r\n\t\t\tSystem.out.println(msg);\r\n\t}\r\n\r\n\tpublic static void print(String msg) {\r\n\t\tif (printLogEnabled)\r\n\t\t\tSystem.out.print(msg);\r\n\t}\r\n\r\n\tpublic void simStarted(String outFolder, String fileName) {\r\n\t\tstartTime = System.currentTimeMillis();\r\n\t\tfilePrefix = fileName;\r\n\t\toutputFolder = outFolder;\r\n\t\ttaskMap = new HashMap<Integer, LogItem>();\r\n\t\tvmLoadList = new LinkedList<VmLoadLogItem>();\r\n\t\tapDelayList = new LinkedList<ApDelayLogItem>();\r\n\t\t\r\n\t\tnumOfAppTypes = SimSettings.getInstance().getTaskLookUpTable().length;\r\n\t\t\r\n\t\tif (SimSettings.getInstance().getDeepFileLoggingEnabled()) {\r\n\t\t\ttry {\r\n\t\t\t\tsuccessFile = new File(outputFolder, filePrefix + \"_SUCCESS.log\");\r\n\t\t\t\tsuccessFW = new FileWriter(successFile, true);\r\n\t\t\t\tsuccessBW = new BufferedWriter(successFW);\r\n\r\n\t\t\t\tfailFile = new File(outputFolder, filePrefix + \"_FAIL.log\");\r\n\t\t\t\tfailFW = new FileWriter(failFile, true);\r\n\t\t\t\tfailBW = new BufferedWriter(failFW);\r\n\t\t\t\t\r\n\t\t\t\tappendToFile(successBW, \"#auto generated file!\");\r\n\t\t\t\tappendToFile(failBW, \"#auto generated file!\");\r\n\t\t\t} catch (IOException e) {\r\n\t\t\t\te.printStackTrace();\r\n\t\t\t\tSystem.exit(1);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t// extract following values for each app type.\r\n\t\t// last index is average of all app types\r\n\t\tuncompletedTask = new int[numOfAppTypes + 1];\r\n\t\tuncompletedTaskOnCloud = new int[numOfAppTypes + 1];\r\n\t\tuncompletedTaskOnEdge = new int[numOfAppTypes + 1];\r\n\t\tuncompletedTaskOnMobile = new int[numOfAppTypes + 1];\r\n\r\n\t\tcompletedTask = new int[numOfAppTypes + 1];\r\n\t\tcompletedTaskOnCloud = new int[numOfAppTypes + 1];\r\n\t\tcompletedTaskOnEdge = new int[numOfAppTypes + 1];\r\n\t\tcompletedTaskOnMobile = new int[numOfAppTypes + 1];\r\n\r\n\t\tfailedTask = new int[numOfAppTypes + 1];\r\n\t\tfailedTaskOnCloud = new int[numOfAppTypes + 1];\r\n\t\tfailedTaskOnEdge = new int[numOfAppTypes + 1];\r\n\t\tfailedTaskOnMobile = new int[numOfAppTypes + 1];\r\n\r\n\t\tnetworkDelay = new double[numOfAppTypes + 1];\r\n\t\tgsmDelay = new double[numOfAppTypes + 1];\r\n\t\twanDelay = new double[numOfAppTypes + 1];\r\n\t\tmanDelay = new double[numOfAppTypes + 1];\r\n\t\tlanDelay = new double[numOfAppTypes + 1];\r\n\t\t\r\n\t\tgsmUsage = new double[numOfAppTypes + 1];\r\n\t\twanUsage = new double[numOfAppTypes + 1];\r\n\t\tmanUsage = new double[numOfAppTypes + 1];\r\n\t\tlanUsage = new double[numOfAppTypes + 1];\r\n\r\n\t\tserviceTime = new double[numOfAppTypes + 1];\r\n\t\tserviceTimeOnCloud = new double[numOfAppTypes + 1];\r\n\t\tserviceTimeOnEdge = new double[numOfAppTypes + 1];\r\n\t\tserviceTimeOnMobile = new double[numOfAppTypes + 1];\r\n\r\n\t\tprocessingTime = new double[numOfAppTypes + 1];\r\n\t\tprocessingTimeOnCloud = new double[numOfAppTypes + 1];\r\n\t\tprocessingTimeOnEdge = new double[numOfAppTypes + 1];\r\n\t\tprocessingTimeOnMobile = new double[numOfAppTypes + 1];\r\n\r\n\t\tfailedTaskDueToVmCapacity = new int[numOfAppTypes + 1];\r\n\t\tfailedTaskDueToVmCapacityOnCloud = new int[numOfAppTypes + 1];\r\n\t\tfailedTaskDueToVmCapacityOnEdge = new int[numOfAppTypes + 1];\r\n\t\tfailedTaskDueToVmCapacityOnMobile = new int[numOfAppTypes + 1];\r\n\t\t\r\n\t\tcost = new double[numOfAppTypes + 1];\r\n\t\tQoE = new double[numOfAppTypes + 1];\r\n\t\tfailedTaskDuetoBw = new int[numOfAppTypes + 1];\r\n\t\tfailedTaskDuetoLanBw = new int[numOfAppTypes + 1];\r\n\t\tfailedTaskDuetoManBw = new int[numOfAppTypes + 1];\r\n\t\tfailedTaskDuetoWanBw = new int[numOfAppTypes + 1];\r\n\t\tfailedTaskDuetoGsmBw = new int[numOfAppTypes + 1];\r\n\t\tfailedTaskDuetoMobility = new int[numOfAppTypes + 1];\r\n\t\trefectedTaskDuetoWlanRange = new int[numOfAppTypes + 1];\r\n\r\n\t\torchestratorOverhead = new double[numOfAppTypes + 1];\r\n\t}\r\n\r\n\tpublic void addLog(int deviceId, int taskId, int taskType,\r\n\t\t\tint taskLenght, int taskInputType, int taskOutputSize) {\r\n\t\t// printLine(taskId+\"->\"+taskStartTime);\r\n\t\ttaskMap.put(taskId, new LogItem(deviceId, taskType, taskLenght, taskInputType, taskOutputSize));\r\n\t}\r\n\r\n\tpublic void taskStarted(int taskId, double time) {\r\n\t\ttaskMap.get(taskId).taskStarted(time);\r\n\t}\r\n\r\n\tpublic void setUploadDelay(int taskId, double delay, NETWORK_DELAY_TYPES delayType) {\r\n\t\ttaskMap.get(taskId).setUploadDelay(delay, delayType);\r\n\t}\r\n\r\n\tpublic void setDownloadDelay(int taskId, double delay, NETWORK_DELAY_TYPES delayType) {\r\n\t\ttaskMap.get(taskId).setDownloadDelay(delay, delayType);\r\n\t}\r\n\t\r\n\tpublic void taskAssigned(int taskId, int datacenterId, int hostId, int vmId, int vmType) {\r\n\t\ttaskMap.get(taskId).taskAssigned(datacenterId, hostId, vmId, vmType);\r\n\t}\r\n\r\n\tpublic void taskExecuted(int taskId) {\r\n\t\ttaskMap.get(taskId).taskExecuted();\r\n\t}\r\n\r\n\tpublic void taskEnded(int taskId, double time) {\r\n\t\ttaskMap.get(taskId).taskEnded(time);\r\n\t\trecordLog(taskId);\r\n\t}\r\n\r\n\tpublic void rejectedDueToVMCapacity(int taskId, double time, int vmType) {\r\n\t\ttaskMap.get(taskId).taskRejectedDueToVMCapacity(time, vmType);\r\n\t\trecordLog(taskId);\r\n\t}\r\n\r\n public void rejectedDueToWlanCoverage(int taskId, double time, int vmType) {\r\n \ttaskMap.get(taskId).taskRejectedDueToWlanCoverage(time, vmType);\r\n\t\trecordLog(taskId);\r\n }\r\n \r\n\tpublic void rejectedDueToBandwidth(int taskId, double time, int vmType, NETWORK_DELAY_TYPES delayType) {\r\n\t\ttaskMap.get(taskId).taskRejectedDueToBandwidth(time, vmType, delayType);\r\n\t\trecordLog(taskId);\r\n\t}\r\n\r\n\tpublic void failedDueToBandwidth(int taskId, double time, NETWORK_DELAY_TYPES delayType) {\r\n\t\ttaskMap.get(taskId).taskFailedDueToBandwidth(time, delayType);\r\n\t\trecordLog(taskId);\r\n\t}\r\n\r\n\tpublic void failedDueToMobility(int taskId, double time) {\r\n\t\ttaskMap.get(taskId).taskFailedDueToMobility(time);\r\n\t\trecordLog(taskId);\r\n\t}\r\n\r\n\tpublic void setQoE(int taskId, double QoE){\r\n\t\ttaskMap.get(taskId).setQoE(QoE);\r\n\t}\r\n\t\r\n\tpublic void setOrchestratorOverhead(int taskId, double overhead){\r\n\t\ttaskMap.get(taskId).setOrchestratorOverhead(overhead);\r\n\t}\r\n\r\n\tpublic void addVmUtilizationLog(double time, double loadOnEdge, double loadOnCloud, double loadOnMobile) {\r\n\t\tif(SimSettings.getInstance().getLocationLogInterval() != 0)\r\n\t\t\tvmLoadList.add(new VmLoadLogItem(time, loadOnEdge, loadOnCloud, loadOnMobile));\r\n\t}\r\n\r\n\tpublic void addApDelayLog(double time, double[] apUploadDelays, double[] apDownloadDelays) {\r\n\t\tif(SimSettings.getInstance().getApDelayLogInterval() != 0)\r\n\t\t\tapDelayList.add(new ApDelayLogItem(time, apUploadDelays, apDownloadDelays));\r\n\t}\r\n\t\r\n\tpublic void simStopped() throws IOException {\r\n\t\tendTime = System.currentTimeMillis();\r\n\t\tFile vmLoadFile = null, locationFile = null, apUploadDelayFile = null, apDownloadDelayFile = null;\r\n\t\tFileWriter vmLoadFW = null, locationFW = null, apUploadDelayFW = null, apDownloadDelayFW = null;\r\n\t\tBufferedWriter vmLoadBW = null, locationBW = null, apUploadDelayBW = null, apDownloadDelayBW = null;\r\n\r\n\t\t// Save generic results to file for each app type. last index is average\r\n\t\t// of all app types\r\n\t\tFile[] genericFiles = new File[numOfAppTypes + 1];\r\n\t\tFileWriter[] genericFWs = new FileWriter[numOfAppTypes + 1];\r\n\t\tBufferedWriter[] genericBWs = new BufferedWriter[numOfAppTypes + 1];\r\n\r\n\t\t// open all files and prepare them for write\r\n\t\tif (fileLogEnabled) {\r\n\t\t\tvmLoadFile = new File(outputFolder, filePrefix + \"_VM_LOAD.log\");\r\n\t\t\tvmLoadFW = new FileWriter(vmLoadFile, true);\r\n\t\t\tvmLoadBW = new BufferedWriter(vmLoadFW);\r\n\r\n\t\t\tlocationFile = new File(outputFolder, filePrefix + \"_LOCATION.log\");\r\n\t\t\tlocationFW = new FileWriter(locationFile, true);\r\n\t\t\tlocationBW = new BufferedWriter(locationFW);\r\n\r\n\t\t\tapUploadDelayFile = new File(outputFolder, filePrefix + \"_AP_UPLOAD_DELAY.log\");\r\n\t\t\tapUploadDelayFW = new FileWriter(apUploadDelayFile, true);\r\n\t\t\tapUploadDelayBW = new BufferedWriter(apUploadDelayFW);\r\n\r\n\t\t\tapDownloadDelayFile = new File(outputFolder, filePrefix + \"_AP_DOWNLOAD_DELAY.log\");\r\n\t\t\tapDownloadDelayFW = new FileWriter(apDownloadDelayFile, true);\r\n\t\t\tapDownloadDelayBW = new BufferedWriter(apDownloadDelayFW);\r\n\r\n\t\t\tfor (int i = 0; i < numOfAppTypes + 1; i++) {\r\n\t\t\t\tString fileName = \"ALL_APPS_GENERIC.log\";\r\n\r\n\t\t\t\tif (i < numOfAppTypes) {\r\n\t\t\t\t\t// if related app is not used in this simulation, just discard it\r\n\t\t\t\t\tif (SimSettings.getInstance().getTaskLookUpTable()[i][0] == 0)\r\n\t\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\t\tfileName = SimSettings.getInstance().getTaskName(i) + \"_GENERIC.log\";\r\n\t\t\t\t}\r\n\r\n\t\t\t\tgenericFiles[i] = new File(outputFolder, filePrefix + \"_\" + fileName);\r\n\t\t\t\tgenericFWs[i] = new FileWriter(genericFiles[i], true);\r\n\t\t\t\tgenericBWs[i] = new BufferedWriter(genericFWs[i]);\r\n\t\t\t\tappendToFile(genericBWs[i], \"#auto generated file!\");\r\n\t\t\t}\r\n\r\n\t\t\tappendToFile(vmLoadBW, \"#auto generated file!\");\r\n\t\t\tappendToFile(locationBW, \"#auto generated file!\");\r\n\t\t\tappendToFile(apUploadDelayBW, \"#auto generated file!\");\r\n\t\t\tappendToFile(apDownloadDelayBW, \"#auto generated file!\");\r\n\t\t}\r\n\r\n\t\t//the tasks in the map is not completed yet!\r\n\t\tfor (Map.Entry<Integer, LogItem> entry : taskMap.entrySet()) {\r\n\t\t\tLogItem value = entry.getValue();\r\n\r\n\t\t\tuncompletedTask[value.getTaskType()]++;\r\n\t\t\tif (value.getVmType() == SimSettings.VM_TYPES.CLOUD_VM.ordinal())\r\n\t\t\t\tuncompletedTaskOnCloud[value.getTaskType()]++;\r\n\t\t\telse if (value.getVmType() == SimSettings.VM_TYPES.MOBILE_VM.ordinal())\r\n\t\t\t\tuncompletedTaskOnMobile[value.getTaskType()]++;\r\n\t\t\telse\r\n\t\t\t\tuncompletedTaskOnEdge[value.getTaskType()]++;\r\n\t\t}\r\n\r\n\t\t// calculate total values\r\n\t\tuncompletedTask[numOfAppTypes] = IntStream.of(uncompletedTask).sum();\r\n\t\tuncompletedTaskOnCloud[numOfAppTypes] = IntStream.of(uncompletedTaskOnCloud).sum();\r\n\t\tuncompletedTaskOnEdge[numOfAppTypes] = IntStream.of(uncompletedTaskOnEdge).sum();\r\n\t\tuncompletedTaskOnMobile[numOfAppTypes] = IntStream.of(uncompletedTaskOnMobile).sum();\r\n\r\n\t\tcompletedTask[numOfAppTypes] = IntStream.of(completedTask).sum();\r\n\t\tcompletedTaskOnCloud[numOfAppTypes] = IntStream.of(completedTaskOnCloud).sum();\r\n\t\tcompletedTaskOnEdge[numOfAppTypes] = IntStream.of(completedTaskOnEdge).sum();\r\n\t\tcompletedTaskOnMobile[numOfAppTypes] = IntStream.of(completedTaskOnMobile).sum();\r\n\r\n\t\tfailedTask[numOfAppTypes] = IntStream.of(failedTask).sum();\r\n\t\tfailedTaskOnCloud[numOfAppTypes] = IntStream.of(failedTaskOnCloud).sum();\r\n\t\tfailedTaskOnEdge[numOfAppTypes] = IntStream.of(failedTaskOnEdge).sum();\r\n\t\tfailedTaskOnMobile[numOfAppTypes] = IntStream.of(failedTaskOnMobile).sum();\r\n\r\n\t\tnetworkDelay[numOfAppTypes] = DoubleStream.of(networkDelay).sum();\r\n\t\tlanDelay[numOfAppTypes] = DoubleStream.of(lanDelay).sum();\r\n\t\tmanDelay[numOfAppTypes] = DoubleStream.of(manDelay).sum();\r\n\t\twanDelay[numOfAppTypes] = DoubleStream.of(wanDelay).sum();\r\n\t\tgsmDelay[numOfAppTypes] = DoubleStream.of(gsmDelay).sum();\r\n\t\t\r\n\t\tlanUsage[numOfAppTypes] = DoubleStream.of(lanUsage).sum();\r\n\t\tmanUsage[numOfAppTypes] = DoubleStream.of(manUsage).sum();\r\n\t\twanUsage[numOfAppTypes] = DoubleStream.of(wanUsage).sum();\r\n\t\tgsmUsage[numOfAppTypes] = DoubleStream.of(gsmUsage).sum();\r\n\r\n\t\tserviceTime[numOfAppTypes] = DoubleStream.of(serviceTime).sum();\r\n\t\tserviceTimeOnCloud[numOfAppTypes] = DoubleStream.of(serviceTimeOnCloud).sum();\r\n\t\tserviceTimeOnEdge[numOfAppTypes] = DoubleStream.of(serviceTimeOnEdge).sum();\r\n\t\tserviceTimeOnMobile[numOfAppTypes] = DoubleStream.of(serviceTimeOnMobile).sum();\r\n\r\n\t\tprocessingTime[numOfAppTypes] = DoubleStream.of(processingTime).sum();\r\n\t\tprocessingTimeOnCloud[numOfAppTypes] = DoubleStream.of(processingTimeOnCloud).sum();\r\n\t\tprocessingTimeOnEdge[numOfAppTypes] = DoubleStream.of(processingTimeOnEdge).sum();\r\n\t\tprocessingTimeOnMobile[numOfAppTypes] = DoubleStream.of(processingTimeOnMobile).sum();\r\n\r\n\t\tfailedTaskDueToVmCapacity[numOfAppTypes] = IntStream.of(failedTaskDueToVmCapacity).sum();\r\n\t\tfailedTaskDueToVmCapacityOnCloud[numOfAppTypes] = IntStream.of(failedTaskDueToVmCapacityOnCloud).sum();\r\n\t\tfailedTaskDueToVmCapacityOnEdge[numOfAppTypes] = IntStream.of(failedTaskDueToVmCapacityOnEdge).sum();\r\n\t\tfailedTaskDueToVmCapacityOnMobile[numOfAppTypes] = IntStream.of(failedTaskDueToVmCapacityOnMobile).sum();\r\n\t\t\r\n\t\tcost[numOfAppTypes] = DoubleStream.of(cost).sum();\r\n\t\tQoE[numOfAppTypes] = DoubleStream.of(QoE).sum();\r\n\t\tfailedTaskDuetoBw[numOfAppTypes] = IntStream.of(failedTaskDuetoBw).sum();\r\n\t\tfailedTaskDuetoGsmBw[numOfAppTypes] = IntStream.of(failedTaskDuetoGsmBw).sum();\r\n\t\tfailedTaskDuetoWanBw[numOfAppTypes] = IntStream.of(failedTaskDuetoWanBw).sum();\r\n\t\tfailedTaskDuetoManBw[numOfAppTypes] = IntStream.of(failedTaskDuetoManBw).sum();\r\n\t\tfailedTaskDuetoLanBw[numOfAppTypes] = IntStream.of(failedTaskDuetoLanBw).sum();\r\n\t\tfailedTaskDuetoMobility[numOfAppTypes] = IntStream.of(failedTaskDuetoMobility).sum();\r\n\t\trefectedTaskDuetoWlanRange[numOfAppTypes] = IntStream.of(refectedTaskDuetoWlanRange).sum();\r\n\r\n\t\torchestratorOverhead[numOfAppTypes] = DoubleStream.of(orchestratorOverhead).sum();\r\n\t\t\r\n\t\t// calculate server load\r\n\t\tdouble totalVmLoadOnEdge = 0;\r\n\t\tdouble totalVmLoadOnCloud = 0;\r\n\t\tdouble totalVmLoadOnMobile = 0;\r\n\t\tfor (VmLoadLogItem entry : vmLoadList) {\r\n\t\t\ttotalVmLoadOnEdge += entry.getEdgeLoad();\r\n\t\t\ttotalVmLoadOnCloud += entry.getCloudLoad();\r\n\t\t\ttotalVmLoadOnMobile += entry.getMobileLoad();\r\n\t\t\tif (fileLogEnabled && SimSettings.getInstance().getVmLoadLogInterval() != 0)\r\n\t\t\t\tappendToFile(vmLoadBW, entry.toString());\r\n\t\t}\r\n\r\n\t\tif (fileLogEnabled) {\r\n\t\t\t// write location info to file for each location\r\n\t\t\t// assuming each location has only one access point\r\n\t\t\tdouble locationLogInterval = SimSettings.getInstance().getLocationLogInterval();\r\n\t\t\tif(locationLogInterval != 0) {\r\n\t\t\t\tfor (int t = 1; t < (SimSettings.getInstance().getSimulationTime() / locationLogInterval); t++) {\r\n\t\t\t\t\tint[] locationInfo = new int[SimSettings.getInstance().getNumOfEdgeDatacenters()];\r\n\t\t\t\t\tDouble time = t * SimSettings.getInstance().getLocationLogInterval();\r\n\t\t\t\t\t\r\n\t\t\t\t\tif (time < SimSettings.CLIENT_ACTIVITY_START_TIME)\r\n\t\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\t\tfor (int i = 0; i < SimManager.getInstance().getNumOfMobileDevice(); i++) {\r\n\t\t\t\t\t\tLocation loc = SimManager.getInstance().getMobilityModel().getLocation(i, time);\r\n\t\t\t\t\t\tlocationInfo[loc.getServingWlanId()]++;\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tlocationBW.write(time.toString());\r\n\t\t\t\t\tfor (int i = 0; i < locationInfo.length; i++)\r\n\t\t\t\t\t\tlocationBW.write(SimSettings.DELIMITER + locationInfo[i]);\r\n\r\n\t\t\t\t\tlocationBW.newLine();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t// write delay info to file for each access point\r\n\t\t\tif(SimSettings.getInstance().getApDelayLogInterval() != 0) {\r\n\t\t\t\tfor (ApDelayLogItem entry : apDelayList) {\r\n\t\t\t\t\tappendToFile(apUploadDelayBW, entry.getUploadStat());\r\n\t\t\t\t\tappendToFile(apDownloadDelayBW, entry.getDownloadStat());\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tfor (int i = 0; i < numOfAppTypes + 1; i++) {\r\n\r\n\t\t\t\tif (i < numOfAppTypes) {\r\n\t\t\t\t\t// if related app is not used in this simulation, just discard it\r\n\t\t\t\t\tif (SimSettings.getInstance().getTaskLookUpTable()[i][0] == 0)\r\n\t\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\r\n\t\t\t\t// check if the divisor is zero in order to avoid division by\r\n\t\t\t\t// zero problem\r\n\t\t\t\tdouble _serviceTime = (completedTask[i] == 0) ? 0.0 : (serviceTime[i] / (double) completedTask[i]);\r\n\t\t\t\tdouble _networkDelay = (completedTask[i] == 0) ? 0.0 : (networkDelay[i] / ((double) completedTask[i] - (double)completedTaskOnMobile[i]));\r\n\t\t\t\tdouble _processingTime = (completedTask[i] == 0) ? 0.0 : (processingTime[i] / (double) completedTask[i]);\r\n\t\t\t\tdouble _vmLoadOnEdge = (vmLoadList.size() == 0) ? 0.0 : (totalVmLoadOnEdge / (double) vmLoadList.size());\r\n\t\t\t\tdouble _vmLoadOnClould = (vmLoadList.size() == 0) ? 0.0 : (totalVmLoadOnCloud / (double) vmLoadList.size());\r\n\t\t\t\tdouble _vmLoadOnMobile = (vmLoadList.size() == 0) ? 0.0 : (totalVmLoadOnMobile / (double) vmLoadList.size());\r\n\t\t\t\tdouble _cost = (completedTask[i] == 0) ? 0.0 : (cost[i] / (double) completedTask[i]);\r\n\t\t\t\tdouble _QoE1 = (completedTask[i] == 0) ? 0.0 : (QoE[i] / (double) completedTask[i]);\r\n\t\t\t\tdouble _QoE2 = (completedTask[i] == 0) ? 0.0 : (QoE[i] / (double) (failedTask[i] + completedTask[i]));\r\n\r\n\t\t\t\tdouble _lanDelay = (lanUsage[i] == 0) ? 0.0\r\n\t\t\t\t\t\t: (lanDelay[i] / (double) lanUsage[i]);\r\n\t\t\t\tdouble _manDelay = (manUsage[i] == 0) ? 0.0\r\n\t\t\t\t\t\t: (manDelay[i] / (double) manUsage[i]);\r\n\t\t\t\tdouble _wanDelay = (wanUsage[i] == 0) ? 0.0\r\n\t\t\t\t\t\t: (wanDelay[i] / (double) wanUsage[i]);\r\n\t\t\t\tdouble _gsmDelay = (gsmUsage[i] == 0) ? 0.0\r\n\t\t\t\t\t\t: (gsmDelay[i] / (double) gsmUsage[i]);\r\n\t\t\t\t\r\n\t\t\t\t// write generic results\r\n\t\t\t\tString genericResult1 = Integer.toString(completedTask[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(failedTask[i]) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Integer.toString(uncompletedTask[i]) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Integer.toString(failedTaskDuetoBw[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_serviceTime) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Double.toString(_processingTime) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Double.toString(_networkDelay) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(0) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Double.toString(_cost) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Integer.toString(failedTaskDueToVmCapacity[i]) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Integer.toString(failedTaskDuetoMobility[i]) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Double.toString(_QoE1) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Double.toString(_QoE2) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(refectedTaskDuetoWlanRange[i]);\r\n\r\n\t\t\t\t// check if the divisor is zero in order to avoid division by zero problem\r\n\t\t\t\tdouble _serviceTimeOnEdge = (completedTaskOnEdge[i] == 0) ? 0.0\r\n\t\t\t\t\t\t: (serviceTimeOnEdge[i] / (double) completedTaskOnEdge[i]);\r\n\t\t\t\tdouble _processingTimeOnEdge = (completedTaskOnEdge[i] == 0) ? 0.0\r\n\t\t\t\t\t\t: (processingTimeOnEdge[i] / (double) completedTaskOnEdge[i]);\r\n\t\t\t\tString genericResult2 = Integer.toString(completedTaskOnEdge[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(failedTaskOnEdge[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(uncompletedTaskOnEdge[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(0) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_serviceTimeOnEdge) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_processingTimeOnEdge) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(0.0) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Double.toString(_vmLoadOnEdge) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Integer.toString(failedTaskDueToVmCapacityOnEdge[i]);\r\n\r\n\t\t\t\t// check if the divisor is zero in order to avoid division by zero problem\r\n\t\t\t\tdouble _serviceTimeOnCloud = (completedTaskOnCloud[i] == 0) ? 0.0\r\n\t\t\t\t\t\t: (serviceTimeOnCloud[i] / (double) completedTaskOnCloud[i]);\r\n\t\t\t\tdouble _processingTimeOnCloud = (completedTaskOnCloud[i] == 0) ? 0.0\r\n\t\t\t\t\t\t: (processingTimeOnCloud[i] / (double) completedTaskOnCloud[i]);\r\n\t\t\t\tString genericResult3 = Integer.toString(completedTaskOnCloud[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(failedTaskOnCloud[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(uncompletedTaskOnCloud[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(0) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_serviceTimeOnCloud) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_processingTimeOnCloud) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Double.toString(0.0) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_vmLoadOnClould) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Integer.toString(failedTaskDueToVmCapacityOnCloud[i]);\r\n\t\t\t\t\r\n\t\t\t\t// check if the divisor is zero in order to avoid division by zero problem\r\n\t\t\t\tdouble _serviceTimeOnMobile = (completedTaskOnMobile[i] == 0) ? 0.0\r\n\t\t\t\t\t\t: (serviceTimeOnMobile[i] / (double) completedTaskOnMobile[i]);\r\n\t\t\t\tdouble _processingTimeOnMobile = (completedTaskOnMobile[i] == 0) ? 0.0\r\n\t\t\t\t\t\t: (processingTimeOnMobile[i] / (double) completedTaskOnMobile[i]);\r\n\t\t\t\tString genericResult4 = Integer.toString(completedTaskOnMobile[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(failedTaskOnMobile[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(uncompletedTaskOnMobile[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(0) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_serviceTimeOnMobile) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_processingTimeOnMobile) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Double.toString(0.0) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_vmLoadOnMobile) + SimSettings.DELIMITER \r\n\t\t\t\t\t\t+ Integer.toString(failedTaskDueToVmCapacityOnMobile[i]);\r\n\t\t\t\t\r\n\t\t\t\tString genericResult5 = Double.toString(_lanDelay) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_manDelay) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_wanDelay) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_gsmDelay) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(failedTaskDuetoLanBw[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(failedTaskDuetoManBw[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(failedTaskDuetoWanBw[i]) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Integer.toString(failedTaskDuetoGsmBw[i]);\r\n\t\t\t\t\r\n\t\t\t\t//performance related values\r\n\t\t\t\tdouble _orchestratorOverhead = orchestratorOverhead[i] / (double) (failedTask[i] + completedTask[i]);\r\n\t\t\t\t\r\n\t\t\t\tString genericResult6 = Long.toString((endTime-startTime)/60) + SimSettings.DELIMITER\r\n\t\t\t\t\t\t+ Double.toString(_orchestratorOverhead);\r\n\t\t\t\t\t\t\r\n\r\n\t\t\t\tappendToFile(genericBWs[i], genericResult1);\r\n\t\t\t\tappendToFile(genericBWs[i], genericResult2);\r\n\t\t\t\tappendToFile(genericBWs[i], genericResult3);\r\n\t\t\t\tappendToFile(genericBWs[i], genericResult4);\r\n\t\t\t\tappendToFile(genericBWs[i], genericResult5);\r\n\t\t\t\t\r\n\t\t\t\t//append performance related values only to ALL_ALLPS file\r\n\t\t\t\tif(i == numOfAppTypes) {\r\n\t\t\t\t\tappendToFile(genericBWs[i], genericResult6);\r\n\t\t\t\t}\r\n\t\t\t\telse {\r\n\t\t\t\t\tprintLine(SimSettings.getInstance().getTaskName(i));\r\n\t\t\t\t\tprintLine(\"# of tasks (Edge/Cloud): \"\r\n\t\t\t\t\t\t\t+ (failedTask[i] + completedTask[i]) + \"(\"\r\n\t\t\t\t\t\t\t+ (failedTaskOnEdge[i] + completedTaskOnEdge[i]) + \"/\" \r\n\t\t\t\t\t\t\t+ (failedTaskOnCloud[i]+ completedTaskOnCloud[i]) + \")\" );\r\n\t\t\t\t\t\r\n\t\t\t\t\tprintLine(\"# of failed tasks (Edge/Cloud): \"\r\n\t\t\t\t\t\t\t+ failedTask[i] + \"(\"\r\n\t\t\t\t\t\t\t+ failedTaskOnEdge[i] + \"/\"\r\n\t\t\t\t\t\t\t+ failedTaskOnCloud[i] + \")\");\r\n\t\t\t\t\t\r\n\t\t\t\t\tprintLine(\"# of completed tasks (Edge/Cloud): \"\r\n\t\t\t\t\t\t\t+ completedTask[i] + \"(\"\r\n\t\t\t\t\t\t\t+ completedTaskOnEdge[i] + \"/\"\r\n\t\t\t\t\t\t\t+ completedTaskOnCloud[i] + \")\");\r\n\t\t\t\t\t\r\n\t\t\t\t\tprintLine(\"---------------------------------------\");\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\t// close open files\r\n\t\t\tif (SimSettings.getInstance().getDeepFileLoggingEnabled()) {\r\n\t\t\t\tsuccessBW.close();\r\n\t\t\t\tfailBW.close();\r\n\t\t\t}\r\n\t\t\tvmLoadBW.close();\r\n\t\t\tlocationBW.close();\r\n\t\t\tapUploadDelayBW.close();\r\n\t\t\tapDownloadDelayBW.close();\r\n\t\t\tfor (int i = 0; i < numOfAppTypes + 1; i++) {\r\n\t\t\t\tif (i < numOfAppTypes) {\r\n\t\t\t\t\t// if related app is not used in this simulation, just\r\n\t\t\t\t\t// discard it\r\n\t\t\t\t\tif (SimSettings.getInstance().getTaskLookUpTable()[i][0] == 0)\r\n\t\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\t\t\t\tgenericBWs[i].close();\r\n\t\t\t}\r\n\t\t\t\r\n\t\t}\r\n\r\n\t\t// printout important results\r\n\t\tprintLine(\"# of tasks (Edge/Cloud/Mobile): \"\r\n\t\t\t\t+ (failedTask[numOfAppTypes] + completedTask[numOfAppTypes]) + \"(\"\r\n\t\t\t\t+ (failedTaskOnEdge[numOfAppTypes] + completedTaskOnEdge[numOfAppTypes]) + \"/\" \r\n\t\t\t\t+ (failedTaskOnCloud[numOfAppTypes]+ completedTaskOnCloud[numOfAppTypes]) + \"/\" \r\n\t\t\t\t+ (failedTaskOnMobile[numOfAppTypes]+ completedTaskOnMobile[numOfAppTypes]) + \")\");\r\n\t\t\r\n\t\tprintLine(\"# of failed tasks (Edge/Cloud/Mobile): \"\r\n\t\t\t\t+ failedTask[numOfAppTypes] + \"(\"\r\n\t\t\t\t+ failedTaskOnEdge[numOfAppTypes] + \"/\"\r\n\t\t\t\t+ failedTaskOnCloud[numOfAppTypes] + \"/\"\r\n\t\t\t\t+ failedTaskOnMobile[numOfAppTypes] + \")\");\r\n\t\t\r\n\t\tprintLine(\"# of completed tasks (Edge/Cloud/Mobile): \"\r\n\t\t\t\t+ completedTask[numOfAppTypes] + \"(\"\r\n\t\t\t\t+ completedTaskOnEdge[numOfAppTypes] + \"/\"\r\n\t\t\t\t+ completedTaskOnCloud[numOfAppTypes] + \"/\"\r\n\t\t\t\t+ completedTaskOnMobile[numOfAppTypes] + \")\");\r\n\t\t\r\n\t\tprintLine(\"# of uncompleted tasks (Edge/Cloud/Mobile): \"\r\n\t\t\t\t+ uncompletedTask[numOfAppTypes] + \"(\"\r\n\t\t\t\t+ uncompletedTaskOnEdge[numOfAppTypes] + \"/\"\r\n\t\t\t\t+ uncompletedTaskOnCloud[numOfAppTypes] + \"/\"\r\n\t\t\t\t+ uncompletedTaskOnMobile[numOfAppTypes] + \")\");\r\n\r\n\t\tprintLine(\"# of failed tasks due to vm capacity (Edge/Cloud/Mobile): \"\r\n\t\t\t\t+ failedTaskDueToVmCapacity[numOfAppTypes] + \"(\"\r\n\t\t\t\t+ failedTaskDueToVmCapacityOnEdge[numOfAppTypes] + \"/\"\r\n\t\t\t\t+ failedTaskDueToVmCapacityOnCloud[numOfAppTypes] + \"/\"\r\n\t\t\t\t+ failedTaskDueToVmCapacityOnMobile[numOfAppTypes] + \")\");\r\n\t\t\r\n\t\tprintLine(\"# of failed tasks due to Mobility/WLAN Range/Network(WLAN/MAN/WAN/GSM): \"\r\n\t\t\t\t+ failedTaskDuetoMobility[numOfAppTypes]\r\n\t\t\t\t+ \"/\" + refectedTaskDuetoWlanRange[numOfAppTypes]\r\n\t\t\t\t+ \"/\" + failedTaskDuetoBw[numOfAppTypes] \r\n\t\t\t\t+ \"(\" + failedTaskDuetoLanBw[numOfAppTypes] \r\n\t\t\t\t+ \"/\" + failedTaskDuetoManBw[numOfAppTypes] \r\n\t\t\t\t+ \"/\" + failedTaskDuetoWanBw[numOfAppTypes] \r\n\t\t\t\t+ \"/\" + failedTaskDuetoGsmBw[numOfAppTypes] + \")\");\r\n\t\t\r\n\t\tprintLine(\"percentage of failed tasks: \"\r\n\t\t\t\t+ String.format(\"%.6f\", ((double) failedTask[numOfAppTypes] * (double) 100)\r\n\t\t\t\t\t\t/ (double) (completedTask[numOfAppTypes] + failedTask[numOfAppTypes]))\r\n\t\t\t\t+ \"%\");\r\n\r\n\t\tprintLine(\"average service time: \"\r\n\t\t\t\t+ String.format(\"%.6f\", serviceTime[numOfAppTypes] / (double) completedTask[numOfAppTypes])\r\n\t\t\t\t+ \" seconds. (\" + \"on Edge: \"\r\n\t\t\t\t+ String.format(\"%.6f\", serviceTimeOnEdge[numOfAppTypes] / (double) completedTaskOnEdge[numOfAppTypes])\r\n\t\t\t\t+ \", \" + \"on Cloud: \"\r\n\t\t\t\t+ String.format(\"%.6f\", serviceTimeOnCloud[numOfAppTypes] / (double) completedTaskOnCloud[numOfAppTypes])\r\n\t\t\t\t+ \", \" + \"on Mobile: \"\r\n\t\t\t\t+ String.format(\"%.6f\", serviceTimeOnMobile[numOfAppTypes] / (double) completedTaskOnMobile[numOfAppTypes])\r\n\t\t\t\t+ \")\");\r\n\r\n\t\tprintLine(\"average processing time: \"\r\n\t\t\t\t+ String.format(\"%.6f\", processingTime[numOfAppTypes] / (double) completedTask[numOfAppTypes])\r\n\t\t\t\t+ \" seconds. (\" + \"on Edge: \"\r\n\t\t\t\t+ String.format(\"%.6f\", processingTimeOnEdge[numOfAppTypes] / (double) completedTaskOnEdge[numOfAppTypes])\r\n\t\t\t\t+ \", \" + \"on Cloud: \" \r\n\t\t\t\t+ String.format(\"%.6f\", processingTimeOnCloud[numOfAppTypes] / (double) completedTaskOnCloud[numOfAppTypes])\r\n\t\t\t\t+ \", \" + \"on Mobile: \" \r\n\t\t\t\t+ String.format(\"%.6f\", processingTimeOnMobile[numOfAppTypes] / (double) completedTaskOnMobile[numOfAppTypes])\r\n\t\t\t\t+ \")\");\r\n\r\n\t\tprintLine(\"average network delay: \"\r\n\t\t\t\t+ String.format(\"%.6f\", networkDelay[numOfAppTypes] / ((double) completedTask[numOfAppTypes] - (double) completedTaskOnMobile[numOfAppTypes]))\r\n\t\t\t\t+ \" seconds. (\" + \"LAN delay: \"\r\n\t\t\t\t+ String.format(\"%.6f\", lanDelay[numOfAppTypes] / (double) lanUsage[numOfAppTypes])\r\n\t\t\t\t+ \", \" + \"MAN delay: \"\r\n\t\t\t\t+ String.format(\"%.6f\", manDelay[numOfAppTypes] / (double) manUsage[numOfAppTypes])\r\n\t\t\t\t+ \", \" + \"WAN delay: \"\r\n\t\t\t\t+ String.format(\"%.6f\", wanDelay[numOfAppTypes] / (double) wanUsage[numOfAppTypes])\r\n\t\t\t\t+ \", \" + \"GSM delay: \"\r\n\t\t\t\t+ String.format(\"%.6f\", gsmDelay[numOfAppTypes] / (double) gsmUsage[numOfAppTypes]) + \")\");\r\n\r\n\t\tprintLine(\"average server utilization Edge/Cloud/Mobile: \" \r\n\t\t\t\t+ String.format(\"%.6f\", totalVmLoadOnEdge / (double) vmLoadList.size()) + \"/\"\r\n\t\t\t\t+ String.format(\"%.6f\", totalVmLoadOnCloud / (double) vmLoadList.size()) + \"/\"\r\n\t\t\t\t+ String.format(\"%.6f\", totalVmLoadOnMobile / (double) vmLoadList.size()));\r\n\r\n\t\tprintLine(\"average cost: \" + cost[numOfAppTypes] / completedTask[numOfAppTypes] + \"$\");\r\n\t\tprintLine(\"average overhead: \" + orchestratorOverhead[numOfAppTypes] / (failedTask[numOfAppTypes] + completedTask[numOfAppTypes]) + \" ns\");\r\n\t\tprintLine(\"average QoE (for all): \" + QoE[numOfAppTypes] / (failedTask[numOfAppTypes] + completedTask[numOfAppTypes]) + \"%\");\r\n\t\tprintLine(\"average QoE (for executed): \" + QoE[numOfAppTypes] / completedTask[numOfAppTypes] + \"%\");\r\n\r\n\t\t// clear related collections (map list etc.)\r\n\t\ttaskMap.clear();\r\n\t\tvmLoadList.clear();\r\n\t\tapDelayList.clear();\r\n\t}\r\n\t\r\n\tprivate void recordLog(int taskId){\r\n\t\tLogItem value = taskMap.remove(taskId);\r\n\t\t\r\n\t\tif (value.isInWarmUpPeriod())\r\n\t\t\treturn;\r\n\r\n\t\tif (value.getStatus() == SimLogger.TASK_STATUS.COMLETED) {\r\n\t\t\tcompletedTask[value.getTaskType()]++;\r\n\r\n\t\t\tif (value.getVmType() == SimSettings.VM_TYPES.CLOUD_VM.ordinal())\r\n\t\t\t\tcompletedTaskOnCloud[value.getTaskType()]++;\r\n\t\t\telse if (value.getVmType() == SimSettings.VM_TYPES.MOBILE_VM.ordinal())\r\n\t\t\t\tcompletedTaskOnMobile[value.getTaskType()]++;\r\n\t\t\telse\r\n\t\t\t\tcompletedTaskOnEdge[value.getTaskType()]++;\r\n\t\t}\r\n\t\telse {\r\n\t\t\tfailedTask[value.getTaskType()]++;\r\n\r\n\t\t\tif (value.getVmType() == SimSettings.VM_TYPES.CLOUD_VM.ordinal())\r\n\t\t\t\tfailedTaskOnCloud[value.getTaskType()]++;\r\n\t\t\telse if (value.getVmType() == SimSettings.VM_TYPES.MOBILE_VM.ordinal())\r\n\t\t\t\tfailedTaskOnMobile[value.getTaskType()]++;\r\n\t\t\telse\r\n\t\t\t\tfailedTaskOnEdge[value.getTaskType()]++;\r\n\t\t}\r\n\r\n\t\tif (value.getStatus() == SimLogger.TASK_STATUS.COMLETED) {\r\n\t\t\tcost[value.getTaskType()] += value.getCost();\r\n\t\t\tQoE[value.getTaskType()] += value.getQoE();\r\n\t\t\tserviceTime[value.getTaskType()] += value.getServiceTime();\r\n\t\t\tnetworkDelay[value.getTaskType()] += value.getNetworkDelay();\r\n\t\t\tprocessingTime[value.getTaskType()] += (value.getServiceTime() - value.getNetworkDelay());\r\n\t\t\torchestratorOverhead[value.getTaskType()] += value.getOrchestratorOverhead();\r\n\t\t\t\r\n\t\t\tif(value.getNetworkDelay(NETWORK_DELAY_TYPES.WLAN_DELAY) != 0) {\r\n\t\t\t\tlanUsage[value.getTaskType()]++;\r\n\t\t\t\tlanDelay[value.getTaskType()] += value.getNetworkDelay(NETWORK_DELAY_TYPES.WLAN_DELAY);\r\n\t\t\t}\r\n\t\t\tif(value.getNetworkDelay(NETWORK_DELAY_TYPES.MAN_DELAY) != 0) {\r\n\t\t\t\tmanUsage[value.getTaskType()]++;\r\n\t\t\t\tmanDelay[value.getTaskType()] += value.getNetworkDelay(NETWORK_DELAY_TYPES.MAN_DELAY);\r\n\t\t\t}\r\n\t\t\tif(value.getNetworkDelay(NETWORK_DELAY_TYPES.WAN_DELAY) != 0) {\r\n\t\t\t\twanUsage[value.getTaskType()]++;\r\n\t\t\t\twanDelay[value.getTaskType()] += value.getNetworkDelay(NETWORK_DELAY_TYPES.WAN_DELAY);\r\n\t\t\t}\r\n\t\t\tif(value.getNetworkDelay(NETWORK_DELAY_TYPES.GSM_DELAY) != 0) {\r\n\t\t\t\tgsmUsage[value.getTaskType()]++;\r\n\t\t\t\tgsmDelay[value.getTaskType()] += value.getNetworkDelay(NETWORK_DELAY_TYPES.GSM_DELAY);\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\tif (value.getVmType() == SimSettings.VM_TYPES.CLOUD_VM.ordinal()) {\r\n\t\t\t\tserviceTimeOnCloud[value.getTaskType()] += value.getServiceTime();\r\n\t\t\t\tprocessingTimeOnCloud[value.getTaskType()] += (value.getServiceTime() - value.getNetworkDelay());\r\n\t\t\t}\r\n\t\t\telse if (value.getVmType() == SimSettings.VM_TYPES.MOBILE_VM.ordinal()) {\r\n\t\t\t\tserviceTimeOnMobile[value.getTaskType()] += value.getServiceTime();\r\n\t\t\t\tprocessingTimeOnMobile[value.getTaskType()] += value.getServiceTime();\r\n\t\t\t}\r\n\t\t\telse {\r\n\t\t\t\tserviceTimeOnEdge[value.getTaskType()] += value.getServiceTime();\r\n\t\t\t\tprocessingTimeOnEdge[value.getTaskType()] += (value.getServiceTime() - value.getNetworkDelay());\r\n\t\t\t}\r\n\t\t} else if (value.getStatus() == SimLogger.TASK_STATUS.REJECTED_DUE_TO_VM_CAPACITY) {\r\n\t\t\tfailedTaskDueToVmCapacity[value.getTaskType()]++;\r\n\t\t\t\r\n\t\t\tif (value.getVmType() == SimSettings.VM_TYPES.CLOUD_VM.ordinal())\r\n\t\t\t\tfailedTaskDueToVmCapacityOnCloud[value.getTaskType()]++;\r\n\t\t\telse if (value.getVmType() == SimSettings.VM_TYPES.MOBILE_VM.ordinal())\r\n\t\t\t\tfailedTaskDueToVmCapacityOnMobile[value.getTaskType()]++;\r\n\t\t\telse\r\n\t\t\t\tfailedTaskDueToVmCapacityOnEdge[value.getTaskType()]++;\r\n\t\t} else if (value.getStatus() == SimLogger.TASK_STATUS.REJECTED_DUE_TO_BANDWIDTH\r\n\t\t\t\t|| value.getStatus() == SimLogger.TASK_STATUS.UNFINISHED_DUE_TO_BANDWIDTH) {\r\n\t\t\tfailedTaskDuetoBw[value.getTaskType()]++;\r\n\t\t\tif (value.getNetworkError() == NETWORK_ERRORS.LAN_ERROR)\r\n\t\t\t\tfailedTaskDuetoLanBw[value.getTaskType()]++;\r\n\t\t\telse if (value.getNetworkError() == NETWORK_ERRORS.MAN_ERROR)\r\n\t\t\t\tfailedTaskDuetoManBw[value.getTaskType()]++;\r\n\t\t\telse if (value.getNetworkError() == NETWORK_ERRORS.WAN_ERROR)\r\n\t\t\t\tfailedTaskDuetoWanBw[value.getTaskType()]++;\r\n\t\t\telse if (value.getNetworkError() == NETWORK_ERRORS.GSM_ERROR)\r\n\t\t\t\tfailedTaskDuetoGsmBw[value.getTaskType()]++;\r\n\t\t} else if (value.getStatus() == SimLogger.TASK_STATUS.UNFINISHED_DUE_TO_MOBILITY) {\r\n\t\t\tfailedTaskDuetoMobility[value.getTaskType()]++;\r\n\t\t} else if (value.getStatus() == SimLogger.TASK_STATUS.REJECTED_DUE_TO_WLAN_COVERAGE) {\r\n\t\t\trefectedTaskDuetoWlanRange[value.getTaskType()]++;;\r\n }\r\n\t\t\r\n\t\t//if deep file logging is enabled, record every task result\r\n\t\tif (SimSettings.getInstance().getDeepFileLoggingEnabled()){\r\n\t\t\ttry {\r\n\t\t\t\tif (value.getStatus() == SimLogger.TASK_STATUS.COMLETED)\r\n\t\t\t\t\tappendToFile(successBW, value.toString(taskId));\r\n\t\t\t\telse\r\n\t\t\t\t\tappendToFile(failBW, value.toString(taskId));\r\n\t\t\t} catch (IOException e) {\r\n\t\t\t\te.printStackTrace();\r\n\t\t\t\tSystem.exit(1);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r"
] | import edu.boun.edgecloudsim.utils.SimLogger;
import java.util.List;
import org.antlr.runtime.RecognitionException;
import org.cloudbus.cloudsim.Host;
import org.cloudbus.cloudsim.UtilizationModelFull;
import org.cloudbus.cloudsim.Vm;
import org.cloudbus.cloudsim.core.CloudSim;
import org.cloudbus.cloudsim.core.SimEvent;
import net.sourceforge.jFuzzyLogic.FIS;
import edu.boun.edgecloudsim.cloud_server.CloudVM;
import edu.boun.edgecloudsim.core.SimManager;
import edu.boun.edgecloudsim.core.SimSettings;
import edu.boun.edgecloudsim.edge_orchestrator.EdgeOrchestrator;
import edu.boun.edgecloudsim.edge_server.EdgeHost;
import edu.boun.edgecloudsim.edge_server.EdgeVM;
import edu.boun.edgecloudsim.edge_client.CpuUtilizationModel_Custom;
import edu.boun.edgecloudsim.edge_client.Task; | fis2.setVariable("nearest_edge_uitl", nearestEdgeUtilization);
fis2.setVariable("best_remote_edge_uitl", bestRemoteEdgeUtilization);
// Evaluate
fis2.evaluate();
/*
SimLogger.printLine("########################################");
SimLogger.printLine("man bw: " + manBW);
SimLogger.printLine("nearest_edge_uitl: " + nearestEdgeUtilization);
SimLogger.printLine("best_remote_edge_uitl: " + bestRemoteEdgeHostUtilization);
SimLogger.printLine("offload_decision: " + fis2.getVariable("offload_decision").getValue());
SimLogger.printLine("########################################");
*/
if(fis2.getVariable("offload_decision").getValue() > 50){
bestHostIndex = bestRemoteEdgeHostIndex;
bestHostUtilization = bestRemoteEdgeUtilization;
}
double delay_sensitivity = SimSettings.getInstance().getTaskLookUpTable()[task.getTaskType()][12];
// Set inputs
fis1.setVariable("wan_bw", wanBW);
fis1.setVariable("task_size", task.getCloudletLength());
fis1.setVariable("delay_sensitivity", delay_sensitivity);
fis1.setVariable("avg_edge_util", bestHostUtilization);
// Evaluate
fis1.evaluate();
/*
SimLogger.printLine("########################################");
SimLogger.printLine("wan bw: " + wanBW);
SimLogger.printLine("task_size: " + task.getCloudletLength());
SimLogger.printLine("delay_sensitivity: " + delay_sensitivity);
SimLogger.printLine("avg_edge_util: " + bestHostUtilization);
SimLogger.printLine("offload_decision: " + fis1.getVariable("offload_decision").getValue());
SimLogger.printLine("########################################");
*/
if(fis1.getVariable("offload_decision").getValue() > 50){
result = SimSettings.CLOUD_DATACENTER_ID;
}
else{
result = bestHostIndex;
}
}
else if(policy.equals("FUZZY_COMPETITOR")){
double utilization = edgeUtilization;
double cpuSpeed = (double)100 - utilization;
double videoExecution = SimSettings.getInstance().getTaskLookUpTable()[task.getTaskType()][12];
double dataSize = task.getCloudletFileSize() + task.getCloudletOutputSize();
double normalizedDataSize = Math.min(MAX_DATA_SIZE, dataSize)/MAX_DATA_SIZE;
// Set inputs
fis3.setVariable("wan_bw", wanBW);
fis3.setVariable("cpu_speed", cpuSpeed);
fis3.setVariable("video_execution", videoExecution);
fis3.setVariable("data_size", normalizedDataSize);
// Evaluate
fis3.evaluate();
/*
SimLogger.printLine("########################################");
SimLogger.printLine("wan bw: " + wanBW);
SimLogger.printLine("cpu_speed: " + cpuSpeed);
SimLogger.printLine("video_execution: " + videoExecution);
SimLogger.printLine("data_size: " + normalizedDataSize);
SimLogger.printLine("offload_decision: " + fis2.getVariable("offload_decision").getValue());
SimLogger.printLine("########################################");
*/
if(fis3.getVariable("offload_decision").getValue() > 50)
result = SimSettings.CLOUD_DATACENTER_ID;
else
result = SimSettings.GENERIC_EDGE_DEVICE_ID;
}
else if(policy.equals("NETWORK_BASED")){
if(wanBW > 6)
result = SimSettings.CLOUD_DATACENTER_ID;
else
result = SimSettings.GENERIC_EDGE_DEVICE_ID;
}
else if(policy.equals("UTILIZATION_BASED")){
double utilization = edgeUtilization;
if(utilization > 80)
result = SimSettings.CLOUD_DATACENTER_ID;
else
result = SimSettings.GENERIC_EDGE_DEVICE_ID;
}
else if(policy.equals("HYBRID")){
double utilization = edgeUtilization;
if(wanBW > 6 && utilization > 80)
result = SimSettings.CLOUD_DATACENTER_ID;
else
result = SimSettings.GENERIC_EDGE_DEVICE_ID;
}
else {
SimLogger.printLine("Unknown edge orchestrator policy! Terminating simulation...");
System.exit(0);
}
}
else {
SimLogger.printLine("Unknown simulation scenario! Terminating simulation...");
System.exit(0);
}
return result;
}
@Override
public Vm getVmToOffload(Task task, int deviceId) {
Vm selectedVM = null;
if(deviceId == SimSettings.CLOUD_DATACENTER_ID){
//Select VM on cloud devices via Least Loaded algorithm!
double selectedVmCapacity = 0; //start with min value
List<Host> list = SimManager.getInstance().getCloudServerManager().getDatacenter().getHostList();
for (int hostIndex=0; hostIndex < list.size(); hostIndex++) { | List<CloudVM> vmArray = SimManager.getInstance().getCloudServerManager().getVmList(hostIndex); | 0 |
millecker/storm-apps | commons/src/at/illecker/storm/commons/svm/featurevector/POSFeatureVectorGenerator.java | [
"public class Configuration {\n private static final Logger LOG = LoggerFactory\n .getLogger(Configuration.class);\n\n public static final boolean RUNNING_WITHIN_JAR = Configuration.class\n .getResource(\"Configuration.class\").toString().startsWith(\"jar:\");\n\n public static final String WORKING_DIR_PATH = (RUNNING_WITHIN_JAR) ? \"\"\n : System.getProperty(\"user.dir\") + File.separator;\n\n public static final String TEMP_DIR_PATH = System\n .getProperty(\"java.io.tmpdir\");\n\n public static final String GLOBAL_RESOURCES_DATASETS_SEMEVAL = \"global.resources.datasets.semeval\";\n public static final String GLOBAL_RESOURCES_DATASETS_CRAWLER = \"global.resources.datasets.crawler\";\n\n public static final String GLOBAL_RESOURCES_DICT = \"global.resources.dict\";\n public static final String GLOBAL_RESOURCES_DICT_SENTIMENT = \"global.resources.dict.sentiment\";\n public static final String GLOBAL_RESOURCES_DICT_SENTIMENT_SENTIWORDNET_PATH = \"global.resources.dict.sentiment.sentiwordnet.path\";\n public static final String GLOBAL_RESOURCES_DICT_SLANG = \"global.resources.dict.slang\";\n public static final String GLOBAL_RESOURCES_DICT_WORDNET_PATH = \"global.resources.dict.wordnet.path\";\n\n public static final Map CONFIG = readConfig();\n\n @SuppressWarnings(\"rawtypes\")\n public static Map readConfig() {\n Map conf = readConfigFile(WORKING_DIR_PATH + \"conf/defaults.yaml\", true);\n // read custom config\n LOG.info(\"Try to load user-specific config...\");\n Map customConfig = readConfigFile(WORKING_DIR_PATH\n + \"conf/configuration.yaml\", false);\n if (customConfig != null) {\n conf.putAll(customConfig);\n } else if (RUNNING_WITHIN_JAR) {\n customConfig = readConfigFile(\"../conf/configuration.yaml\", false);\n if (customConfig != null) {\n conf.putAll(customConfig);\n }\n }\n return conf;\n }\n\n @SuppressWarnings(\"rawtypes\")\n public static Map readConfigFile(String file, boolean mustExist) {\n Yaml yaml = new Yaml(new SafeConstructor());\n Map ret = null;\n InputStream input = IOUtils.getInputStream(file);\n if (input != null) {\n ret = (Map) yaml.load(new InputStreamReader(input));\n LOG.info(\"Loaded \" + file);\n try {\n input.close();\n } catch (IOException e) {\n LOG.error(\"IOException: \" + e.getMessage());\n }\n } else if (mustExist) {\n LOG.error(\"Config file \" + file + \" was not found!\");\n }\n if ((ret == null) && (mustExist)) {\n throw new RuntimeException(\"Config file \" + file + \" was not found!\");\n }\n return ret;\n }\n\n public static <K, V> V get(K key) {\n return get(key, null);\n }\n\n public static <K, V> V get(K key, V defaultValue) {\n return get((Map<K, V>) CONFIG, key, defaultValue);\n }\n\n public static <K, V> V get(Map<K, V> map, K key, V defaultValue) {\n V value = map.get(key);\n if (value == null) {\n value = defaultValue;\n }\n return value;\n }\n\n public static Dataset getDataSetSemEval2013() {\n return Dataset.readFromYaml((Map) ((Map) CONFIG\n .get(GLOBAL_RESOURCES_DATASETS_SEMEVAL)).get(\"2013\"));\n }\n\n public static Dataset getDataSetSemEval2013Mixed() {\n return Dataset.readFromYaml((Map) ((Map) CONFIG\n .get(GLOBAL_RESOURCES_DATASETS_SEMEVAL)).get(\"2013Mixed\"));\n }\n\n public static Dataset getDataSetSemEval2014() {\n return Dataset.readFromYaml((Map) ((Map) CONFIG\n .get(GLOBAL_RESOURCES_DATASETS_SEMEVAL)).get(\"2014\"));\n }\n\n public static List<Status> getDataSetCrawler() {\n return getDataSetCrawler((String) ((Map) ((Map) CONFIG\n .get(GLOBAL_RESOURCES_DATASETS_CRAWLER)).get(\"Crawler\"))\n .get(\"language.filter\"));\n }\n\n public static List<Status> getDataSetCrawler(String filterLanguage) {\n return JsonUtils.readTweetsDirectory((String) ((Map) ((Map) CONFIG\n .get(GLOBAL_RESOURCES_DATASETS_CRAWLER)).get(\"Crawler\")).get(\"path\"),\n filterLanguage);\n }\n\n public static List<Status> getDataSetCrawlerTest() {\n return getDataSetCrawlerTest((String) ((Map) ((Map) CONFIG\n .get(GLOBAL_RESOURCES_DATASETS_CRAWLER)).get(\"CrawlerTest\"))\n .get(\"language.filter\"));\n }\n\n public static List<Status> getDataSetCrawlerTest(String filterLanguage) {\n return JsonUtils.readTweetsDirectory((String) ((Map) ((Map) CONFIG\n .get(GLOBAL_RESOURCES_DATASETS_CRAWLER)).get(\"CrawlerTest\"))\n .get(\"path\"), filterLanguage);\n }\n\n public static List<String> getNameEntities() {\n return (List<String>) ((Map) CONFIG.get(GLOBAL_RESOURCES_DICT))\n .get(\"NameEntities\");\n }\n\n public static List<String> getFirstNames() {\n return (List<String>) ((Map) CONFIG.get(GLOBAL_RESOURCES_DICT))\n .get(\"FirstNames\");\n }\n\n public static List<Map> getEmoticons() {\n return (List<Map>) ((Map) CONFIG.get(GLOBAL_RESOURCES_DICT))\n .get(\"Emoticons\");\n }\n\n public static List<Map> getInterjections() {\n return (List<Map>) ((Map) CONFIG.get(GLOBAL_RESOURCES_DICT))\n .get(\"Interjections\");\n }\n\n public static List<String> getStopWords() {\n return (List<String>) ((Map) CONFIG.get(GLOBAL_RESOURCES_DICT))\n .get(\"StopWords\");\n }\n\n public static List<Map> getSentimentWordlists() {\n return (List<Map>) CONFIG.get(GLOBAL_RESOURCES_DICT_SENTIMENT);\n }\n\n public static String getSentiWordNetDict() {\n return (String) CONFIG\n .get(GLOBAL_RESOURCES_DICT_SENTIMENT_SENTIWORDNET_PATH);\n }\n\n public static List<Map> getSlangWordlists() {\n return (List<Map>) CONFIG.get(GLOBAL_RESOURCES_DICT_SLANG);\n }\n\n public static String getWordNetDict() {\n return (String) CONFIG.get(GLOBAL_RESOURCES_DICT_WORDNET_PATH);\n }\n\n}",
"public class ArkPOSTagger {\n private static final Logger LOG = LoggerFactory.getLogger(ArkPOSTagger.class);\n private static final boolean LOGGING = Configuration.get(\n \"commons.postagger.logging\", false);\n private static final ArkPOSTagger INSTANCE = new ArkPOSTagger();\n String m_taggingModel;\n private Model m_model;\n private FeatureExtractor m_featureExtractor;\n\n private ArkPOSTagger() {\n // Load ARK POS Tagger\n try {\n m_taggingModel = Configuration\n .get(\"global.resources.postagger.ark.model.path\");\n LOG.info(\"Load ARK POS Tagger with model: \" + m_taggingModel);\n // TODO absolute path needed for resource\n if ((Configuration.RUNNING_WITHIN_JAR)\n && (!m_taggingModel.startsWith(\"/\"))) {\n m_taggingModel = \"/\" + m_taggingModel;\n }\n m_model = Model.loadModelFromText(m_taggingModel);\n m_featureExtractor = new FeatureExtractor(m_model, false);\n } catch (IOException e) {\n LOG.error(\"IOException: \" + e.getMessage());\n }\n }\n\n public static ArkPOSTagger getInstance() {\n return INSTANCE;\n }\n\n public List<List<TaggedToken>> tagTweets(List<List<String>> tweets) {\n List<List<TaggedToken>> taggedTweets = new ArrayList<List<TaggedToken>>();\n for (List<String> tweet : tweets) {\n taggedTweets.add(tag(tweet));\n }\n return taggedTweets;\n }\n\n public List<TaggedToken> tag(List<String> tokens) {\n Sentence sentence = new Sentence();\n sentence.tokens = tokens;\n ModelSentence ms = new ModelSentence(sentence.T());\n m_featureExtractor.computeFeatures(sentence, ms);\n m_model.greedyDecode(ms, false);\n\n List<TaggedToken> taggedTokens = new ArrayList<TaggedToken>();\n for (int t = 0; t < sentence.T(); t++) {\n TaggedToken tt = new TaggedToken(tokens.get(t),\n m_model.labelVocab.name(ms.labels[t]));\n taggedTokens.add(tt);\n }\n return taggedTokens;\n }\n\n public void serializeModel() {\n SerializationUtils.serialize(m_model, m_taggingModel + \"_model.ser\");\n }\n\n public void serializeFeatureExtractor() {\n SerializationUtils.serialize(m_featureExtractor, m_taggingModel\n + \"_featureExtractor.ser\");\n }\n\n public static void main(String[] args) {\n boolean extendedTest = false;\n boolean useSerialization = true;\n\n // load tweets\n List<Tweet> tweets = null;\n if (extendedTest) {\n // Twitter crawler\n // List<Status> extendedTweets = Configuration\n // .getDataSetUibkCrawlerTest(\"en\");\n // tweets = new ArrayList<Tweet>();\n // for (Status tweet : extendedTweets) {\n // tweets.add(new Tweet(tweet.getId(), tweet.getText(), 0));\n // }\n\n // SemEval2013\n Dataset dataset = Configuration.getDataSetSemEval2013();\n tweets = dataset.getTrainTweets(true);\n } else {\n tweets = Tweet.getTestTweets();\n }\n\n Preprocessor preprocessor = Preprocessor.getInstance();\n ArkPOSTagger posTagger = ArkPOSTagger.getInstance();\n\n if (useSerialization) {\n posTagger.serializeModel();\n posTagger.serializeFeatureExtractor();\n }\n\n // process tweets\n long startTime = System.currentTimeMillis();\n for (Tweet tweet : tweets) {\n // Tokenize\n List<String> tokens = Tokenizer.tokenize(tweet.getText());\n\n // Preprocess\n List<String> preprocessedTokens = preprocessor.preprocess(tokens);\n\n // POS Tagging\n List<TaggedToken> taggedTokens = posTagger.tag(preprocessedTokens);\n\n LOG.info(\"Tweet: '\" + tweet + \"'\");\n LOG.info(\"TaggedTweet: \" + taggedTokens);\n }\n long elapsedTime = System.currentTimeMillis() - startTime;\n LOG.info(\"POSTagger finished after \" + elapsedTime + \" ms\");\n LOG.info(\"Total tweets: \" + tweets.size());\n LOG.info((elapsedTime / (double) tweets.size()) + \" ms per Tweet\");\n }\n\n}",
"public class GatePOSTagger {\n private static final Logger LOG = LoggerFactory\n .getLogger(GatePOSTagger.class);\n private static final boolean LOGGING = Configuration.get(\n \"commons.postagger.logging\", false);\n private static final GatePOSTagger INSTANCE = new GatePOSTagger();\n private MaxentTagger m_posTagger;\n\n private GatePOSTagger() {\n // Load Stanford POS Tagger with GATE model\n String taggingModel = Configuration\n .get(\"global.resources.postagger.gate.model.path\");\n LOG.info(\"Load Stanford POS Tagger with model: \" + taggingModel);\n TaggerConfig posTaggerConf = new TaggerConfig(\"-model\", taggingModel);\n m_posTagger = new MaxentTagger(taggingModel, posTaggerConf, false);\n }\n\n public static GatePOSTagger getInstance() {\n return INSTANCE;\n }\n\n public List<List<TaggedWord>> tagTweets(List<List<TaggedWord>> tweets) {\n List<List<TaggedWord>> taggedTweets = new ArrayList<List<TaggedWord>>();\n for (List<TaggedWord> tweet : tweets) {\n taggedTweets.add(tag(tweet));\n }\n return taggedTweets;\n }\n\n public List<TaggedWord> tag(List<TaggedWord> pretaggedTokens) {\n return m_posTagger.tagSentence(pretaggedTokens, true);\n }\n\n public static void main(String[] args) {\n boolean extendedTest = true;\n\n // load tweets\n List<Tweet> tweets = null;\n if (extendedTest) {\n // Twitter crawler\n // List<Status> extendedTweets = Configuration\n // .getDataSetUibkCrawlerTest(\"en\");\n // tweets = new ArrayList<Tweet>();\n // for (Status tweet : extendedTweets) {\n // tweets.add(new Tweet(tweet.getId(), tweet.getText(), 0));\n // }\n\n // SemEval2013\n Dataset dataset = Configuration.getDataSetSemEval2013();\n tweets = dataset.getTrainTweets(true);\n } else {\n tweets = Tweet.getTestTweets();\n }\n\n Preprocessor preprocessor = Preprocessor.getInstance();\n GatePOSTagger posTagger = GatePOSTagger.getInstance();\n\n // process tweets\n long startTime = System.currentTimeMillis();\n for (Tweet tweet : tweets) {\n // Tokenize\n List<String> tokens = Tokenizer.tokenize(tweet.getText());\n\n // Preprocess\n List<TaggedWord> preprocessedTokens = preprocessor\n .preprocessAndTag(tokens);\n\n // POS Tagging\n List<TaggedWord> taggedTokens = posTagger.tag(preprocessedTokens);\n\n LOG.info(\"Tweet: '\" + tweet + \"'\");\n LOG.info(\"TaggedTweet: \" + taggedTokens);\n }\n long elapsedTime = System.currentTimeMillis() - startTime;\n LOG.info(\"POSTagger finished after \" + elapsedTime + \" ms\");\n LOG.info(\"Total tweets: \" + tweets.size());\n LOG.info((elapsedTime / (double) tweets.size()) + \" ms per Tweet\");\n }\n\n}",
"public class Preprocessor {\n private static final Logger LOG = LoggerFactory.getLogger(Preprocessor.class);\n private static final boolean LOGGING = Configuration.get(\n \"commons.preprocessor.logging\", false);\n private static final Preprocessor INSTANCE = new Preprocessor();\n\n private WordNet m_wordnet;\n private SlangCorrection m_slangCorrection;\n private FirstNames m_firstNames;\n private NameEntities m_nameEntities;\n private Interjections m_interjections;\n\n private Preprocessor() {\n // Load WordNet\n m_wordnet = WordNet.getInstance();\n // Load Slang correction\n m_slangCorrection = SlangCorrection.getInstance();\n // Load FirstNames\n m_firstNames = FirstNames.getInstance();\n // Load NameEntities\n m_nameEntities = NameEntities.getInstance();\n // Load Interjections\n m_interjections = Interjections.getInstance();\n }\n\n public static Preprocessor getInstance() {\n return INSTANCE;\n }\n\n public List<String> preprocess(List<String> tokens) {\n // tail recursion\n return preprocessAccumulator(new LinkedList<String>(tokens), false,\n new ArrayList<String>());\n }\n\n public List<TaggedWord> preprocessAndTag(List<String> tokens) {\n // tail recursion\n return preprocessAccumulator(new LinkedList<String>(tokens), true,\n new ArrayList<TaggedWord>());\n }\n\n @SuppressWarnings(\"unchecked\")\n private <T> List<T> preprocessAccumulator(LinkedList<String> tokens,\n boolean pretag, List<T> processedTokens) {\n\n if (tokens.isEmpty()) {\n return processedTokens;\n } else {\n // remove token from queue\n String token = tokens.removeFirst();\n\n // identify token\n boolean tokenContainsPunctuation = StringUtils\n .consitsOfPunctuations(token);\n boolean tokenIsEmoticon = StringUtils.isEmoticon(token);\n boolean tokenIsURL = StringUtils.isURL(token);\n boolean tokenIsNumeric = StringUtils.isNumeric(token);\n\n // Step 1) Unify Emoticons remove repeating chars\n if ((tokenIsEmoticon) && (!tokenIsURL) && (!tokenIsNumeric)) {\n Matcher m = RegexUtils.TWO_OR_MORE_REPEATING_CHARS_PATTERN\n .matcher(token);\n if (m.find()) {\n boolean isSpecialEmoticon = m.group(1).equals(\"^\");\n String reducedToken = m.replaceAll(\"$1\");\n if (isSpecialEmoticon) { // keep ^^\n reducedToken += \"^\";\n }\n // else {\n // TODO\n // Preprocess token again if there are recursive patterns in it\n // e.g., :):):) -> :):) -> :) Not possible because of Tokenizer\n // tokens.add(0, reducedToken);\n // }\n if (LOGGING) {\n LOG.info(\"Unify Emoticon from '\" + token + \"' to '\" + reducedToken\n + \"'\");\n }\n\n if (pretag) {\n processedTokens.add((T) new TaggedWord(reducedToken, \"UH\"));\n } else {\n processedTokens.add((T) reducedToken);\n }\n return preprocessAccumulator(tokens, pretag, processedTokens);\n }\n } else if (tokenContainsPunctuation) {\n // If token is no Emoticon then there is no further\n // preprocessing for punctuations\n if (pretag) {\n processedTokens.add((T) new TaggedWord(token));\n } else {\n processedTokens.add((T) token);\n }\n return preprocessAccumulator(tokens, pretag, processedTokens);\n }\n\n // identify token\n boolean tokenIsUser = StringUtils.isUser(token);\n boolean tokenIsHashTag = StringUtils.isHashTag(token);\n boolean tokenIsSlang = StringUtils.isSlang(token);\n boolean tokenIsEmail = StringUtils.isEmail(token);\n boolean tokenIsPhone = StringUtils.isPhone(token);\n boolean tokenIsSpecialNumeric = StringUtils.isSpecialNumeric(token);\n boolean tokenIsSeparatedNumeric = StringUtils.isSeparatedNumeric(token);\n\n // Step 2) Slang Correction\n // TODO prevent slang correction if all UPPERCASE\n // 'FC' to [fruit, cake]\n // 'Ajax' to [Asynchronous, Javascript, and, XML]\n // 'TL' to [dr too, long, didn't, read]\n // S.O.L - SOL - [s**t, outta, luck]\n // 'AC/DC' to 'AC' and 'DC' - 'DC' to [don't, care]\n // TODO update dictionary O/U O/A\n if ((!tokenIsEmoticon) && (!tokenIsUser) && (!tokenIsHashTag)\n && (!tokenIsURL) && (!tokenIsNumeric) && (!tokenIsSpecialNumeric)\n && (!tokenIsSeparatedNumeric) && (!tokenIsEmail) && (!tokenIsPhone)) {\n String[] slangCorrection = m_slangCorrection.getCorrection(token\n .toLowerCase());\n if (slangCorrection != null) {\n for (int i = 0; i < slangCorrection.length; i++) {\n if (pretag) {\n // PreTagging for POS Tagger\n TaggedWord preTaggedToken = pretagToken(slangCorrection[i],\n tokenIsHashTag, tokenIsUser, tokenIsURL);\n processedTokens.add((T) preTaggedToken);\n } else {\n processedTokens.add((T) slangCorrection[i]);\n }\n }\n if (LOGGING) {\n LOG.info(\"Slang Correction from '\" + token + \"' to \"\n + Arrays.toString(slangCorrection));\n }\n return preprocessAccumulator(tokens, pretag, processedTokens);\n } else if (tokenIsSlang) {\n if (token.startsWith(\"w/\")) {\n if (pretag) {\n processedTokens.add((T) new TaggedWord(\"with\"));\n // PreTagging for POS Tagger\n TaggedWord preTaggedToken = pretagToken(token.substring(2),\n tokenIsHashTag, tokenIsUser, tokenIsURL);\n processedTokens.add((T) preTaggedToken);\n } else {\n processedTokens.add((T) \"with\");\n processedTokens.add((T) token.substring(2));\n }\n if (LOGGING) {\n LOG.info(\"Slang Correction from '\" + token + \"' to \" + \"[with, \"\n + token.substring(2) + \"]\");\n }\n return preprocessAccumulator(tokens, pretag, processedTokens);\n } else {\n if (LOGGING) {\n LOG.info(\"Slang Correction might be missing for '\" + token + \"'\");\n }\n }\n }\n }\n\n // Step 3) Check if there are punctuations between words\n // e.g., L.O.V.E\n if ((!tokenIsEmoticon) && (!tokenIsUser) && (!tokenIsHashTag)\n && (!tokenIsURL) && (!tokenIsNumeric) && (!tokenIsSpecialNumeric)\n && (!tokenIsSeparatedNumeric) && (!tokenIsEmail) && (!tokenIsPhone)) {\n // remove alternating letter dot pattern e.g., L.O.V.E\n Matcher m = RegexUtils.ALTERNATING_LETTER_DOT_PATTERN.matcher(token);\n if (m.matches()) {\n String newToken = token.replaceAll(\"\\\\.\", \"\");\n if (m_wordnet.contains(newToken)) {\n if (LOGGING) {\n LOG.info(\"Remove punctuations in word from '\" + token + \"' to '\"\n + newToken + \"'\");\n }\n token = newToken;\n if (pretag) {\n // PreTagging for POS Tagger\n TaggedWord preTaggedToken = pretagToken(token, tokenIsHashTag,\n tokenIsUser, tokenIsURL);\n processedTokens.add((T) preTaggedToken);\n } else {\n processedTokens.add((T) token);\n }\n return preprocessAccumulator(tokens, pretag, processedTokens);\n }\n }\n }\n\n // Step 4) Add missing g in gerund forms e.g., goin\n if ((!tokenIsUser) && (!tokenIsHashTag) && (!tokenIsURL)\n && (token.endsWith(\"in\")) && (!m_firstNames.isFirstName(token))\n && (!m_wordnet.contains(token.toLowerCase()))) {\n // append \"g\" if a word ends with \"in\" and is not in the vocabulary\n if (LOGGING) {\n LOG.info(\"Add missing \\\"g\\\" from '\" + token + \"' to '\" + token + \"g'\");\n }\n token = token + \"g\";\n if (pretag) {\n // PreTagging for POS Tagger, because it could be a interjection\n TaggedWord preTaggedToken = pretagToken(token, tokenIsHashTag,\n tokenIsUser, tokenIsURL);\n processedTokens.add((T) preTaggedToken);\n } else {\n processedTokens.add((T) token);\n }\n return preprocessAccumulator(tokens, pretag, processedTokens);\n }\n\n // Step 5) Remove elongations of characters (suuuper)\n // 'lollll' to 'loll' because 'loll' is found in dict\n // TODO 'AHHHHH' to 'AH'\n if ((!tokenIsEmoticon) && (!tokenIsUser) && (!tokenIsHashTag)\n && (!tokenIsURL) && (!tokenIsNumeric) && (!tokenIsSpecialNumeric)\n && (!tokenIsSeparatedNumeric) && (!tokenIsEmail) && (!tokenIsPhone)) {\n\n // remove repeating chars\n token = removeRepeatingChars(token);\n\n // Step 5b) Try Slang Correction again\n String[] slangCorrection = m_slangCorrection.getCorrection(token\n .toLowerCase());\n if (slangCorrection != null) {\n for (int i = 0; i < slangCorrection.length; i++) {\n if (pretag) {\n // PreTagging for POS Tagger\n TaggedWord preTaggedToken = pretagToken(slangCorrection[i],\n tokenIsHashTag, tokenIsUser, tokenIsURL);\n processedTokens.add((T) preTaggedToken);\n } else {\n processedTokens.add((T) slangCorrection[i]);\n }\n }\n if (LOGGING) {\n LOG.info(\"Slang Correction from '\" + token + \"' to \"\n + Arrays.toString(slangCorrection));\n }\n return preprocessAccumulator(tokens, pretag, processedTokens);\n }\n }\n\n // add token to processed list\n if (pretag) {\n // PreTagging for POS Tagger\n TaggedWord preTaggedToken = pretagToken(token, tokenIsHashTag,\n tokenIsUser, tokenIsURL);\n processedTokens.add((T) preTaggedToken);\n } else {\n processedTokens.add((T) token);\n }\n return preprocessAccumulator(tokens, pretag, processedTokens);\n }\n }\n\n private TaggedWord pretagToken(String token, boolean tokenIsHashTag,\n boolean tokenIsUser, boolean tokenIsURL) {\n TaggedWord preTaggedToken = new TaggedWord(token);\n if (tokenIsHashTag) {\n preTaggedToken.setTag(\"HT\");\n } else if (tokenIsUser) {\n preTaggedToken.setTag(\"USR\");\n } else if (tokenIsURL) {\n preTaggedToken.setTag(\"URL\");\n } else if (StringUtils.isRetweet(token)) {\n preTaggedToken.setTag(\"RT\");\n } else if (m_nameEntities.isNameEntity(token)) {\n if (LOGGING) {\n LOG.info(\"NameEntity labelled for \" + token);\n }\n preTaggedToken.setTag(\"NNP\");\n } else if ((m_interjections.isInterjection(token))\n || (StringUtils.isEmoticon(token))) {\n if (LOGGING) {\n LOG.info(\"Interjection or Emoticon labelled for \" + token);\n }\n preTaggedToken.setTag(\"UH\");\n }\n return preTaggedToken;\n }\n\n private String removeRepeatingChars(String value) {\n // if there are three repeating equal chars\n // then remove one char until the word is found in the vocabulary\n // else if the word is not found reduce the repeating chars to one\n\n // collect matches for sub-token search\n List<int[]> matches = new ArrayList<int[]>();\n\n Matcher m = RegexUtils.THREE_OR_MORE_REPEATING_CHARS_PATTERN.matcher(value);\n while (m.find()) {\n int start = m.start();\n int end = m.end();\n // String c = m.group(1);\n // LOG.info(\"token: '\" + value + \"' match at start: \" + start + \" end: \"\n // + end);\n\n // check if token is not in the vocabulary\n if (!m_wordnet.contains(value)) {\n // collect matches for subtoken check\n matches.add(new int[] { start, end });\n\n StringBuilder sb = new StringBuilder(value);\n for (int i = 0; i < end - start - 1; i++) {\n sb.deleteCharAt(start); // delete repeating char\n\n // LOG.info(\"check token: '\" + sb.toString() + \"'\");\n // check if token is in the vocabulary\n if (m_wordnet.contains(sb.toString())) {\n if (LOGGING) {\n LOG.info(\"removeRepeatingChars from token '\" + value + \"' to '\"\n + sb + \"'\");\n }\n return sb.toString();\n }\n\n // if the token is not in the vocabulary check all combinations\n // of prior matches\n // TODO really necessary?\n for (int j = 0; j < matches.size(); j++) {\n int startSub = matches.get(j)[0];\n int endSub = matches.get(j)[1];\n if (startSub != start) {\n StringBuilder subSb = new StringBuilder(sb);\n for (int k = 0; k < endSub - startSub - 1; k++) {\n subSb.deleteCharAt(startSub);\n\n // LOG.info(\"check subtoken: '\" + subSb.toString() + \"'\");\n if (m_wordnet.contains(subSb.toString())) {\n if (LOGGING) {\n LOG.info(\"removeRepeatingChars from '\" + value + \"' to '\"\n + subSb + \"'\");\n }\n return subSb.toString();\n }\n }\n }\n }\n }\n }\n }\n\n // no match have been found\n // reduce all repeating chars\n if (!matches.isEmpty()) {\n String reducedToken = m.replaceAll(\"$1\");\n if (LOGGING) {\n LOG.info(\"removeRepeatingChars(not found in dict) from '\" + value\n + \"' to '\" + reducedToken + \"'\");\n }\n value = reducedToken;\n }\n return value;\n }\n\n public List<List<String>> preprocessTweets(List<List<String>> tweets) {\n List<List<String>> preprocessedTweets = new ArrayList<List<String>>();\n for (List<String> tweet : tweets) {\n preprocessedTweets.add(preprocess(tweet));\n }\n return preprocessedTweets;\n }\n\n public List<List<TaggedWord>> preprocessAndTagTweets(List<List<String>> tweets) {\n List<List<TaggedWord>> preprocessedTweets = new ArrayList<List<TaggedWord>>();\n for (List<String> tweet : tweets) {\n preprocessedTweets.add(preprocessAndTag(tweet));\n }\n return preprocessedTweets;\n }\n\n public static void main(String[] args) {\n Preprocessor preprocessor = Preprocessor.getInstance();\n List<Tweet> tweets = null;\n boolean extendedTest = true;\n boolean debugOutput = false;\n\n // load tweets\n if (extendedTest) {\n // Twitter crawler\n // List<Status> extendedTweets = Configuration\n // .getDataSetUibkCrawlerTest(\"en\");\n // tweets = new ArrayList<Tweet>();\n // for (Status tweet : extendedTweets) {\n // tweets.add(new Tweet(tweet.getId(), tweet.getText(), 0));\n // }\n\n // SemEval2013\n Dataset dataset = Configuration.getDataSetSemEval2013();\n tweets = dataset.getTrainTweets(true);\n\n } else { // test tweets\n tweets = Tweet.getTestTweets();\n tweets.add(new Tweet(0L, \"2moro afaik bbq hf lol loool lollll\"));\n tweets\n .add(new Tweet(\n 0L,\n \"suuuper suuper professional tell aahh aaahh aahhh aaahhh aaaahhhhh gaaahh gaaahhhaaag haaahaaa hhhaaaahhhaaa\"));\n tweets.add(new Tweet(0L, \"Martin martin kevin Kevin Justin justin\"));\n tweets.add(new Tweet(0L, \"10,000 1000 +111 -111,0000.4444\"));\n tweets.add(new Tweet(0L,\n \"bankruptcy\\ud83d\\ude05 happy:-) said:-) ;-)yeah\"));\n tweets.add(new Tweet(0L, \"I\\u2019m shit\\u002c fan\\\\u002c \\\\u2019t\"));\n tweets\n .add(new Tweet(\n 0L,\n \"like...and vegas.just hosp.now lies\\u002c1st lies,1st candy....wasn\\u2019t Nevada\\u002cFlorida\\u002cOhio\\u002cTuesday lol.,.lol lol...lol..\"));\n tweets.add(new Tweet(0L, \"L.O.V.E D.R.U.G.S K.R.I.T\"));\n tweets\n .add(new Tweet(\n 0L,\n \"Lamar.....I free..edom free.edom star.Kisses,Star Yes..a Oh,I it!!!Go Jenks/sagna\"));\n tweets\n .add(new Tweet(\n 0L,\n \"32.50 $3.25 49.3% 97.1FM 97.1fm 8.30pm 12.45am 12.45AM 12.45PM 6-7pm 5-8p 6pm-9pm @9.15 tonight... 10,000 199,400 149,597,900 20,000+ 10.45,9 8/11/12\"));\n tweets\n .add(new Tweet(0L,\n \"(6ft.10) 2),Chap 85.3%(6513 ([email protected]) awayDAWN.com www.asdf.org\"));\n }\n\n // Tokenize\n List<List<String>> tokenizedTweets = Tokenizer.tokenizeTweets(tweets);\n\n // Preprocess only\n long startTime = System.currentTimeMillis();\n List<List<String>> preprocessedTweets = preprocessor\n .preprocessTweets(tokenizedTweets);\n LOG.info(\"Preprocess finished after \"\n + (System.currentTimeMillis() - startTime) + \" ms\");\n\n // Preprocess and tag\n startTime = System.currentTimeMillis();\n List<List<TaggedWord>> preprocessedTaggedTweets = preprocessor\n .preprocessAndTagTweets(tokenizedTweets);\n LOG.info(\"PreprocessAndTag finished after \"\n + (System.currentTimeMillis() - startTime) + \" ms\");\n\n if (debugOutput) {\n for (int i = 0; i < tweets.size(); i++) {\n LOG.info(\"Tweet: '\" + tweets.get(i).getText() + \"'\");\n LOG.info(\"Preprocessed: '\" + preprocessedTweets.get(i) + \"'\");\n LOG.info(\"PreprocessedTagged: '\" + preprocessedTaggedTweets.get(i)\n + \"'\");\n }\n }\n }\n}",
"public class Tokenizer {\n private static final Logger LOG = LoggerFactory.getLogger(Tokenizer.class);\n private static final boolean LOGGING = Configuration.get(\n \"commons.tokenizer.logging\", false);\n\n public static enum Type {\n REGEX_TOKENIZER, ARK_TOKENIZER, STANFORD_TOKENIZER\n }\n\n public static List<List<String>> tokenizeTweets(List<Tweet> tweets) {\n return tokenizeTweets(tweets, Type.REGEX_TOKENIZER);\n }\n\n public static List<List<String>> tokenizeTweets(List<Tweet> tweets, Type type) {\n List<List<String>> tokenizedTweets = new ArrayList<List<String>>();\n for (Tweet tweet : tweets) {\n tokenizedTweets.add(tokenize(tweet.getText(), type));\n }\n return tokenizedTweets;\n }\n\n public static List<String> tokenize(String str) {\n return tokenize(str, Type.REGEX_TOKENIZER);\n }\n\n public static List<String> tokenize(String str, Type type) {\n // Step 1) Trim text\n str = str.trim();\n\n // Step 2) Replace Unicode symbols \\u0000\n if (UnicodeUtils.containsUnicode(str)) {\n String replacedText = UnicodeUtils.replaceUnicodeSymbols(str);\n // LOG.info(\"Replaced Unicode symbols from '\" + str + \"' to '\"\n // + replacedText + \"'\");\n if ((LOGGING) && (replacedText.equals(str))) {\n LOG.warn(\"Unicode symbols could not be replaced: '\" + str + \"'\");\n }\n str = replacedText;\n }\n\n // Step 3) Replace HTML symbols &#[0-9];\n if (HtmlUtils.containsHtml(str)) {\n String replacedText = HtmlUtils.replaceHtmlSymbols(str);\n // LOG.info(\"Replaced HTML symbols from '\" + text + \"' to '\"\n // + replacedText + \"'\");\n if ((LOGGING) && (replacedText.equals(str))) {\n LOG.warn(\"HTML symbols could not be replaced: '\" + str + \"'\");\n }\n str = replacedText;\n }\n\n // Step 4) Tokenize\n List<String> tokenizedTokens = null;\n\n switch (type) {\n case REGEX_TOKENIZER:\n tokenizedTokens = new ArrayList<String>();\n Matcher m = RegexUtils.TOKENIZER_PATTERN.matcher(str);\n while (m.find()) {\n tokenizedTokens.add(m.group());\n }\n break;\n\n case ARK_TOKENIZER:\n tokenizedTokens = Twokenize.tokenize(str);\n break;\n\n case STANFORD_TOKENIZER:\n TokenizerFactory<Word> tokenizer = PTBTokenizerFactory\n .newTokenizerFactory();\n tokenizer.setOptions(\"ptb3Escaping=false\");\n List<List<HasWord>> sentences = MaxentTagger.tokenizeText(\n new StringReader(str), tokenizer);\n // Convert sentences to List<String>\n tokenizedTokens = new ArrayList<String>();\n for (List<HasWord> sentence : sentences) {\n for (HasWord word : sentence) {\n tokenizedTokens.add(word.word());\n }\n }\n break;\n\n default:\n break;\n }\n\n return tokenizedTokens;\n }\n\n public static void main(String[] args) {\n boolean extendedTest = true;\n List<Tweet> tweets = null;\n Type type = Type.REGEX_TOKENIZER;\n\n // load tweets\n if (extendedTest) {\n Dataset dataset = Configuration.getDataSetSemEval2013();\n tweets = dataset.getTrainTweets(true);\n } else { // test tweets\n tweets = Tweet.getTestTweets();\n tweets\n .add(new Tweet(\n 0L,\n \":-))) xDD XDD ;) :) :-) :) :D :o) :] :3 :c) :> =] 8) =) :} :^) :-D 8-D 8D x-D xD X-D XD =-D =D =-3 =3\"));\n tweets\n .add(new Tweet(0L,\n \">:[ :-( :( :-c :c :-< :< :-[ :[ :{ ;( :-|| :@ >:( :'-( :'( :'-) :') \\\\m/\"));\n tweets\n .add(new Tweet(\n 0L,\n \"\\\"All the money you've spent on my credit card I'm taking it out of your account\\\".... Hi I'm Sydney and I'm filing bankruptcy\\ud83d\\ude05\\ud83d\\ude05\\ud83d\\ude05\\ud83d\\ude05 \\ud83d\\ude05\"));\n tweets\n .add(new Tweet(\n 0L,\n \"word:-) Moon:Oct Jobs! Thursday:... http://t.co/TZZzrrKa +1 (000) 123-4567, (000) 123-4567, and 123-4567 \"));\n tweets\n .add(new Tweet(\n 0L,\n \"t/m k/o w/my b/slisten Rt/follow S/o S/O O/U O/A w/ w/Biden w/deals w/you w/the w/her\"));\n tweets\n .add(new Tweet(0L, \"5pm 5Am 5% $5 5-6am 7am-10pm U.S. U.K. L.O.V.E\"));\n }\n\n // Tokenize tweets\n long startTime = System.currentTimeMillis();\n for (Tweet tweet : tweets) {\n List<String> tokens = Tokenizer.tokenize(tweet.getText(), type);\n LOG.info(\"Tweet: '\" + tweet.getText() + \"'\");\n LOG.info(\"Tokens: \" + tokens);\n }\n LOG.info(\"Tokenize finished after \"\n + (System.currentTimeMillis() - startTime) + \" ms\");\n }\n\n}",
"public final class Tweet implements Serializable {\n private static final long serialVersionUID = 5246263296320608188L;\n private final Long m_id;\n private final String m_text;\n private final Double m_score;\n\n public Tweet(Long id, String text, Double score) {\n this.m_id = id;\n this.m_text = text;\n this.m_score = score;\n }\n\n public Tweet(Long id, String text) {\n this(id, text, null);\n }\n\n public Long getId() {\n return m_id;\n }\n\n public String getText() {\n return m_text;\n }\n\n public Double getScore() {\n return m_score;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (obj == null) {\n return false;\n }\n if (getClass() != obj.getClass()) {\n return false;\n }\n final Tweet other = (Tweet) obj;\n // check if id is matching\n if (this.m_id != other.getId()) {\n return false;\n }\n // check if text is matching\n if (!this.m_text.equals(other.getText())) {\n return false;\n }\n return true;\n }\n\n @Override\n public String toString() {\n return \"Tweet [id=\" + m_id + \", text=\" + m_text\n + ((m_score != null) ? \", score=\" + m_score : \"\") + \"]\";\n }\n\n public static List<Tweet> getTestTweets() {\n List<Tweet> tweets = new ArrayList<Tweet>();\n tweets.add(new Tweet(1L,\n \"Gas by my house hit $3.39 !!!! I'm goin to Chapel Hill on Sat . :)\",\n 1.0));\n tweets\n .add(new Tweet(\n 2L,\n \"@oluoch @victor_otti @kunjand I just watched it ! Sridevi's comeback .... U remember her from the 90s ?? Sun mornings on NTA ;)\",\n 1.0));\n tweets\n .add(new Tweet(\n 3L,\n \"PBR & @mokbpresents bring you Jim White at the @Do317 Lounge on October 23rd at 7 pm ! http://t.co/7x8OfC56.\",\n 0.5));\n tweets\n .add(new Tweet(\n 4L,\n \"Why is it so hard to find the @TVGuideMagazine these days ? Went to 3 stores for the Castle cover issue . NONE . Will search again tomorrow ...\",\n 0.0));\n tweets.add(new Tweet(0L,\n \"called in sick for the third straight day. ugh.\", 0.0));\n tweets\n .add(new Tweet(\n 5L,\n \"Here we go. BANK FAAAAIL FRIDAY -- The FDIC says the Bradford Bank in Baltimore, Maryland has become the 82nd bank failure of the year.\",\n 0.0));\n tweets.add(new Tweet(0L,\n \"Oh, I'm afraid your Windows-using friends will not survive.\", 0.0));\n\n tweets\n .add(new Tweet(\n 6L,\n \"Excuse the connectivity of this live stream , from Baba Amr , so many activists using only one Sat Modem . LIVE http://t.co/U283IhZ5 #Homs\"));\n tweets\n .add(new Tweet(\n 7L,\n \"Show your LOVE for your local field & it might win an award ! Gallagher Park #Bedlington current 4th in National Award http://t.co/WeiMDtQt\"));\n tweets\n .add(new Tweet(\n 8L,\n \"@firecore Can you tell me when an update for the Apple TV 3rd gen becomes available ? The missing update holds me back from buying #appletv3\"));\n tweets\n .add(new Tweet(\n 9L,\n \"My #cre blog Oklahoma Per Square Foot returns to the @JournalRecord blog hub tomorrow . I will have some interesting local data to share .\"));\n tweets\n .add(new Tweet(\n 10L,\n \"\\\" " @bbcburnsy : Loads from SB ; "talks with Chester continue ; no deals 4 out of contract players ' til Jan ; Dev t Roth , Coops to Chest'ld #hcafc \\\"\"));\n\n // thesis examples\n tweets\n .add(new Tweet(\n 11L,\n \"@user1 @user2 OMG I just watched Michael's comeback ! U remember him from the 90s ?? yaaaa \\uD83D\\uDE09 #michaelcomeback\"));\n tweets\n .add(new Tweet(12L,\n \"@user1 @user2 OMG I just watched it again ! \\uD83D\\uDE09 #michaelcomeback\"));\n tweets.add(new Tweet(13L,\n \"@user3 I luv him too ! \\uD83D\\uDE09 #michaelcomeback\"));\n\n return tweets;\n }\n\n}"
] | import cmu.arktweetnlp.Tagger.TaggedToken;
import edu.stanford.nlp.ling.TaggedWord;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import at.illecker.storm.commons.Configuration;
import at.illecker.storm.commons.postagger.ArkPOSTagger;
import at.illecker.storm.commons.postagger.GatePOSTagger;
import at.illecker.storm.commons.preprocessor.Preprocessor;
import at.illecker.storm.commons.tokenizer.Tokenizer;
import at.illecker.storm.commons.tweet.Tweet; | if (posTags[7] != 0) // emoticon
resultFeatureVector.put(m_vectorStartId + 7, posTags[7]);
}
if (LOGGING) {
LOG.info("POStags: " + Arrays.toString(posTags));
}
return resultFeatureVector;
}
private double[] countPOSTagsFromTaggedWords(List<TaggedWord> taggedWords,
boolean normalize) {
// 7 = [NOUN, VERB, ADJECTIVE, ADVERB, INTERJECTION, PUNCTUATION, HASHTAG]
double[] posTags = new double[] { 0d, 0d, 0d, 0d, 0d, 0d, 0d };
int wordCount = 0;
for (TaggedWord word : taggedWords) {
wordCount++;
String pennTag = word.tag();
if (pennTag.startsWith("NN")) {
posTags[0]++;
} else if (pennTag.startsWith("VB")) {
posTags[1]++;
} else if (pennTag.startsWith("JJ")) {
posTags[2]++;
} else if (pennTag.startsWith("RB")) {
posTags[3]++;
} else if (pennTag.startsWith("UH")) {
posTags[4]++;
} else if ((pennTag.equals(".")) || (pennTag.equals(":"))) {
posTags[5]++;
} else if (pennTag.startsWith("HT")) {
posTags[6]++;
}
}
if (normalize) {
for (int i = 0; i < posTags.length; i++) {
posTags[i] /= wordCount;
}
}
return posTags;
}
private double[] countPOSTagsFromTaggedTokens(List<TaggedToken> taggedTokens,
boolean normalize) {
// 8 = [NOUN, VERB, ADJECTIVE, ADVERB, INTERJECTION, PUNCTUATION, HASHTAG,
// EMOTICON]
double[] posTags = new double[] { 0d, 0d, 0d, 0d, 0d, 0d, 0d, 0d };
int wordCount = 0;
for (TaggedToken word : taggedTokens) {
wordCount++;
String arkTag = word.tag;
// http://www.ark.cs.cmu.edu/TweetNLP/annot_guidelines.pdf
if (arkTag.equals("N") || arkTag.equals("O") || arkTag.equals("Z")) {
// TODO || arkTag.equals("^")
posTags[0]++;
} else if (arkTag.equals("V") || arkTag.equals("T")) {
posTags[1]++;
} else if (arkTag.equals("A")) {
posTags[2]++;
} else if (arkTag.equals("R")) {
posTags[3]++;
} else if (arkTag.equals("!")) {
posTags[4]++;
} else if (arkTag.equals(",")) {
posTags[5]++;
} else if (arkTag.equals("#")) {
posTags[6]++;
} else if (arkTag.equals("E")) {
posTags[7]++;
}
}
if (normalize) {
for (int i = 0; i < posTags.length; i++) {
posTags[i] /= wordCount;
}
}
return posTags;
}
public static void main(String[] args) {
boolean useArkPOSTagger = true;
Preprocessor preprocessor = Preprocessor.getInstance();
List<Tweet> tweets = Tweet.getTestTweets();
// Tokenize
List<List<String>> tokenizedTweets = Tokenizer.tokenizeTweets(tweets);
if (useArkPOSTagger) {
ArkPOSTagger arkPOSTagger = ArkPOSTagger.getInstance();
// Preprocess only
long startTime = System.currentTimeMillis();
List<List<String>> preprocessedTweets = preprocessor
.preprocessTweets(tokenizedTweets);
LOG.info("Preprocess finished after "
+ (System.currentTimeMillis() - startTime) + " ms");
// Ark POS Tagging
startTime = System.currentTimeMillis();
List<List<TaggedToken>> taggedTweets = arkPOSTagger
.tagTweets(preprocessedTweets);
LOG.info("Ark POS Tagger finished after "
+ (System.currentTimeMillis() - startTime) + " ms");
// POS Feature Vector Generation
FeatureVectorGenerator fvg = new POSFeatureVectorGenerator(false, true);
for (List<TaggedToken> taggedTokens : taggedTweets) {
Map<Integer, Double> posFeatureVector = fvg
.generateFeatureVectorFromTaggedTokens(taggedTokens);
// Build feature vector string
String featureVectorStr = "";
for (Map.Entry<Integer, Double> feature : posFeatureVector.entrySet()) {
featureVectorStr += " " + feature.getKey() + ":" + feature.getValue();
}
LOG.info("Tweet: '" + taggedTokens + "'");
LOG.info("POSFeatureVector: " + featureVectorStr);
}
} else { | GatePOSTagger gatePOSTagger = GatePOSTagger.getInstance(); | 2 |
idega/com.idega.xformsmanager | src/java/com/idega/xformsmanager/component/FormComponent.java | [
"public interface PropertiesComponent {\n\n\tpublic abstract LocalizedStringBean getErrorMsg(ErrorType errorType);\n\n\t// public abstract LocalizedStringBean getErrorMsg();\n\n\tpublic abstract void setErrorMsg(ErrorType errorType,\n\t\t\tLocalizedStringBean errorMsg);\n\t\n\tpublic abstract Collection<ErrorType> getExistingErrors();\n\n\t// public abstract void setErrorMsg(LocalizedStringBean errorMsg);\n\n\tpublic abstract LocalizedStringBean getLabel();\n\n\tpublic abstract void setLabel(LocalizedStringBean label);\n\n\tpublic abstract boolean isRequired();\n\n\tpublic abstract void setRequired(boolean required);\n\n\tpublic abstract String getP3ptype();\n\n\tpublic abstract void setP3ptype(String p3ptype);\n\n\tpublic abstract String getAutofillKey();\n\n\tpublic abstract void setAutofillKey(String autofill_key);\n\t\n\tpublic abstract LocalizedStringBean getHelpText();\n\n\tpublic abstract void setHelpText(LocalizedStringBean help_text);\n\n//\tpublic abstract void setValidationText(LocalizedStringBean validation_text);\n//\n//\tpublic abstract LocalizedStringBean getValidationText();\n\n\tpublic abstract Variable getVariable();\n\n\tpublic abstract void setVariable(Variable variable);\n\n\tpublic abstract void setVariable(String variableStringRepresentation);\n\n\t// public abstract boolean isReadonly();\n\n\t// public abstract void setReadonly(boolean readonly);\n\n\tpublic abstract boolean isHasValidationConstraints();\n\t\n\tpublic abstract String getCalculateExp();\n\n\tpublic abstract void setCalculate(String calculate_exp);\n\n\tpublic abstract boolean isCalculate();\n\t\n\tpublic abstract void setIsCalculate(boolean isCalculate);\n\t\n\tpublic abstract void setUseHtmlEditor(boolean useHtmlEditor);\n\t\n\tpublic abstract boolean isUseHtmlEditor();\n}",
"public class ComponentDataBean {\n\t\n\tprivate Element element;\n\t// private Bind bind;\n\tprivate Element previewElement;\n\tprivate Element keyExtInstance;\n\tprivate Element keySetvalue;\n\tprivate ComponentBind componentBind;\n\t\n\tprivate Map<Locale, Element> localizedHtmlComponents;\n\t\n\tpublic Element getPreviewElement() {\n\t\treturn previewElement;\n\t}\n\t\n\tpublic void setPreviewElement(Element preview_element) {\n\t\tthis.previewElement = preview_element;\n\t}\n\t\n\tpublic Nodeset getNodeset() {\n\t\t\n\t\t// Bind bind = getBind();\n\t\tBind bind = getComponentBind().getBind();\n\t\treturn bind != null ? bind.getNodeset() : null;\n\t}\n\t\n\t/**\n\t * sets bind only, also @see putBind\n\t * \n\t * @param bind\n\t */\n\t// public void setBind(Bind bind) {\n\t// this.bind = bind;\n\t// }\n\t/**\n\t * sets bind and updates component element to reference the bind\n\t * \n\t * @param bind\n\t */\n\t// public void putBind(Bind bind) {\n\t//\t\t\n\t// bind.getFormComponent().getComponentDataBean().getElement()\n\t// .setAttribute(FormManagerUtil.bind_att, bind.getId());\n\t// this.bind = bind;\n\t// }\n\tpublic Element getElement() {\n\t\treturn element;\n\t}\n\t\n\tpublic void setElement(Element element) {\n\t\tthis.element = element;\n\t}\n\t\n\tprotected ComponentDataBean getDataBeanInstance() {\n\t\t\n\t\treturn new ComponentDataBean();\n\t}\n\t\n\tpublic Element getKeyExtInstance() {\n\t\treturn keyExtInstance;\n\t}\n\t\n\tpublic void setKeyExtInstance(Element key_ext_instance) {\n\t\tthis.keyExtInstance = key_ext_instance;\n\t}\n\t\n\tpublic Element getKeySetvalue() {\n\t\treturn keySetvalue;\n\t}\n\t\n\tpublic void setKeySetvalue(Element key_setvalue) {\n\t\tthis.keySetvalue = key_setvalue;\n\t}\n\t\n\tpublic Map<Locale, Element> getLocalizedHtmlComponents() {\n\t\t\n\t\tif (localizedHtmlComponents == null)\n\t\t\tlocalizedHtmlComponents = new HashMap<Locale, Element>();\n\t\t\n\t\treturn localizedHtmlComponents;\n\t}\n\t\n\tpublic void setLocalizedHtmlComponents(\n\t Map<Locale, Element> localizedHtmlComponents) {\n\t\tthis.localizedHtmlComponents = localizedHtmlComponents;\n\t}\n\t\n\tpublic ComponentBind getComponentBind() {\n\t\treturn componentBind;\n\t}\n\t\n\tpublic void setComponentBind(ComponentBind componentBind) {\n\t\tthis.componentBind = componentBind;\n\t}\n}",
"public class FormComponentContainerImpl extends FormComponentImpl implements\n FormComponentContainer, Container {\n\t\n\tprotected List<String> containedComponentsIdsSequence;\n\tprotected Map<String, FormComponent> containedComponents;\n\t\n\tpublic void loadContainerComponents() {\n\t\t\n\t\tfinal List<String[]> componentsTypesAndIds = getXFormsManager()\n\t\t .getContainedComponentsTypesAndIds(this);\n\t\tfinal List<String> componentsIds = getContainedComponentsIds();\n\t\t\n\t\tfinal FormComponentFactory componentsFactory = getFormDocument()\n\t\t .getContext().getFormComponentFactory();\n\t\t\n\t\tfor (String[] componentTypeAndId : componentsTypesAndIds) {\n\t\t\t\n\t\t\tString componentType = componentTypeAndId[0];\n\t\t\tString componentId = componentTypeAndId[1];\n\t\t\tFormComponent component = componentsFactory\n\t\t\t .getFormComponentByType(componentType);\n\t\t\tcomponent.setFormDocument(getFormDocument());\n\t\t\t\n\t\t\tcomponent.setId(componentId);\n\t\t\tcomponent.setParent(this);\n\t\t\tcomponentsIds.add(componentId);\n\t\t\tgetContainedComponents().put(componentId, component);\n\t\t\t\n\t\t\tcomponent.load();\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic XFormsManagerContainer getXFormsManager() {\n\t\t\n\t\treturn getFormDocument().getContext().getXformsManagerFactory()\n\t\t .getXformsManagerContainer();\n\t}\n\t\n\tpublic List<String> getContainedComponentsIds() {\n\t\t\n\t\tif (containedComponentsIdsSequence == null)\n\t\t\tcontainedComponentsIdsSequence = new LinkedList<String>();\n\t\t\n\t\treturn containedComponentsIdsSequence;\n\t}\n\t\n\tpublic FormComponent getContainedComponent(String componentId) {\n\t\t\n\t\tfinal FormComponent component;\n\t\t\n\t\tif (!getContainedComponents().containsKey(componentId)) {\n\t\t\t\n\t\t\tcomponent = null;\n\t\t\tLogger.getLogger(getClass().getName()).log(\n\t\t\t Level.WARNING,\n\t\t\t \"No component found by id = \" + componentId\n\t\t\t + \" in the contrainer (id=\" + getId() + \", form id = \"\n\t\t\t + getFormDocument().getFormId());\n\t\t} else\n\t\t\tcomponent = getContainedComponents().get(componentId);\n\t\t\n\t\treturn component;\n\t}\n\t\n\tprotected Map<String, FormComponent> getContainedComponents() {\n\t\t\n\t\tif (containedComponents == null)\n\t\t\tcontainedComponents = new HashMap<String, FormComponent>();\n\t\t\n\t\treturn containedComponents;\n\t}\n\t\n\tpublic Component addComponent(String componentType, String nextSiblingId) {\n\t\treturn (Component) addFormComponent(componentType, nextSiblingId);\n\t}\n\t\n\tpublic FormComponent addFormComponent(String componentType,\n\t String nextSiblingId) {\n\t\t\n\t\tDMContext dmContext = getFormDocument().getContext();\n\t\tFormComponent component = dmContext.getFormComponentFactory()\n\t\t .getFormComponentByType(componentType);\n\t\t\n\t\tdmContext.getComponentsTemplate().loadComponentFromTemplate(component);\n\t\t\n\t\tString generatedComponentId = getFormDocument()\n\t\t .generateNewComponentId();\n\t\tcomponent.setId(generatedComponentId);\n\t\tcomponent.setParent(this);\n\t\tcomponent.setFormDocument(getFormDocument());\n\t\t\n\t\tif (nextSiblingId != null) {\n\t\t\t\n\t\t\tFormComponent nextSibling = getContainedComponent(nextSiblingId);\n\t\t\t\n\t\t\tif (nextSibling == null)\n\t\t\t\tLogger\n\t\t\t\t .getLogger(getClass().getName())\n\t\t\t\t .log(\n\t\t\t\t Level.WARNING,\n\t\t\t\t \"The next sibling component not found by id provided = \"\n\t\t\t\t + nextSiblingId\n\t\t\t\t + \", appending to the end of children. Container id = \"\n\t\t\t\t + getId() + \" and form id = \"\n\t\t\t\t + getFormDocument().getFormId());\n\t\t\t\n\t\t\tcomponent.setNextSibling(nextSibling);\n\t\t}\n\t\t\n\t\tcomponent.create();\n\t\t\n\t\taddComponentToChildren(component, nextSiblingId);\n\t\t\n\t\treturn component;\n\t}\n\t\n\tprotected void addComponentToChildren(FormComponent component,\n\t String nextSiblingId) {\n\t\t\n\t\tgetContainedComponents().put(component.getId(), component);\n\t\t\n\t\tList<String> childrenIds = getContainedComponentsIds();\n\t\t\n\t\t// append component to the end of the list\n\t\tif (nextSiblingId == null) {\n\t\t\t\n\t\t\tif (!childrenIds.isEmpty())\n\t\t\t\t// setting the next sibling for component that goes before the\n\t\t\t\t// new component\n\t\t\t\tgetContainedComponent(childrenIds.get(childrenIds.size() - 1))\n\t\t\t\t .setNextSibling(component);\n\t\t\t\n\t\t\t// and append the new component id to the end\n\t\t\tchildrenIds.add(component.getId());\n\t\t\t\n\t\t} else {\n\t\t\t\n\t\t\t// inserting component before next sibling\n\t\t\tfor (int i = 0; i < childrenIds.size(); i++) {\n\t\t\t\t\n\t\t\t\tif (childrenIds.get(i).equals(nextSiblingId)) {\n\t\t\t\t\t\n\t\t\t\t\t// tell the component, that will go before this new\n\t\t\t\t\t// component about itself\n\t\t\t\t\tif (i != 0)\n\t\t\t\t\t\tgetContainedComponent(childrenIds.get(i - 1))\n\t\t\t\t\t\t .setNextSibling(component);\n\t\t\t\t\t\n\t\t\t\t\t// and insert to the children list\n\t\t\t\t\tchildrenIds.add(i, component.getId());\n\t\t\t\t\t\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic Component getComponent(String componentId) {\n\t\treturn (Component) getContainedComponent(componentId);\n\t}\n\t\n\t// public void tellComponentId(String componentId) {\n\t// getParent().tellComponentId(componentId);\n\t// }\n\t\n\tpublic void rearrangeComponents() {\n\t\t\n\t\tfinal List<String> containedComponentsIds = getContainedComponentsIds();\n\t\t\n\t\tint size = containedComponentsIds.size();\n\t\tMap<String, FormComponent> containedComponents = getContainedComponents();\n\t\t\n\t\tfor (int i = size - 1; i >= 0; i--) {\n\t\t\t\n\t\t\tString componentId = containedComponentsIds.get(i);\n\t\t\t\n\t\t\tif (containedComponents.containsKey(componentId)) {\n\t\t\t\t\n\t\t\t\tFormComponent comp = containedComponents.get(componentId);\n\t\t\t\t\n\t\t\t\tif (i != size - 1) {\n\t\t\t\t\t\n\t\t\t\t\tcomp.setNextSiblingRerender(containedComponents\n\t\t\t\t\t .get(containedComponentsIds.get(i + 1)));\n\t\t\t\t} else\n\t\t\t\t\tcomp.setNextSiblingRerender(null);\n\t\t\t\t\n\t\t\t} else\n\t\t\t\tthrow new NullPointerException(\n\t\t\t\t \"Component, which id was provided in list was not found. Provided: \"\n\t\t\t\t + componentId);\n\t\t}\n\t}\n\t\n\tpublic void componentsOrderChanged() {\n\t}\n\t\n\t@Override\n\tprotected void changeBindNames() {\n\t}\n\t\n\t@Override\n\tpublic void load() {\n\t\tsuper.load();\n\t\tloadContainerComponents();\n\t}\n\t\n\t// @Override\n\t// public void render() {\n\t//\t\t\n\t// boolean load = this.load;\n\t// super.render();\n\t//\t\t\n\t// if(load)\n\t// loadContainerComponents();\n\t// }\n\t\n\t@Override\n\tpublic Element getHtmlRepresentation(Locale locale) throws Exception {\n\t\tLogger\n\t\t .getLogger(getClass().getName())\n\t\t .log(\n\t\t Level.WARNING,\n\t\t \"Called getHtmlRepresentation on container component. Container doesn't have representation. Container id = \"\n\t\t + getId()\n\t\t + \" and form id = \"\n\t\t + getFormDocument().getFormId());\n\t\treturn null;\n\t}\n\t\n\t@Override\n\tpublic PropertiesComponent getProperties() {\n\t\treturn null;\n\t}\n\t\n\tpublic void unregisterComponent(String componentId) {\n\t\t\n\t\tgetContainedComponents().remove(componentId);\n\t\tgetContainedComponentsIds().remove(componentId);\n\t}\n\t\n\t/**\n\t * adds children components to the confirmation page\n\t */\n\t@Override\n\tpublic void addToConfirmationPage() {\n\t\t\n\t\tList<String> ids = getContainedComponentsIds();\n\t\t\n\t\tfor (int i = ids.size() - 1; i >= 0; i--)\n\t\t\tgetContainedComponents().get(ids.get(i)).addToConfirmationPage();\n\t}\n\t\n\t/**\n\t * removes all children components first, then removes itself\n\t */\n\t@Override\n\tpublic void remove() {\n\t\t\n\t\tList<String> containedComps = new ArrayList<String>(\n\t\t getContainedComponentsIds());\n\t\tfor (String cid : containedComps)\n\t\t\tgetComponent(cid).remove();\n\t\t\n\t\tsuper.remove();\n\t}\n\t\n\tpublic FormComponentPage getParentPage() {\n\t\t\n\t\tFormComponentContainer parent = getParent();\n\t\t\n\t\tFormComponentPage page = null;\n\t\t\n\t\twhile (page == null) {\n\t\t\t\n\t\t\tif (parent instanceof FormComponentPage)\n\t\t\t\tpage = (FormComponentPage) parent;\n\t\t\telse\n\t\t\t\tparent = parent.getParent();\n\t\t}\n\t\t\n\t\treturn page;\n\t}\n\t\n\t@Override\n\tpublic void dispatchEvent(Event eventType, Object eventContext,\n\t FormComponent dispatcher) {\n\t\t\n\t\tfor (FormComponent child : getContainedComponents().values()) {\n\t\t\tchild.dispatchEvent(eventType, eventContext, dispatcher);\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic void mappingSiblingChanged(String... relevantMappings) {\n\t\t\n\t\tfor (FormComponent component : getContainedComponents().values()) {\n\t\t\tcomponent.mappingSiblingChanged(relevantMappings);\n\t\t}\n\t}\n}",
"public enum ConstUpdateType {\n\t\n\tLABEL,\n\tCONSTRAINT_REQUIRED,\n\tCALCULATE,\n\tCALCULATE_EXP,\n\tERROR_MSG,\n\tP3P_TYPE,\n\tITEMSET,\n\tEXTERNAL_DATA_SRC,\n\tTHANKYOU_TEXT,\n\tAUTOFILL_KEY,\n\tHELP_TEXT,\n//\tREAD_ONLY,\n\tTEXT,\n\tSTEPS_VISUALIZATION_USED,\n\tSUBMISSION_ACTION,\n\tVARIABLE_NAME,\n\tBUTTON_REFER_TO_ACTION,\n\tDATA_SRC_USED,\n\tADD_BUTTON_LABEL,\n\tREMOVE_BUTTON_LABEL,\n\tDESCRIPTION_BUTTON_LABEL,\n\tUPLOADING_FILE_DESC,\n\tUPLOADER_HEADER_TEXT,\n\tHTML_EDITOR;\n//\tVALIDATION;\n}",
"public enum Event {\n\t\n\tthxPageIdChanged\n}",
"public interface FormComponentMapping {\n\t\n\tpublic abstract void setMapping(String mappingExpression);\n\t\n\tpublic abstract void removeMapping();\n}",
"public class Nodeset {\n\t\n\t/**\n\t * this path should be the same as the value of the bind nodeset attribute\n\t */\n\tprivate String path;\n\tprivate Element nodesetElement;\n\tprivate Nodeset parentBindNodeset;\n\tprivate FormDocument formDocument;\n\t\n\tpublic Nodeset(FormDocument formDocument) {\n\t\t\n\t\tthis.formDocument = formDocument;\n\t}\n\t\n\tpublic String getContent() {\n\t\treturn nodesetElement.getTextContent();\n\t}\n\t\n\tpublic void setContent(String content) {\n\t\tnodesetElement.setTextContent(content);\n\t}\n\t\n\tpublic String getMapping() {\n\t\t\n\t\treturn getNodesetElement().getAttribute(FormManagerUtil.mapping_att);\n\t}\n\t\n\tpublic void setMapping(String mapping) {\n\t\t\n\t\tif (mapping == null)\n\t\t\tgetNodesetElement().removeAttribute(FormManagerUtil.mapping_att);\n\t\telse\n\t\t\tgetNodesetElement().setAttribute(FormManagerUtil.mapping_att,\n\t\t\t mapping);\n\t}\n\t\n\tpublic String getPath() {\n\t\treturn path;\n\t}\n\t\n\tprotected void setPath(String path) {\n\t\tthis.path = path;\n\t}\n\t\n\t/**\n\t * @return xpath usable path to the model item. e.g. instance('data-instance')/mymodelitem\n\t */\n\tpublic String getXPathPath() {\n\t\t\n\t\treturn \"instance('data-instance')/\" + getPath();\n\t}\n\t\n\tpublic Element getNodesetElement() {\n\t\treturn nodesetElement;\n\t}\n\t\n\tprotected void setNodesetElement(Element nodesetElement) {\n\t\tthis.nodesetElement = nodesetElement;\n\t}\n\t\n\tpublic void remove() {\n\t\t\n\t\tgetNodesetElement().getParentNode().removeChild(getNodesetElement());\n\t\tpath = null;\n\t\t\n\t\tif (!StringUtil.isEmpty(getMapping())) {\n\t\t\t\n\t\t\tmappingSiblingChanged(getMapping());\n\t\t}\n\t}\n\t\n\tpublic void rename(String newName) {\n\t\t\n\t\tString path = getPath();\n\t\tElement nodesetElement = getNodesetElement();\n\t\t\n\t\tpath = path.replaceFirst(nodesetElement.getNodeName(), newName);\n\t\tnodesetElement = (Element) nodesetElement.getOwnerDocument()\n\t\t .renameNode(nodesetElement, nodesetElement.getNamespaceURI(),\n\t\t newName);\n\t\tsetNodesetElement(nodesetElement);\n\t\tsetPath(path);\n\t}\n\t\n\t/**\n\t * sets mapping for the nodeset, and also, might add the mapping updater for the component\n\t * element in case there are more than one component in the form with the same mapping\n\t * \n\t * @param formComponent\n\t * @param mappingExpression\n\t */\n\tpublic void setMapping(FormComponent formComponent, String mappingExpression) {\n\t\t\n\t\tif (StringUtil.isEmpty(mappingExpression)) {\n\t\t\t\n\t\t\tLogger.getLogger(getClass().getName()).log(\n\t\t\t Level.WARNING,\n\t\t\t \"Passed empty mapping expression, removing mapping. Component = \"\n\t\t\t + formComponent.getId() + \", form id=\"\n\t\t\t + formComponent.getFormDocument().getId());\n\t\t\tremoveMapping(formComponent);\n\t\t\t\n\t\t} else if (!mappingExpression.equals(getMapping())) {\n\t\t\t\n\t\t\tString previousMapping = getMapping();\n\t\t\tsetMapping(mappingExpression);\n\t\t\tFormComponentMapping mapping = formComponent\n\t\t\t .getFormComponentMapping(this);\n\t\t\tmapping.setMapping(mappingExpression);\n\t\t\tmappingSiblingChanged(previousMapping, mappingExpression);\n\t\t}\n\t}\n\t\n\tpublic void removeMapping(FormComponent formComponent) {\n\t\t\n\t\tFormComponentMapping mapping = formComponent\n\t\t .getFormComponentMapping(this);\n\t\t\n\t\tString previousMapping = getMapping();\n\t\tsetMapping(null);\n\t\tmapping.removeMapping();\n\t\t\n\t\tif (!StringUtil.isEmpty(previousMapping)) {\n\t\t\t\n\t\t\tmappingSiblingChanged(previousMapping);\n\t\t}\n\t}\n\t\n\tprivate void mappingSiblingChanged(String... relevantMappings) {\n\t\t\n\t\tgetFormDocument().mappingSiblingChanged(relevantMappings);\n\t}\n\t\n\tpublic Nodeset getParentBindNodeset() {\n\t\treturn parentBindNodeset;\n\t}\n\t\n\tpublic void setParentBindNodeset(Nodeset parentBindNodeset) {\n\t\tthis.parentBindNodeset = parentBindNodeset;\n\t}\n\t\n\tFormDocument getFormDocument() {\n\t\treturn formDocument;\n\t}\n\t\n\tpublic void reactToMappingSiblingChanged(FormComponent formComponent,\n\t String... relevantMappings) {\n\t\t\n\t\tif (isRelevantMapping(relevantMappings)) {\n\t\t\t\n\t\t\tFormComponentMapping mapping = formComponent\n\t\t\t .getFormComponentMapping(this);\n\t\t\tmapping.setMapping(getMapping());\n\t\t}\n\t}\n\t\n\tprivate boolean isRelevantMapping(String... mappings) {\n\t\t\n\t\tString myMapping = getMapping();\n\t\t\n\t\tif (!StringUtil.isEmpty(myMapping)) {\n\t\t\t\n\t\t\tfor (String mapping : mappings) {\n\t\t\t\t\n\t\t\t\tif (mapping.equals(myMapping))\n\t\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn false;\n\t}\n}"
] | import org.w3c.dom.Node;
import com.idega.xformsmanager.business.component.properties.PropertiesComponent;
import com.idega.xformsmanager.component.beans.ComponentDataBean;
import com.idega.xformsmanager.component.impl.FormComponentContainerImpl;
import com.idega.xformsmanager.component.properties.impl.ConstUpdateType;
import com.idega.xformsmanager.context.Event;
import com.idega.xformsmanager.xform.FormComponentMapping;
import com.idega.xformsmanager.xform.Nodeset; | package com.idega.xformsmanager.component;
/**
* this interface represents "internal to the xform document manager" form component representation.
* Shouldn't be used outside the xform document manager
*
* @author <a href="mailto:[email protected]">Vytautas Čivilis</a>
* @version $Revision: 1.8 $ Last modified: $Date: 2009/04/29 10:46:13 $ by $Author: civilis $
*/
public interface FormComponent {
/**
* loads xforms component from components template. This should be called BEFORE create().
*/
public abstract void loadFromTemplate();
/**
* adds templated component to the xform document. This method should be called AFTER
* loadFromTemplate(). The sufficient information should be already added to this component
* (like parent container)
*
* @see FormComponentContainerImpl addComponent method for example
*/
public abstract void create();
/**
* loads xforms component from the xform document. The sufficient information should be already
* added to this component (like parent container)
*
* @see FormComponentContainerImpl loadContainerComponents method for example
*/
public abstract void load();
/**
* specifies the component, before which this component should go in the xforms document
*
* @param component
* sibling component
*/
public abstract void setNextSibling(FormComponent component);
public abstract FormComponent getNextSibling();
/**
* moves this component to new location before next sibling specified
*
* @param nextSibling
*/
public abstract void setNextSiblingRerender(FormComponent nextSibling);
public abstract String getId();
public abstract void setId(String id);
public abstract void setType(String type);
public abstract String getType();
public abstract PropertiesComponent getProperties();
public abstract void remove();
public abstract void setParent(FormComponentContainer parent);
public abstract void setFormDocument(FormDocument form_document);
/**
* performs adding component to the confirmation page
*/
public abstract void addToConfirmationPage();
public abstract FormComponentContainer getParent();
public abstract void update(ConstUpdateType what);
public abstract void update(ConstUpdateType what, Object property);
public abstract ComponentDataBean getComponentDataBean();
public abstract void setComponentDataBean(
ComponentDataBean componentDataBean);
public abstract FormDocument getFormDocument();
| public abstract void dispatchEvent(Event event, Object eventContext, | 4 |
emop/EmopAndroid | src/com/emop/client/MainTabActivity.java | [
"public static final String TAG_EMOP = \"emop\";\r",
"public class ApiResult {\r\n\tpublic static final String ERR_JSON_PARSE = \"err_json_parse\";\r\n\tpublic static final String ERR_NETWORKING_UNKOWN = \"err_networking_unkown\";\r\n\t\r\n\tpublic JSONObject json = null;\r\n\tpublic boolean isOK = false;\r\n\tpublic String errorMsg = \"\";\r\n\tpublic String errorCode = \"\";\r\n\t\r\n\r\n\t\r\n\tpublic String getString(String key){\r\n\t\tString str = null;\r\n\t\tif(json != null){\r\n\t\t\ttry {\r\n\t\t\t\tJSONObject v = json;\r\n\t\t\t\tObject o = null;\r\n\t\t\t\tfor(String k: key.split(\"\\\\.\")){\r\n\t\t\t\t\tif(!v.has(k)) {\r\n\t\t\t\t\t\tv = null;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t\to = v.get(k);\r\n\t\t\t\t\tif(o instanceof JSONObject){\r\n\t\t\t\t\t\tv = (JSONObject)o;\r\n\t\t\t\t\t}else{\r\n\t\t\t\t\t\tstr = o.toString();\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t} catch (JSONException e) {\r\n\t\t\t\t//e.printStackTrace();\r\n\t\t\t\tLog.e(TAG_EMOP, \"JSONException error:\" + e.toString(), e);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn str;\r\n\t}\r\n\t\r\n\tpublic JSONObject getJSONObject(String key){\r\n\t\tJSONObject data = null;\r\n\t\tif(json != null){\r\n\t\t\ttry {\r\n\t\t\t\tJSONObject v = json;\r\n\t\t\t\tObject o = null;\r\n\t\t\t\tfor(String k: key.split(\"\\\\.\")){\r\n\t\t\t\t\tif(!v.has(k)) {\r\n\t\t\t\t\t\tv = null;\r\n\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t}\r\n\t\t\t\t\to = v.get(k);\r\n\t\t\t\t\tif(o instanceof JSONObject){\r\n\t\t\t\t\t\tv = (JSONObject)o;\r\n\t\t\t\t\t\tdata = v;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t} catch (JSONException e) {\r\n\t\t\t\t//e.printStackTrace();\r\n\t\t\t\tLog.e(TAG_EMOP, \"JSONException error:\" + e.toString(), e);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn data;\r\n\t}\t\r\n\t\r\n\tpublic String errorMsg(){\t\t\r\n\t\tif(this.errorMsg != null && this.errorMsg.trim().length() > 0){\r\n\t\t\treturn this.errorMsg.trim();\r\n\t\t}else{\r\n\t\t\treturn this.errorCode;\t\t\t\r\n\t\t}\r\n\t}\r\n\t\r\n\t//private String getString(String key, )\r\n}\r",
"public class FmeiClient {\r\n\t//public ImageCache cache = null;\r\n\t//需要长时间保存的图片,例如分类,热门。\r\n\tpublic ImageLoader appImgLoader = null;\r\n\t\r\n\t//临时图片加载,比如瀑布流图片。\r\n\tpublic ImageLoader tmpImgLoader = null;\r\n\t\r\n\tpublic String userId = null;\r\n\t//推荐应用下载的用户ID. 应用里面的链接都是包含这个用的PID\r\n\tpublic String trackUserId = null;\r\n\tpublic String trackPID = null;\r\n\t\r\n\t/**\r\n\t * 收藏夹ID.\r\n\t */\r\n\tpublic String favoriteId = null;\r\n\tpublic boolean isInited = false;\r\n\r\n\tprivate static FmeiClient ins = null;\r\n\tprivate TaodianApi api = null;\r\n\tprivate Context ctx = null;\r\n\tprivate AppConfig config = null;\r\n\t\r\n\t//private stai\r\n\t\r\n\tpublic FmeiClient(){\r\n\t\tthis.api = new TaodianApi();\r\n\t}\r\n\t\r\n\tpublic static FmeiClient getInstance(Context ctx){\r\n\t\treturn getInstance(ctx, false);\r\n\t}\r\n\t\r\n\tpublic static synchronized FmeiClient getInstance(Context ctx, boolean check_conn){\r\n\t\tif(ins == null){\r\n\t\t\tins = new FmeiClient();\r\n\t\t}\r\n\t\tif(ctx != null){\r\n\t\t\tins.ctx = ctx;\r\n\t\t\tins.api.ctx = ctx;\r\n\t\t}\r\n\t\tif(ins.appImgLoader == null && ctx != null){\r\n\t\t\tFile picDir = null;\r\n\t\t\tif(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){\r\n\t\t\t\ttry{\r\n\t\t\t\t\tpicDir = ctx.getExternalFilesDir(\"doudougou\");\r\n\t\t\t\t}catch(Throwable e){\r\n\t\t\t\t\tLog.w(TAG_EMOP, \"Error:\" + e.toString(), e);\r\n\t\t\t\t}\r\n\t\t\t\tif(picDir == null){\r\n\t\t\t\t\tpicDir = new File(Environment.getExternalStorageDirectory(), \"doudougou\");\r\n\t\t\t\t}\r\n\t\t\t\tLog.i(TAG_EMOP, \"App cache dir:\" + picDir.getAbsolutePath());\r\n\t\t\t\tif(!picDir.isDirectory()){\r\n\t\t\t\t\tif(!picDir.mkdirs()){\r\n\t\t\t\t\t\tpicDir = ctx.getCacheDir();\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tif(!picDir.canWrite()){\r\n\t\t\t\t\tpicDir = ctx.getCacheDir();\r\n\t\t\t\t}\r\n\t\t\t}else {\r\n\t\t\t\tLog.i(TAG_EMOP, \"The external storage is disabled.\");\t\t\t\t\r\n\t\t\t\tpicDir = ctx.getCacheDir();\t\t\t\t\r\n\t\t\t}\r\n\t\t\tLog.i(TAG_EMOP, \"App image dir:\" + picDir.getAbsolutePath());\r\n\t\t\tins.appImgLoader = new ImageLoader(ctx, picDir, \r\n\t\t\t\t\t0, 8); \r\n\t\t\tins.tmpImgLoader = ins.appImgLoader;\r\n\t\t}\r\n\t\t\r\n\t\tif(check_conn){\r\n\t\t\tins.check_networking(ctx);\r\n\t\t}\r\n\t\treturn ins;\r\n\t}\r\n\t\r\n\tpublic boolean isLogined(){\r\n\t\treturn this.userId != null && this.userId.length() > 0 && Integer.parseInt(this.userId) > 0;\r\n\t}\r\n\t\r\n\t/**\r\n\t * 链接一下taodian API看看网络是否正常。\r\n\t * @param ctx\r\n\t * @return\r\n\t */\r\n\tpublic ApiResult check_networking(Context ctx){\r\n\t\treturn this.api.connect(ctx);\r\n\t}\r\n\t\r\n\t/*\r\n\t * 取得专题列表.\r\n\t */\r\n\tpublic Cursor getTopicList(ContentResolver contentResolver){\r\n\t\tCursor c = contentResolver.query(Schema.TOPIC_LIST, \r\n\t\t\t\tnew String[] {BaseColumns._ID, Topic.TITLE, Topic.ITEM_COUNT,\r\n\t\t\t\tTopic.DESC, \r\n\t\t\t\tTopic.FRONT_PIC, \r\n\t\t\t\tTopic.UPDATE_TIME,\r\n\t\t\t\tTopic.VIEW_ORDER\r\n\t\t}, null, null, null);\r\n\t\treturn c;\r\n\t}\r\n\t\r\n\t/*\r\n\t * 取得分类列表.\r\n\t */\r\n\tpublic Cursor getCateList(ContentResolver contentResolver){\r\n\t\tCursor c = contentResolver.query(Schema.CATE_LIST, \r\n\t\t\t\tnew String[] {BaseColumns._ID, Topic.TITLE, Topic.ITEM_COUNT,\r\n\t\t\t\tTopic.DESC, \r\n\t\t\t\tTopic.FRONT_PIC, \r\n\t\t\t\tTopic.UPDATE_TIME\r\n\t\t}, null, null, null);\r\n\t\treturn c;\r\n\t}\r\n\t\r\n\t/*\r\n\t * 取得热门分类列表.\r\n\t */\r\n\tpublic Cursor getHotCateList(ContentResolver contentResolver){\r\n\t\tCursor c = contentResolver.query(Schema.HOT_CATE_LIST, \r\n\t\t\t\tnew String[] {BaseColumns._ID, Topic.TITLE, Topic.ITEM_COUNT,\r\n\t\t\t\tTopic.DESC, \r\n\t\t\t\tTopic.FRONT_PIC, \r\n\t\t\t\tTopic.UPDATE_TIME\r\n\t\t}, null, null, null);\r\n\t\treturn c;\r\n\t}\t\r\n\r\n\t/*\r\n\t * 取得专题列表.\r\n\t */\r\n\tpublic Cursor getItemList(ContentResolver contentResolver, Uri uri){\r\n\t\tLog.d(com.emop.client.Constants.TAG_EMOP, \"on getItemList:\" + uri.toString());\r\n\t\t\r\n\t\tCursor c = contentResolver.query(uri, \r\n\t\t\t\tnew String[] {BaseColumns._ID, Item.SHORT_KEY, Item.PIC_URL,\r\n\t\t\t\tItem.ITEM_CONTENT_TYPE, \r\n\t\t\t\tItem.UPDATE_TIME, Item.WEIBO_ID,\r\n\t\t\t\tItem.PRICE,\r\n\t\t\t\tItem.MESSAGE,\r\n\t\t\t\tItem.RECT_RATE\r\n\t\t}, null, null, null);\r\n\t\t\r\n\t\treturn c;\r\n\t}\r\n\t\r\n\t/**\r\n\t * 通过uri地址更新内容列表。\r\n\t * @param contentResolver\r\n\t * @param uri\r\n\t * @return\r\n\t */\r\n\tpublic ApiResult refreshDataByUri(ContentResolver contentResolver, Uri uri){\r\n\t\treturn refreshDataByUri(contentResolver, uri, TaodianApi.STATUS_NORMAL);\r\n\t}\r\n\t\r\n\t/**\r\n\t * 通过uri地址更新内容列表。\r\n\t * @param contentResolver\r\n\t * @param uri\r\n\t * @param async -- 是否异步返回结果。 如果为true数据在后台线程保存到数据库。网络返回后\r\n\t * @return\r\n\t */\t\r\n\tpublic ApiResult refreshDataByUri(ContentResolver contentResolver, Uri uri, int status){\r\n\t\treturn refreshDataByUri(contentResolver, uri, status, false);\r\n\t}\t\r\n\t\r\n\tpublic ApiResult refreshDataByUri(ContentResolver contentResolver, Uri uri, int status, boolean sync){\r\n\t\tLog.e(Constants.TAG_EMOP, \"refresh uri:\" + uri.toString());\r\n\t\tApiResult r = null;\r\n switch (Schema.FmeiUriMatcher.match(uri)) {\r\n \tcase Schema.TYPE_CATE_ITEM_LIST:\r\n \tcase Schema.TYPE_HOT_ITEM_LIST:\r\n \tcase Schema.TYPE_TOPIC_ITEM_LIST:\r\n \t\tr = refreshTopicItemList(contentResolver, uri, sync, null);\r\n \t\tbreak;\r\n \tcase Schema.TYPE_TOPICS:\r\n \t\tr = this.refreshTopicList(contentResolver, status, \"\");\r\n \t\tbreak;\r\n \tcase Schema.TYPE_CATES:\r\n \t\tr = this.refreshCateList(contentResolver, status);\r\n \t\tbreak;\r\n \tcase Schema.TYPE_HOTS:\r\n \t\tr = this.refreshHotCatList(contentResolver, status);\r\n \tcase Schema.TYPE_ACT_ITEM_LIST:\r\n \t\tr = this.refreshActivityItemList(contentResolver);\r\n \tcase Schema.TYPE_MYFAV_ITEM_LIST:\r\n \t\tr = this.refreshMyFavoriteItemList(contentResolver);\r\n }\r\n\t\t\r\n\t\treturn r;\r\n\t}\r\n\t\r\n\t/**\r\n\t * \r\n\t * @param contentResolver\r\n\t * @param uri\r\n\t */\r\n\tpublic void refreshUri(ContentResolver contentResolver, Uri uri){\r\n\t\t\r\n\t}\r\n\t\r\n\tpublic ApiResult refreshTopicList(ContentResolver contentResolver){\r\n\t\treturn refreshTopicList(contentResolver, TaodianApi.STATUS_NORMAL, \"\");\r\n\t}\r\n\t/**\r\n\t * 刷新专题列表。\r\n\t * @param contentResolver\r\n\t */\r\n\tpublic ApiResult refreshTopicList(ContentResolver contentResolver, int status, String noCache){\r\n\t\tLog.e(Constants.TAG_EMOP, \"refreshList....\");\r\n\t\tApiResult r = this.api.getTopicList(10, status, noCache);\r\n\t\tif(r.isOK){\r\n\t\t\tJSONObject json = null;\r\n\t\t\ttry {\r\n\t\t\t\tjson = r.json.getJSONObject(\"data\");\r\n\t\t\t\tJSONArray jarray = json.getJSONArray(\"items\");\r\n\t\t\t\tfor(int i = 0; i < jarray.length(); i++){\r\n\t\t\t\t\tcontentResolver.update(Schema.TOPIC_LIST, \r\n\t\t\t\t\t\t\tTopic.convertJson(jarray.getJSONObject(i)), \r\n\t\t\t\t\t\t\tnull, null);\r\n\t\t\t\t}\r\n\t\t\t\t//contentResolver.notifyChange(Schema.TOPIC_LIST, null);\r\n\t\t\t} catch (JSONException e) {\r\n\t\t\t}\r\n\t\t}else {\r\n\t\t\tLog.d(Constants.TAG_EMOP, \"Failed to refresh list:\" + r.errorMsg());\r\n\t\t}\r\n\t\treturn r;\r\n\t}\r\n\t\r\n\tpublic ApiResult refreshCateList(ContentResolver contentResolver, int status){\r\n\t\tLog.e(Constants.TAG_EMOP, \"refresh cate List....\");\r\n\t\tApiResult r = this.api.getCateList(10, status);\r\n\t\tif(r.isOK){\r\n\t\t\tJSONObject json = null;\r\n\t\t\ttry {\r\n\t\t\t\tjson = r.json.getJSONObject(\"data\");\r\n\t\t\t\tJSONArray jarray = json.getJSONArray(\"items\");\r\n\t\t\t\tfor(int i = 0; i < jarray.length(); i++){\r\n\t\t\t\t\tcontentResolver.update(Schema.CATE_LIST, \r\n\t\t\t\t\t\t\tTopic.convertJson(jarray.getJSONObject(i)), \r\n\t\t\t\t\t\t\tnull, null);\r\n\t\t\t\t}\r\n\t\t\t\tcontentResolver.notifyChange(Schema.CATE_LIST, null);\r\n\t\t\t} catch (JSONException e) {\r\n\t\t\t}\r\n\t\t}else {\r\n\t\t\tLog.d(Constants.TAG_EMOP, \"Failed to refresh list:\" + r.errorMsg());\r\n\t\t}\r\n\t\treturn r;\r\n\t}\r\n\t\r\n\tpublic ApiResult refreshHotCatList(ContentResolver contentResolver, int status){\r\n\t\tLog.e(Constants.TAG_EMOP, \"refresh hot cate List....\");\r\n\t\tApiResult r = this.api.getHotCateList(10, status);\r\n\t\tif(r.isOK){\r\n\t\t\tJSONObject json = null;\r\n\t\t\ttry {\r\n\t\t\t\tjson = r.json.getJSONObject(\"data\");\r\n\t\t\t\tJSONArray jarray = json.getJSONArray(\"items\");\r\n\t\t\t\tfor(int i = 0; i < jarray.length(); i++){\r\n\t\t\t\t\tcontentResolver.update(Schema.HOT_CATE_LIST, \r\n\t\t\t\t\t\t\tTopic.convertJson(jarray.getJSONObject(i)), \r\n\t\t\t\t\t\t\tnull, null);\r\n\t\t\t\t}\r\n\t\t\t\tcontentResolver.notifyChange(Schema.CATE_LIST, null);\r\n\t\t\t} catch (JSONException e) {\r\n\t\t\t}\r\n\t\t}else {\r\n\t\t\tLog.d(Constants.TAG_EMOP, \"Failed to refresh list:\" + r.errorMsg());\r\n\t\t}\r\n\t\treturn r;\r\n\t}\r\n\t\r\n\tpublic ApiResult refreshActList(ContentResolver contentResolver){\r\n\t\tLog.e(Constants.TAG_EMOP, \"refresh act topic List....\");\r\n\t\tApiResult r = this.api.getActList(1, TaodianApi.STATUS_NORMAL);\r\n\t\tif(r.isOK){\r\n\t\t\tJSONObject json = null;\r\n\t\t\ttry {\r\n\t\t\t\tjson = r.json.getJSONObject(\"data\");\r\n\t\t\t\tJSONArray jarray = json.getJSONArray(\"items\");\r\n\t\t\t\tfor(int i = 0; i < jarray.length(); i++){\r\n\t\t\t\t\tcontentResolver.update(Schema.ACTIVITY_LIST, \r\n\t\t\t\t\t\t\tTopic.convertJson(jarray.getJSONObject(i)), \r\n\t\t\t\t\t\t\tnull, null);\r\n\t\t\t\t}\r\n\t\t\t} catch (JSONException e) {\r\n\t\t\t}\r\n\t\t}else {\r\n\t\t\tLog.d(Constants.TAG_EMOP, \"Failed to refresh list:\" + r.errorMsg());\r\n\t\t}\r\n\t\treturn r;\r\n\t}\t\r\n\t\r\n\t/**\r\n\t * 刷新专题图片列表。\r\n\t * @param contentResolver\r\n\t */\r\n\tpublic ApiResult refreshTopicItemList(ContentResolver contentResolver, int topic_id){\r\n\t\tUri topicList = Uri.parse(\"content://\" + Schema.AUTHORITY + \"/topic/\" + topic_id + \"/list\");\r\n\t\t\r\n\t\treturn this.refreshTopicItemList(contentResolver, topicList);\r\n\t}\r\n\t\r\n\t/**\r\n\t * 刷新活动图片列表。\r\n\t * @param contentResolver\r\n\t */\r\n\tpublic ApiResult refreshActivityItemList(ContentResolver contentResolver){\r\n\t\tApiResult r = null;\r\n\t\tint topicId = getActivityTopicId(contentResolver);\r\n\t\tUri topicList = Uri.parse(\"content://\" + Schema.AUTHORITY + \"/act/\" + topicId + \"/list\");\t\t\r\n\t\tr = this.refreshTopicItemList(contentResolver, topicList);\r\n\t\treturn r;\r\n\t}\t\r\n\t\r\n\t/**\r\n\t * 刷新我的收藏活动图片列表。\r\n\t * @param contentResolver\r\n\t */\r\n\tpublic ApiResult refreshMyFavoriteItemList(ContentResolver contentResolver){\r\n\t\tApiResult r = null;\r\n\t\tif(this.isLogined()){\r\n\t\t\tString fid = this.getFavoriteId();\r\n\t\t\tUri topicList = Uri.parse(\"content://\" + Schema.AUTHORITY + \"/myfav/\" + fid + \"/list\");\t\r\n\t\t\tLog.e(Constants.TAG_EMOP, \"refresh myfav item list:\" + fid);\r\n\t\t\tr = this.api.getMyFavoriteItemList(fid, this.userId);\r\n\t\t\tif(r.isOK){\r\n\t\t\t\tJSONObject json = null;\r\n\t\t\t\ttry {\r\n\t\t\t\t\tjson = r.json.getJSONObject(\"data\");\r\n\t\t\t\t\tJSONArray jarray = json.getJSONArray(\"items\");\r\n\t\t\t\t\tfor(int i = 0; i < jarray.length(); i++){\r\n\t\t\t\t\t\tcontentResolver.update(topicList, \r\n\t\t\t\t\t\t\t\tItem.convertJson(jarray.getJSONObject(i)), \r\n\t\t\t\t\t\t\t\tnull, null);\r\n\t\t\t\t\t}\r\n\t\t\t\t} catch (JSONException e) {\r\n\t\t\t\t}\r\n\t\t\t}else {\r\n\t\t\t\tLog.d(Constants.TAG_EMOP, \"Failed to refresh list:\" + r.errorMsg());\r\n\t\t\t}\t\t\r\n\t\t}\r\n\t\treturn r;\r\n\t}\t\t\r\n\t\r\n\t/**\r\n\t * 链接活动页,也是一个特殊的专题活动。取到专题的ID.\r\n\t * @return\r\n\t */\r\n\tpublic int getActivityTopicId(ContentResolver contentResolver){\r\n\t\tint topicId = 0;\r\n\t\tCursor c = contentResolver.query(Schema.ACTIVITY_LIST, \r\n\t\t\t\tnew String[] {BaseColumns._ID }, null, null, null);\r\n\t\tif(c.getCount() == 0){\r\n\t\t\tthis.refreshActList(contentResolver);\r\n\t\t\tif(c != null)c.close();\r\n\t\t\tc = contentResolver.query(Schema.ACTIVITY_LIST, \r\n\t\t\t\t\tnew String[] {BaseColumns._ID }, null, null, null);\t\t\t\r\n\t\t}\r\n\t\tif(c.getCount() > 0){\r\n\t\t\tc.moveToFirst();\r\n\t\t\tint topic = c.getColumnIndex(BaseColumns._ID);\r\n\t\t\ttopicId = c.getInt(topic);\t\t\t\r\n\t\t}\r\n\t\tif(c != null)c.close();\r\n\t\treturn topicId;\r\n\t\t\r\n\t}\r\n\t\r\n\tpublic ApiResult refreshTopicItemList(ContentResolver contentResolver, Uri topicList){\r\n\t\treturn refreshTopicItemList(contentResolver, topicList, false, null);\r\n\t}\r\n\tpublic ApiResult refreshTopicItemList(final ContentResolver contentResolver, final Uri topicList, boolean sync, String force){\r\n\t\tint topic_id = Integer.parseInt(topicList.getPathSegments().get(1)); // (int) ContentUris.parseId(uri);\r\n\t\tString cate = topicList.getPathSegments().get(0);\r\n\t\tLog.e(Constants.TAG_EMOP, \"refresh item list:\" + topic_id);\r\n\t\tString pageSize = topicList.getQueryParameter(\"pageSize\");\r\n\t\tString pageNo = topicList.getQueryParameter(\"pageNo\");\r\n\t\tString noCache = topicList.getQueryParameter(\"no_cache\");\r\n\t\tif(force != null && force.equals(\"y\")){\r\n\t\t\tnoCache = \"y\";\r\n\t\t}\r\n\t\t\r\n\t\tint size = 100;\r\n\t\ttry{\r\n\t\t\tsize = Integer.parseInt(pageSize);\r\n\t\t}catch(Throwable e){}\r\n\t\tfinal ApiResult r;\r\n\t\tif(cate.equals(\"act\")){\r\n\t\t\tr = this.api.getTopicItemList(topic_id, size, pageNo);\r\n\t\t}else if(cate.equals(\"shop\")){\r\n\t\t\tr = this.api.getShopItemList(topic_id, size, pageNo, trackUserId, noCache);\r\n\t\t}else {\r\n\t\t\tr = this.api.getTopicPidItemList(topic_id, size, pageNo, trackUserId, noCache);\r\n\t\t}\r\n\t\tif(r != null && r.isOK){\r\n\t\t\tRunnable task = new Runnable(){\r\n\t\t\t\t@Override\r\n\t\t\t\tpublic void run() {\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\tJSONObject json = r.json.getJSONObject(\"data\");\r\n\t\t\t\t\t\tJSONArray jarray = json.getJSONArray(\"items\");\r\n\t\t\t\t\t\tfor(int i = 0; i < jarray.length(); i++){\r\n\t\t\t\t\t\t\tcontentResolver.update(topicList, \r\n\t\t\t\t\t\t\t\t\tItem.convertJson(jarray.getJSONObject(i)), \r\n\t\t\t\t\t\t\t\t\tnull, null);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tcontentResolver.notifyChange(topicList, null);\r\n\t\t\t\t\t} catch (JSONException e) {\r\n\t\t\t\t\t\te.printStackTrace();\r\n\t\t\t\t\t}\t\t\t\t\t\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t};\r\n\t\t\t\r\n\t\t\tif(sync){\r\n\t\t\t\tnew Thread(task).start();\r\n\t\t\t}else {\r\n\t\t\t\ttask.run();\r\n\t\t\t}\r\n\t\t}else {\r\n\t\t\tLog.d(Constants.TAG_EMOP, \"Failed to refresh list:\" + r.errorMsg());\r\n\t\t}\r\n\t\treturn r;\r\n\t}\r\n\t\r\n\t/**\r\n\t * 通过网络查询当前应用的最新版本。\r\n\t * @return\r\n\t */\r\n\tpublic ApiResult checkUpgradeVersion(){\r\n\t\tApiResult r = this.api.call(\"cms_app_version_check\", null);\t\t\r\n\t\t//PackageManager packageManager = ctx.getPackageManager();\r\n\t\t//PackageInfo packInfo packageManager.getp\t\t\r\n\t\treturn r;\r\n\t}\r\n\r\n\tpublic ApiResult addFavorite(String weiboId, String desc, String picUrl, String numId, String shopId, String short_url_key){\r\n\t\treturn addFavorite(weiboId, desc, picUrl, numId, shopId, short_url_key, \"taoke\");\r\n\t}\r\n\t\r\n\tpublic ApiResult addFavorite(String weiboId, String desc, String picUrl, String numId, String shopId, String short_url_key, String contentType){\r\n\t\tLog.d(TAG_EMOP, \"add fav, weiboId:\" + weiboId + \", numId:\" + numId + \", shopId:\" + shopId + \", picUrl:\" + picUrl);\r\n\t\tApiResult r = null;\r\n\t\tString fid = getFavoriteId();\r\n\t\tMap<String, Object> param = new HashMap<String, Object>();\r\n\t\tparam.put(\"user_id\", userId);\r\n\t\tparam.put(\"topic_id\", fid);\r\n\t\tparam.put(\"item_id\", weiboId);\r\n\t\tparam.put(\"pic_url\", picUrl);\r\n\t\tparam.put(\"content_type\", contentType);\r\n\t\tparam.put(\"num_iid\", numId);\r\n\t\tparam.put(\"shop_id\", shopId);\r\n\t\tparam.put(\"short_url_key\", short_url_key);\r\n\t\t\r\n\t\tparam.put(\"item_text\", desc);\r\n\t\tr = api.call(\"tuji_topic_add_item\", param);\r\n\t\treturn r;\r\n\t}\r\n\t\r\n\tpublic ApiResult removeFavorite(String weiboId){\r\n\t\tLog.d(TAG_EMOP, \"remove fav, weiboId:\" + weiboId);\r\n\t\tApiResult r = null;\r\n\t\tString fid = getFavoriteId();\r\n\t\tMap<String, Object> param = new HashMap<String, Object>();\r\n\t\tparam.put(\"user_id\", userId);\r\n\t\tparam.put(\"topic_id\", fid);\r\n\t\tparam.put(\"item_id\", weiboId);\r\n\r\n\t\tr = api.call(\"tuji_topic_remove_items\", param);\r\n\t\treturn r;\r\n\t}\r\n\t\r\n\t\r\n\t/**\r\n\t * 加载应用配置信息,例如:sina key,什么的。\r\n\t * @return\r\n\t */\r\n\tpublic AppConfig config(){\r\n\t\tif(config == null){\r\n\t\t\tconfig = new AppConfig();\r\n\t\t\tApiResult r = api.call(\"cms_app_config_info\", null);\r\n\t\t\tif(r != null && r.isOK){\r\n\t\t\t\tconfig.json = r.getJSONObject(\"data\");\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn config;\r\n\t}\r\n\t\r\n\t/**\r\n\t * 绑定外部登录用户信息,到美觅网系统。\r\n\t * @param source\r\n\t * @param userId\r\n\t * @param token\r\n\t * @return\r\n\t */\r\n\tpublic ApiResult bindUserInfo(String source, String userId, String token){\r\n\t\tMap<String, Object> param = new HashMap<String, Object>();\r\n\t\tparam.put(\"source\", source);\r\n\t\tparam.put(\"ref_id\", userId);\r\n\t\tparam.put(\"access_token\", token);\r\n\t\tif(this.userId != null){\r\n\t\t\tparam.put(\"user_id\", this.userId);\r\n\t\t}\r\n\t\t\r\n\t\tApiResult r = api.call(\"user_bind_login\", param);\r\n\t\t\r\n\t\treturn r;\r\n\t}\r\n\t\r\n\tpublic ApiResult registerUser(Map<String, Object> param){\t\r\n\t\t/**\r\n\t\t * 有user_id是通过,第三方帐号绑定过来。已经生成了user_id.\r\n\t\t * 没有user_id是在应用里面,直接注册的。\r\n\t\t */\r\n\t\tApiResult r = null;\r\n\t\tObject user_id = param.get(\"user_id\");\r\n\t\tif(user_id != null && user_id.toString().length() > 0){\r\n\t\t\tr = api.call(\"user_update_info\", param);\r\n\t\t}else {\r\n\t\t\tr = api.call(\"user_register_new\", param);\r\n\t\t}\r\n\t\t\r\n\t\treturn r;\r\n\t}\r\n\t\r\n\tpublic ApiResult login(String email, String password){\t\r\n\t\tMap<String, Object> param = new HashMap<String, Object>();\r\n\t\tparam.put(\"email\", email);\r\n\t\tparam.put(\"password\", password);\r\n\t\t\r\n\t\tApiResult r = api.call(\"user_login\", param);\r\n\t\t\r\n\t\treturn r;\r\n\t}\r\n\t\r\n\tpublic void saveLoginUser(Activity ctx, String userId){\r\n\t\tthis.userId = userId;\r\n\t\tSharedPreferences settings = ctx.getSharedPreferences(Constants.PREFS_NAME, 0);\r\n \tSharedPreferences.Editor editor = settings.edit();\r\n \teditor.putString(Constants.PREFS_OAUTH_ID, userId);\r\n \teditor.commit();\r\n \tLog.d(TAG_EMOP, \"save user:\" + userId);\r\n\t}\r\n\r\n\tpublic void saveRefUser(Activity ctx, String source, String userId, String nick){\r\n\t\t//this.userId = userId;\r\n\t\tSharedPreferences settings = ctx.getSharedPreferences(Constants.PREFS_NAME, 0);\r\n \tSharedPreferences.Editor editor = settings.edit();\r\n \tif(source.equals(Constants.AUTH_REF_SINA)){\r\n \t\teditor.putString(Constants.PREFS_SINA_UID, userId);\r\n \teditor.putString(Constants.PREFS_SINA_NICK, nick);\r\n \t}else if(source.equals(Constants.AUTH_REF_TAOBAO)){\r\n \t\teditor.putString(Constants.PREFS_TAOBAO_UID, userId);\r\n \teditor.putString(Constants.PREFS_TAOBAO_NICK, nick); \t\t\r\n \t}else if(source.equals(Constants.AUTH_REF_QQ)){\r\n \t\teditor.putString(Constants.PREFS_QQ_UID, userId);\r\n \teditor.putString(Constants.PREFS_QQ_NICK, nick); \t\t\r\n \t}\r\n \teditor.commit();\r\n \tLog.d(TAG_EMOP, \"save user:\" + userId);\r\n\t}\r\n\r\n\tpublic void removeRefUser(Activity ctx, String source){\r\n\t\t//this.userId = userId;\r\n\t\tSharedPreferences settings = ctx.getSharedPreferences(Constants.PREFS_NAME, 0);\r\n \tSharedPreferences.Editor editor = settings.edit();\r\n \tif(source.equals(Constants.AUTH_REF_SINA)){\r\n \t\teditor.remove(Constants.PREFS_SINA_UID);\r\n \t\teditor.remove(Constants.PREFS_SINA_NICK);\r\n \t\teditor.remove(Constants.PREFS_SINA_ACCESS_TOKEN);\r\n \t}else if(source.equals(Constants.AUTH_REF_TAOBAO)){\r\n \t\teditor.remove(Constants.PREFS_TAOBAO_UID);\r\n \t\teditor.remove(Constants.PREFS_TAOBAO_NICK);\r\n \t}else if(source.equals(Constants.AUTH_REF_QQ)){\r\n \t\teditor.remove(Constants.PREFS_QQ_UID);\r\n \t\teditor.remove(Constants.PREFS_QQ_UID);\r\n \t}\r\n \teditor.commit();\r\n \tString sina = settings.getString(Constants.PREFS_SINA_UID, \"\");\r\n \tString taobao = settings.getString(Constants.PREFS_TAOBAO_UID, \"\");\r\n \tString qq = settings.getString(Constants.PREFS_QQ_UID, \"\");\r\n \t\r\n \tif((sina == null || sina.trim().length() == 0) &&\r\n \t (taobao == null || taobao.trim().length() == 0) &&\r\n \t (qq == null || qq.trim().length() == 0)\r\n \t){\r\n \t\tlogout(ctx);\r\n \t} \t\r\n \tLog.d(TAG_EMOP, \"save user:\" + userId);\r\n\t}\r\n\t\r\n\t\r\n\tpublic void logout(Activity ctx){\r\n\t\tthis.userId = null;\r\n\t\tSharedPreferences settings = ctx.getSharedPreferences(Constants.PREFS_NAME, 0);\r\n \tSharedPreferences.Editor editor = settings.edit();\r\n \teditor.putString(Constants.PREFS_OAUTH_ID, \"0\");\r\n \teditor.commit();\r\n \tLog.d(TAG_EMOP, \"logout:\" + userId);\t\t\r\n\t}\r\n\t\r\n\t/**\r\n\t * 我的收藏夹Id.\r\n\t * @return\r\n\t */\r\n\tpublic String getFavoriteId(){\r\n\t\tif((this.favoriteId == null || this.favoriteId.length() == 0) &&\r\n\t\t\t\tthis.isLogined()){\r\n\t\t\tMap<String, Object> param = new HashMap<String, Object>();\r\n\t\t\tparam.put(\"user_id\", userId);\r\n\t\t\tparam.put(\"cate\", 1);\r\n\t\t\tparam.put(\"topic_name\", \"收藏夹\");\r\n\t\t\tparam.put(\"item_head_count\", 0);\r\n\t\t\tparam.put(\"status\", TaodianApi.STATUS_NORMAL);\r\n\t\t\t\r\n\t\t\tApiResult r = api.call(\"tuji_user_topic_list\", param);\r\n\t\t\tif(r.isOK){\r\n\t\t\t\t int count = Integer.parseInt(r.getString(\"data.item_count\").toString());\r\n\t\t\t\t if(count > 0){\r\n\t\t\t\t\t JSONObject obj = r.getJSONObject(\"data\");\r\n\t\t\t\t\t JSONArray items;\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\titems = obj.getJSONArray(\"items\");\r\n\t\t\t\t\t\tthis.favoriteId = items.getJSONObject(0).getString(\"id\");\r\n\t\t\t\t\t} catch (JSONException e) {\r\n\t\t\t\t\t\tLog.e(TAG_EMOP, \"Get favoriate ID error:\" + e.toString(), e);\r\n\t\t\t\t\t}\r\n\t\t\t\t }\r\n\t\t\t}\r\n\t\t\tif(this.favoriteId == null || this.favoriteId.length() == 0){\r\n\t\t\t\tr = api.call(\"tuji_create_topic\", param);\r\n\t\t\t\tif(r.isOK){\r\n\t\t\t\t\tthis.favoriteId = r.getString(\"data.topic_id\");\r\n\t\t\t\t}\t\t\t\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this.favoriteId;\r\n\t}\r\n\t\r\n\t/**\r\n\t * 检查用户PID是否合法。先跳过不检查。\r\n\t * @param id\r\n\t * @return\r\n\t */\r\n\tpublic ApiResult checkTrackId(String id){\r\n\t\tApiResult r = new ApiResult();\r\n\t\tr.isOK = true;\r\n\t\treturn r;\r\n\t}\r\n\t\r\n\tpublic void cleanExpiredData(ContentResolver contentResolver){\r\n\t\tLog.d(Constants.TAG_EMOP, \"cleanExpiredData....\");\r\n\t\tcontentResolver.delete(Schema.TOPIC_LIST, Item.LOCAL_UPDATE_TIME + \" < ?\", \r\n\t\t\t\tnew String[]{(System.currentTimeMillis() - 1000 * 60 * 60 * 24 * 15) + \"\"});\r\n\t\tcontentResolver.delete(Schema.ITME_LIST, Item.LOCAL_UPDATE_TIME + \" < ?\", \r\n\t\t\t\tnew String[]{(System.currentTimeMillis() - 1000 * 60 * 60 * 24 * 5) + \"\"});\t\r\n\t\t\r\n\t\tcontentResolver.delete(Schema.REBATE_LIST, Item.LOCAL_UPDATE_TIME + \" < ?\", \r\n\t\t\t\tnew String[]{(System.currentTimeMillis() - 1000 * 60 * 60 * 24 * 15) + \"\"});\r\n\t\tcontentResolver.delete(Schema.SHOP_LIST, Item.LOCAL_UPDATE_TIME + \" < ?\", \r\n\t\t\t\tnew String[]{(System.currentTimeMillis() - 1000 * 60 * 60 * 24 * 15) + \"\"});\t\t\r\n\t}\r\n\t\r\n\t/**\r\n\t * 更加ID加载单条内容。主要用在,应用从外部启动后。直接进入详情页面。\r\n\t * @param uuid\r\n\t * @return\r\n\t */\r\n\tpublic ApiResult getWeiboInfo(String uuid){\t\t\r\n\t\tMap<String, Object> param = new HashMap<String, Object>();\r\n\t\tparam.put(\"uuid\", uuid);\r\n\t\tparam.put(\"user_id\", userId);\r\n\t\t\r\n\t\tApiResult r = api.call(\"cms_get_uuid_content\", param);\t\t\r\n\r\n\t\treturn r;\r\n\t}\r\n\r\n\tpublic ApiResult getTrackPid(){\t\t\r\n\t\tMap<String, Object> param = new HashMap<String, Object>();\r\n\t\tparam.put(\"uid\", this.trackUserId);\r\n\t\tApiResult r = api.call(\"emop_user_pid\", param);\t\t\r\n\t\tthis.trackPID = r.getString(\"data.pid\");\r\n\t\t\r\n\t\treturn r;\r\n\t}\r\n\t\r\n\t/**\r\n\t * @param uuid\r\n\t * @return\r\n\t */\r\n\tpublic ApiResult updateTrackId(){\r\n\t\tMap<String, Object> param = new HashMap<String, Object>();\r\n\t\tparam.put(\"user_id\", userId);\r\n\t\tparam.put(\"track_user_id\", trackUserId);\r\n\t\t\r\n\t\tApiResult r = api.call(\"user_update_track_id\", param);\t\r\n\t\tif(r != null && r.isOK){\r\n\t\t\tString tid = r.getString(\"data.track_user_id\");\r\n\t\t\tif(tid != null && tid.trim().length() > 0){\r\n\t\t\t\ttrackUserId = tid;\r\n\t\t\t\tSharedPreferences settings = ctx.getSharedPreferences(Constants.PREFS_NAME, 0);\r\n\t\t \tSharedPreferences.Editor editor = settings.edit();\r\n\t\t \teditor.putString(Constants.PREFS_TRACK_ID, tid);\r\n\t\t \teditor.commit();\r\n\t\t\t}\r\n\t\t\tLog.d(\"xx\", \"update task as:\" + tid);\r\n\t\t}\r\n\t\treturn r;\r\n\t}\r\n\t\r\n\t/**\r\n\t * 1. 读取sd卡\r\n\t * 2. 读取应用meta\r\n\t */\r\n\tpublic void updateLocalTrackId(){\r\n\t\tboolean writeSetting = false;\r\n\t\tSharedPreferences settings = ctx.getSharedPreferences(Constants.PREFS_NAME, 0);\r\n\t\ttrackUserId = settings.getString(Constants.PREFS_TRACK_ID, null);\r\n\t\tif(trackUserId == null || trackUserId.trim().equals(\"\")){\r\n\t\t\twriteSetting = true;\r\n\t\t\ttrackUserId = readTrackIdFromSD();\r\n\t\t}\r\n\t\tif(trackUserId == null || trackUserId.trim().equals(\"\")){\r\n\t\t\ttrackUserId = getMetaDataValue(\"emop_track_id\");\r\n\t\t\t//测试模式下,track id还没有替换时。默认是EMOP_USER\r\n\t\t\tif(trackUserId != null && trackUserId.equals(\"EMOP_USER\")){\r\n\t\t\t\ttrackUserId = \"11\";\r\n\t\t\t}\r\n\t\t\tLog.d(TAG_EMOP, \"read track from meta:\" + trackUserId);\r\n\t\t}\r\n\t\tif(trackUserId != null && trackUserId.trim().length() > 0){\r\n\t\t\tif(writeSetting){\r\n\t\t\t\tsaveSettings(Constants.PREFS_TRACK_ID, trackUserId);\r\n\t\t\t}\r\n\t\t\tWriteTrackIdToSD(trackUserId);\r\n\t\t}\r\n\t}\r\n\r\n\tprivate void WriteTrackIdToSD(String tid){\r\n\t\tFile track = null;\r\n\t\tString pid = null;\r\n\t\tOutputStream os = null;\r\n\t\ttry{\r\n\t\t\tif(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){\r\n\t\t\t\ttrack = new File(Environment.getExternalStorageDirectory(), \"taodianhuo.pid\");\r\n\t\t\t}else {\r\n\t\t\t\ttrack = new File(ctx.getExternalFilesDir(null), \"taodianhuo.pid\");\r\n\t\t\t}\r\n\t\t\tLog.d(TAG_EMOP, \"write track user pid:'\" + tid + \"' to:\" + track.getAbsolutePath());\r\n\t\t\tos = new FileOutputStream(track);\r\n\t\t\tif(os != null){\r\n\t\t\t\tos.write(tid.getBytes());\r\n\t\t\t}\r\n\t\t}catch(Throwable e){\r\n\t\t\tLog.d(TAG_EMOP, \"write error:\" + e.toString(), e);\r\n\t\t}finally{\r\n\t\t\tif(os != null){\r\n\t\t\t\ttry {\r\n\t\t\t\t\tos.close();\r\n\t\t\t\t} catch (IOException e) {\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\t\r\n\tprivate String readTrackIdFromSD(){\r\n\t\tFile track = null;\r\n\t\tString pid = null;\r\n\t\tBufferedReader input = null;\r\n\t\ttry{\r\n\t\t\tif(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){\r\n\t\t\t\ttrack = new File(Environment.getExternalStorageDirectory(), \"taodianhuo.pid\");\r\n\t\t\t}else {\r\n\t\t\t\ttrack = new File(ctx.getExternalFilesDir(null), \"taodianhuo.pid\");\r\n\t\t\t}\r\n\t\t\tLog.d(TAG_EMOP, \"read track user from:\" + track.getAbsolutePath());\r\n\t\t\tif(track.isFile()){\r\n\t\t\t\tinput = new BufferedReader(new InputStreamReader(new FileInputStream(track)));\r\n\t\t\t\tpid = input.readLine();\r\n\t\t\t}\r\n\t\t\tLog.d(TAG_EMOP, \"read pid in sdcard:\" + pid);\r\n\t\t}catch(Throwable e){\r\n\t\t\tLog.e(TAG_EMOP, \"read pid error:\" + e.toString(), e);\r\n\t\t}finally{\r\n\t\t\tif(input != null){\r\n\t\t\t\ttry {\r\n\t\t\t\t\tinput.close();\r\n\t\t\t\t} catch (IOException e) {\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn pid;\r\n\t}\r\n\t\r\n private String getMetaDataValue(String name) {\r\n Object value = null;\r\n PackageManager packageManager = ctx.getPackageManager();\r\n ApplicationInfo applicationInfo;\r\n try {\r\n applicationInfo = packageManager.getApplicationInfo(ctx.getPackageName(), PackageManager.GET_META_DATA);\r\n if (applicationInfo != null && applicationInfo.metaData != null) {\r\n value = applicationInfo.metaData.get(name);\r\n }\r\n } catch (NameNotFoundException e) {\r\n throw new RuntimeException(\r\n \"Could not read the name in the manifest file.\", e);\r\n }\r\n if (value == null) {\r\n throw new RuntimeException(\"The name '\" + name\r\n + \"' is not defined in the manifest file's meta data.\");\r\n }\r\n return value.toString();\r\n }\t\r\n\t\t\r\n\tpublic String getSettings(String key){\r\n\t\tSharedPreferences settings = ctx.getSharedPreferences(Constants.PREFS_NAME, 0);\r\n\t\treturn settings.getString(key, null);\r\n\t}\r\n\r\n\tpublic String saveSettings(String key, String value){\r\n\t\tSharedPreferences settings = ctx.getSharedPreferences(Constants.PREFS_NAME, 0);\r\n \tSharedPreferences.Editor editor = settings.edit();\r\n \teditor.putString(key, value);\r\n \teditor.commit();\t\r\n\t\treturn settings.getString(key, null);\r\n\t}\t\r\n\tpublic String removeSettings(String key){\r\n\t\tSharedPreferences settings = ctx.getSharedPreferences(Constants.PREFS_NAME, 0);\r\n \tSharedPreferences.Editor editor = settings.edit();\r\n \teditor.remove(key);\r\n \teditor.commit();\t\r\n\t\treturn settings.getString(key, null);\r\n\t}\r\n}\r",
"public class Schema {\r\n\tpublic static final UriMatcher FmeiUriMatcher;\r\n\r\n\tpublic static final String AUTHORITY = \"com.emop.client.provider.Fmei\";\r\n\t\r\n\t/*\r\n\t * 专题列表。\r\n\t */\r\n public static final Uri TOPIC_LIST = Uri.parse(\"content://\" + AUTHORITY + \"/topics/\");\r\n\t\r\n /*\r\n\t * 我的收藏。\r\n\t */\r\n public static final Uri MYFAV_LIST = Uri.parse(\"content://\" + AUTHORITY + \"/myfav/\");\r\n\r\n /*\r\n * 分类列表\r\n */\r\n public static final Uri CATE_LIST = Uri.parse(\"content://\" + AUTHORITY + \"/cates/\");\r\n\r\n public static final Uri REBATE_CATE_LIST = Uri.parse(\"content://\" + AUTHORITY + \"/rebate_cates/\");\r\n \r\n \r\n\r\n /*\r\n * 店铺列表\r\n */\r\n public static final Uri SHOP_LIST = Uri.parse(\"content://\" + AUTHORITY + \"/shops/\");\r\n \r\n /*\r\n * 热门分类列表\r\n */\r\n public static final Uri HOT_CATE_LIST = Uri.parse(\"content://\" + AUTHORITY + \"/hots/\");\r\n\r\n /*\r\n * 外链活动列表\r\n */\r\n public static final Uri ACTIVITY_LIST = Uri.parse(\"content://\" + AUTHORITY + \"/acts/\");\r\n \r\n \r\n /*\r\n * 内容列表\r\n */\r\n public static final Uri ITME_LIST = Uri.parse(\"content://\" + AUTHORITY + \"/items/\");\r\n\r\n /*\r\n * 折扣列表\r\n */\r\n public static final Uri REBATE_LIST = Uri.parse(\"content://\" + AUTHORITY + \"/rebates/\");\r\n\r\n \r\n public static final int TYPE_TOPICS = 1001;\r\n public static final int TYPE_TOPIC_ID = 1002;\r\n public static final int TYPE_TOPIC_ITEM_LIST = 1003;\r\n \r\n public static final int TYPE_CATES = 2001;\r\n public static final int TYPE_CATE_ID = 2002;\r\n public static final int TYPE_CATE_ITEM_LIST = 2003;\r\n\r\n public static final int TYPE_HOTS = 3001;\r\n //public static final int TYPE_CATES_ID = 4;\r\n public static final int TYPE_HOT_ITEM_LIST = 3003;\r\n\r\n public static final int TYPE_ACTS = 4001; \r\n public static final int TYPE_ACT_ITEM_LIST = 4003;\r\n\r\n public static final int TYPE_MYFAVS = 5001; \r\n public static final int TYPE_MYFAV_ITEM_LIST = 5003;\r\n \r\n \r\n public static final int TYPE_ITEMS = 5001;\r\n public static final int TYPE_ITEM_ID = 5002;\r\n \r\n public static final int TYPE_SHOPS = 6001;\r\n public static final int TYPE_SHOPS_CATE = 6002;\r\n public static final int TYPE_SHOP_ID = 6003;\r\n public static final int TYPE_SHOP_TAOKE_LSIT = 6004;\r\n \r\n public static final int TYPE_REBATES = 7001;\r\n public static final int TYPE_REBATES_CATE = 7002;\r\n\r\n public static final int TYPE_REBATE_CATES = 8001;\r\n public static final int TYPE_REBATE_CATE_ID = 8002;\r\n public static final int TYPE_REBATE_CATE_ITEM_LIST = 8002;\r\n \r\n \r\n static {\r\n \tFmeiUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);\r\n FmeiUriMatcher.addURI(Schema.AUTHORITY, \"topics\", Schema.TYPE_TOPICS);\r\n FmeiUriMatcher.addURI(Schema.AUTHORITY, \"topic/#\", Schema.TYPE_TOPIC_ID);\r\n FmeiUriMatcher.addURI(Schema.AUTHORITY, \"topic/#/list\", Schema.TYPE_TOPIC_ITEM_LIST);\r\n \r\n FmeiUriMatcher.addURI(Schema.AUTHORITY, \"cates\", Schema.TYPE_CATES);\r\n FmeiUriMatcher.addURI(Schema.AUTHORITY, \"cate/#\", Schema.TYPE_CATE_ID);\r\n FmeiUriMatcher.addURI(Schema.AUTHORITY, \"cate/#/list\", Schema.TYPE_CATE_ITEM_LIST);\r\n\r\n FmeiUriMatcher.addURI(Schema.AUTHORITY, \"hots\", Schema.TYPE_HOTS);\r\n FmeiUriMatcher.addURI(Schema.AUTHORITY, \"hot/#/list\", Schema.TYPE_HOT_ITEM_LIST);\r\n \r\n FmeiUriMatcher.addURI(Schema.AUTHORITY, \"acts\", Schema.TYPE_ACTS);\r\n FmeiUriMatcher.addURI(Schema.AUTHORITY, \"act/#/list\", Schema.TYPE_ACT_ITEM_LIST);\r\n\r\n FmeiUriMatcher.addURI(Schema.AUTHORITY, \"rebate_cates\", Schema.TYPE_REBATE_CATES);\r\n FmeiUriMatcher.addURI(Schema.AUTHORITY, \"rebate_cates/#\", Schema.TYPE_REBATE_CATE_ID);\r\n FmeiUriMatcher.addURI(Schema.AUTHORITY, \"rebate_cates/#/list\", Schema.TYPE_REBATE_CATE_ITEM_LIST); \r\n \r\n FmeiUriMatcher.addURI(Schema.AUTHORITY, \"myfavs\", Schema.TYPE_MYFAVS);\r\n FmeiUriMatcher.addURI(Schema.AUTHORITY, \"myfav/#/list\", Schema.TYPE_MYFAV_ITEM_LIST); \r\n \r\n FmeiUriMatcher.addURI(Schema.AUTHORITY, \"items\", Schema.TYPE_ITEMS);\r\n FmeiUriMatcher.addURI(Schema.AUTHORITY, \"item/#\", Schema.TYPE_ITEM_ID);\r\n\r\n FmeiUriMatcher.addURI(Schema.AUTHORITY, \"shops\", Schema.TYPE_SHOPS);\r\n FmeiUriMatcher.addURI(Schema.AUTHORITY, \"shops/cate/#/list\", Schema.TYPE_SHOPS_CATE);\r\n FmeiUriMatcher.addURI(Schema.AUTHORITY, \"shop/#\", Schema.TYPE_SHOP_ID);\r\n FmeiUriMatcher.addURI(Schema.AUTHORITY, \"shop/#/taoke_list\", Schema.TYPE_SHOP_TAOKE_LSIT);\r\n\r\n FmeiUriMatcher.addURI(Schema.AUTHORITY, \"rebates\", Schema.TYPE_REBATES);\r\n FmeiUriMatcher.addURI(Schema.AUTHORITY, \"rebates/cate/#/list\", Schema.TYPE_REBATES_CATE); \r\n } \r\n \r\n}\r",
"public class ClientDataRefresh extends Thread{\r\n\tprivate Context ctx = null;\r\n\tprivate FmeiClient client = null;\r\n\tprivate Display display = null;\r\n\tpublic ClientDataRefresh(Context context, Display display){\r\n\t\tthis.ctx = context;\r\n\t\tclient = FmeiClient.getInstance(context);\r\n\t\tthis.display = display;\r\n\t}\r\n\t\r\n\tpublic void run(){\r\n\t\tclient.isInited = true;\r\n\t\tloadUserInfo();\r\n\t\tclient.updateLocalTrackId();\r\n\t\tclient.getTrackPid();\r\n\t\t\r\n\t\tclient.refreshActivityItemList(ctx.getContentResolver());\r\n\t\tCursor c = ctx.getContentResolver().query(Schema.TOPIC_LIST, new String[]{Columns._ID}, null, null, null);\r\n\t\tc.close();\r\n\t\tloadTopicImage();\r\n\t\tc = ctx.getContentResolver().query(Schema.CATE_LIST, new String[]{Columns._ID}, null, null, null);\t\r\n\t\tc.close();\r\n\t\t\r\n\t\tc = ctx.getContentResolver().query(Schema.HOT_CATE_LIST, new String[]{Columns._ID}, null, null, null);\r\n\t\tc.close();\r\n\t\t\r\n\t\tclient.cleanExpiredData(ctx.getContentResolver());\t\t\r\n\t}\r\n\t\r\n\tpublic void loadTopicImage(){\r\n\t\tCursor c = client.getTopicList(ctx.getContentResolver());\r\n\t\tboolean hasMore = c.moveToFirst();\r\n\t\tint picIndex = 0;\r\n\t\tif(hasMore){\r\n\t\t\tpicIndex = c.getColumnIndex(Topic.FRONT_PIC);\r\n\t\t}\r\n if(display != null){\r\n \tint width = display.getWidth();\r\n\t\t\tfor(int i = 0; i < 5 && hasMore; hasMore = c.moveToNext(), i++){\r\n\t\t\t\tString pic = c.getString(picIndex);\r\n\t\t\t\tclient.tmpImgLoader.loadToCache(pic, width);\r\n\t\t\t}\r\n }\r\n\t\tc.close();\r\n\t}\r\n\t\r\n\t\r\n\tprivate void loadUserInfo(){\r\n\t\tSharedPreferences settings = ctx.getSharedPreferences(Constants.PREFS_NAME, 0);\r\n\t\tString userId = settings.getString(Constants.PREFS_OAUTH_ID, \"\");\r\n\t\tString trackId = settings.getString(Constants.PREFS_TRACK_ID, \"\");\t\t\t\r\n\t\t\r\n\t\tLog.d(Constants.TAG_EMOP, \"User id:\" + userId);\r\n\t\tclient.userId = userId;\r\n\t\tclient.trackUserId = trackId;\r\n\t}\r\n\t\r\n}\r",
"public class UpgradeCheckTask extends AsyncTask<Activity, Void, ApiResult> {\r\n\tprivate static final int DOWN_UPDATE = 1;\r\n\tprivate static final int DOWN_OVER = 2;\r\n\t\r\n\tprivate Activity context;\r\n\tprivate Dialog versionDialog = null;\r\n\tprivate Dialog downloaddialog = null;\r\n\r\n\tprivate PackageInfo curVersion = null;\r\n\tprivate FmeiClient client = null;\r\n\tprivate TextView newVrsionInfo = null;\r\n\tprivate TextView updateNote = null;\r\n\tprivate ApiResult upgradeInfo = null;\r\n\tprivate String apkUrl = null;\r\n\tprivate ProgressBar mProgress;\t\r\n\tprivate File localPath = null;\r\n\tprivate int progress = 0;\r\n\tprivate boolean interceptFlag = false;\r\n\tprivate OnClickListener callback = null;\r\n\tprivate boolean inBackground = false;\r\n\t\r\n\t\r\n\tpublic UpgradeCheckTask(Activity context, OnClickListener callback, boolean inBackground){\r\n\t\tinit(context);\r\n\t\tthis.context = context;\r\n\t\tthis.callback = callback;\r\n\t\tthis.inBackground = inBackground;\r\n\t\tclient = FmeiClient.getInstance(null);\r\n\t}\r\n\t\r\n\tprivate void init(Activity context){\r\n\t\tversionDialog = DialogBuilder.showVersionCheck(context, listener);\r\n\t\tPackageManager packageManager = context.getPackageManager();\r\n\t\ttry {\r\n\t\t\tcurVersion = packageManager.getPackageInfo(context.getPackageName(), 0);\r\n\t\t} catch (NameNotFoundException e) {\r\n\t\t\te.printStackTrace();\r\n\t\t}\t\r\n\t\t\r\n\t\tnewVrsionInfo = (TextView)versionDialog.findViewById(R.id.new_version_info);\r\n\t\tupdateNote = (TextView)versionDialog.findViewById(R.id.new_version_note);\r\n\t}\r\n\t\r\n\tpublic void close(){\r\n\t\tversionDialog.dismiss();\r\n\t}\r\n\r\n\t@Override\r\n\tprotected ApiResult doInBackground(Activity... arg0) {\r\n\t\tif(!inBackground){\r\n\t\t\tthis.mHandler.post(new Runnable(){\r\n\t\t\t\tpublic void run(){\r\n\t\t\t\t\tversionDialog.show();\t\t\t\t\t\r\n\t\t\t\t}\r\n\t\t\t});\r\n\t\t}\r\n\t\tApiResult r = client.checkUpgradeVersion();\r\n\r\n\t\treturn r;\r\n\t}\r\n\t\r\n\tprotected OnClickListener listener = new OnClickListener(){\r\n\r\n\t\t@Override\r\n\t\tpublic void onClick(View v) {\r\n\t\t\tLog.d(Constants.TAG_EMOP, \"click:\" + v.getId());\r\n\t\t\tversionDialog.dismiss();\t\t\t\r\n\t\t\tif(v.getId() == R.id.upgrade_now){\r\n\t\t\t\tonUpgradeVersion(v);\r\n\t\t\t}else{\r\n\t\t\t}\r\n\t\t\tif(callback != null){\r\n\t\t\t\tcallback.onClick(v);\r\n\t\t\t}\t\t\t\r\n\t\t}};\r\n\t\r\n\tprotected void onPostExecute(ApiResult result) {\r\n\t\tif(!result.isOK){\r\n\t\t\tToast.makeText(context, result.errorMsg(), \r\n\t\t\t\t\tToast.LENGTH_LONG).show();\r\n\t\t}else{\r\n\t\t\tlong ver = Integer.parseInt(result.getString(\"data.num_version\"));\r\n\t\t\tif(ver <= curVersion.versionCode){\r\n\t\t\t\tnewVrsionInfo.setText(String.format(\"已经是最新版本:%1s 。\", curVersion.versionName));\r\n\t\t\t\tView v = versionDialog.findViewById(R.id.noNeedUpgrade);\r\n\t\t\t\tv.setVisibility(View.VISIBLE);\r\n\t\t\t\t\r\n\t\t\t\tv = versionDialog.findViewById(R.id.needUpgrade);\r\n\t\t\t\tv.setVisibility(View.GONE);\r\n\t\t\t}else {\r\n\t\t\t\tif(inBackground){\r\n\t\t\t\t\tversionDialog.show();\r\n\t\t\t\t}\r\n\t\t\t\tupgradeInfo = result;\r\n\t\t\t\tString newVersion = \"有新版本:\" + result.getString(\"data.version_name\");\t\t\t\t\r\n\t\t\t\t//newVersion += \"\\n\" + result.getString(\"data.version_update\");\r\n\t\t\t\tnewVrsionInfo.setText(newVersion);\r\n\t\t\t\tnewVersion = result.getString(\"data.version_update\");\r\n\t\t\t\tnewVersion = newVersion.replace(\"\\r\", \"\");\r\n\t\t\t\tupdateNote.setVisibility(View.VISIBLE);\r\n\t\t\t\tupdateNote.setText(newVersion);\r\n\t\t\t\tView v = versionDialog.findViewById(R.id.needUpgrade);\r\n\t\t\t\tv.setVisibility(View.VISIBLE);\r\n\t\t\t\t\r\n\t\t\t\tv = versionDialog.findViewById(R.id.noNeedUpgrade);\r\n\t\t\t\tv.setVisibility(View.GONE);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t\r\n\tpublic void onUpgradeVersion(View v){\r\n\t\tversionDialog.dismiss();\r\n\t\t\r\n\t\tif(upgradeInfo != null){\r\n\t\t\tapkUrl = upgradeInfo.getString(\"data.download_url\");\r\n\t\t\tLog.d(Constants.TAG_EMOP, \"start updrage from:\" + apkUrl);\r\n\t\t\t//client.upgradeNewVersion(apkUrl);\r\n\t\t\tdownloaddialog = DialogBuilder.showInstallAPI(context, null);\r\n\t\t\tmProgress = (ProgressBar)downloaddialog.findViewById(R.id.progress);\r\n\t\t\tdownloaddialog.show();\r\n\t\t\tString state = Environment.getExternalStorageState();\r\n\t\t\tif (Environment.MEDIA_MOUNTED.equals(state)) {\r\n\t\t\t\tdownloadApk();\r\n\t\t\t}else {\r\n\t\t\t\tLog.d(Constants.TAG_EMOP, \"not mount stoarge:\" + state);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n private void downloadApk(){\r\n \tThread downLoadThread = new Thread(mdownApkRunnable);\r\n \tdownLoadThread.start();\r\n }\r\n \r\n private void installApk(){\r\n \tif(downloaddialog != null && downloaddialog.isShowing()){\r\n \t\tdownloaddialog.dismiss();\r\n \t}\r\n \tif(localPath != null && localPath.isFile()){\r\n \t\t//finish();\r\n\r\n\t \tIntent i = new Intent(Intent.ACTION_VIEW);\r\n\t \tUri path = Uri.fromFile(localPath);\r\n\t \tLog.d(Constants.TAG_EMOP, \"download uri:\" + path.toString());\r\n\t \ti.setDataAndType(Uri.fromFile(localPath), \r\n\t \t\t\"application/vnd.android.package-archive\"); \r\n\t \tcontext.startActivity(i); \r\n \t\t//stopSystem();\r\n \t}\r\n }\r\n \r\n \r\n private void stopSystem(){\r\n \tIntent intent = new Intent(Intent.ACTION_MAIN); \r\n intent.addCategory(Intent.CATEGORY_HOME); \r\n intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); \r\n context.startActivity(intent); \r\n android.os.Process.killProcess(android.os.Process.myPid());\r\n } \r\n \r\n private Runnable mdownApkRunnable = new Runnable() {\r\n\r\n\t\t@Override\r\n\t\tpublic void run() {\r\n\t\t\tURL url = null;\r\n\t\t\ttry {\r\n\t\t\t\turl = new URL(apkUrl);\r\n\t\t\t\tHttpURLConnection conn = (HttpURLConnection)url.openConnection();\r\n\t\t\t\t conn.connect();\r\n\t\t\t\t int length = conn.getContentLength();\r\n\t\t\t\t InputStream is = conn.getInputStream();\r\n\t\t\t\t \r\n\t\t\t\t File root = new File(Environment.getExternalStorageDirectory(), \"downloads\"); // .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);\r\n\t\t\t\t if(!root.exists()){\r\n\t\t\t\t\t if(!root.mkdirs()){\r\n\t\t\t\t\t\t Log.d(Constants.TAG_EMOP, \"failed to create dir:\" + root.getAbsolutePath());\r\n\t\t\t\t\t }\r\n\t\t\t\t }\r\n\t\t\t\t \r\n\t\t\t\t localPath = new File(root, \"doudougou.apk\");\r\n\t\t\t\t Log.d(Constants.TAG_EMOP, \"download local file:\" + localPath.getAbsolutePath() + \", size:\" + length);\r\n\t\t\t\t FileOutputStream fos = new FileOutputStream(localPath);\r\n\t\t\t\t int count = 0;\r\n\t\t\t\t byte buf[] = new byte[10240];\r\n\t\t\t\t do{ \r\n\t\t\t\t\t int numread = is.read(buf);\r\n\t\t\t\t\t count += numread;\r\n\t\t\t\t\t progress =(int)(((float)count / length) * 100);\r\n\t\t\t\t\t mHandler.sendEmptyMessage(DOWN_UPDATE);\r\n\t\t\t\t\t if(numread <= 0){ \r\n\t\t\t\t\t\t break;\r\n\t\t\t\t\t }\r\n\t\t\t\t\t Log.d(Constants.TAG_EMOP, \"download size:\" + numread);\r\n\t\t\t\t\t fos.write(buf,0,numread);\r\n\t\t\t\t }while(!interceptFlag);//点击取消就停止下载.\r\n\t\t\t\t fos.close();\r\n\t\t\t\t is.close();\r\n\t\t\t\t mHandler.sendEmptyMessage(DOWN_OVER);\r\n\t\t\t} catch (Exception e) {\r\n\t\t\t\t// TODO Auto-generated catch block\r\n\t\t\t\te.printStackTrace();\r\n\t\t\t}\r\n\t\t\t\r\n\t\t} \r\n \t\r\n }; \r\n \r\n private Handler mHandler = new Handler(){\r\n \tpublic void handleMessage(Message msg) {\r\n \t\t switch (msg.what) {\r\n \t\t \tcase DOWN_UPDATE:\r\n \t\t \t\tmProgress.setProgress(progress);\r\n \t\t \t\tbreak;\r\n \t\t \tcase DOWN_OVER:\r\n \t\t \t\tdownloaddialog.dismiss();\r\n \t\t \t\tinstallApk();\r\n \t\t \t\tbreak;\r\n \t\t \tdefault:\r\n \t\t \t\tbreak;\r\n \t\t }\r\n \t}\r\n \t\r\n }; \r\n}"
] | import static com.emop.client.Constants.TAG_EMOP;
import java.util.Date;
import java.util.List;
import android.app.TabActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Resources;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TabHost;
import com.emop.client.io.ApiResult;
import com.emop.client.io.FmeiClient;
import com.emop.client.provider.Schema;
import com.emop.client.tasks.ClientDataRefresh;
import com.emop.client.tasks.UpgradeCheckTask;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory; | package com.emop.client;
public class MainTabActivity extends TabActivity{
private IWXAPI api;
private LinearLayout navBackGroup = null;
private LinearLayout navText = null;
private int tabCount = 0;
public int curTabIndex = -1;
public TabHost tabHost = null;
private NavMenuListener navListener = null;
//private LookMashClient client = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(Constants.TAG_EMOP, "on create on tab view");
//注册微信插件服务。
api = WXAPIFactory.createWXAPI(this, com.emop.client.wxapi.Constants.APP_ID, false);
api.registerApp(Constants.APP_ID);
setContentView(R.layout.tab_main);
Resources res = getResources(); // Resource object to get Drawables
tabHost = getTabHost(); // The activity TabHost
TabHost.TabSpec spec; // Resusable TabSpec for each tab
Intent intent; // Reusable Intent for each tab
intent = new Intent().setClass(this, GuangActivity.class);
spec = tabHost.newTabSpec("guang").setIndicator("逛街",
res.getDrawable(R.drawable.ic_launcher))
.setContent(intent);
tabHost.addTab(spec);
intent = new Intent().setClass(this, HotActivity.class);
spec = tabHost.newTabSpec("hot").setIndicator("热门",
res.getDrawable(R.drawable.ic_launcher))
.setContent(intent);
tabHost.addTab(spec);
intent = new Intent().setClass(this, CateListActivity.class);
spec = tabHost.newTabSpec("cate_list").setIndicator("分类",
res.getDrawable(R.drawable.ic_launcher))
.setContent(intent);
tabHost.addTab(spec);
intent = new Intent().setClass(this, MyFavoriteActivity.class);
spec = tabHost.newTabSpec("my_favorite").setIndicator("收藏",
res.getDrawable(R.drawable.ic_launcher))
.setContent(intent);
tabHost.addTab(spec);
intent = new Intent().setClass(this, SettingActivity.class);
spec = tabHost.newTabSpec("my_setting").setIndicator("设置",
res.getDrawable(R.drawable.ic_launcher))
.setContent(intent);
tabHost.addTab(spec);
int curTab = 0;
if(savedInstanceState != null){
curTab = savedInstanceState.getInt("curTab", 0);
if(curTab > 0){
activeTab(curTab);
}
}
tabHost.setCurrentTab(curTab);
this.tabCount = tabHost.getTabWidget().getChildCount();
initNavEventListner();
checkLaunchUri();
checkNewVersion();
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
checkLaunchUri();
}
public void activeTab(int t){
if(navListener != null){
navListener.onClick(navText.getChildAt(t));
}
}
protected void onSaveInstanceState(Bundle outState){
outState.putInt("curTab", getTabHost().getCurrentTab());
}
protected void onResume (){
super.onResume();
}
protected void checkLaunchUri(){ | FmeiClient c = FmeiClient.getInstance(this); | 2 |
batir-akhmerov/hybricache | hybricache/src/main/java/org/hybricache/HybriCacheManager.java | [
"public enum CacheMode{VALUE, HASH};\r",
"public enum CacheType{HYBRID, LOCAL, REMOTE};\r",
"public class HybriKeyCache extends BaseCache implements Cache {\r\n\t\r\n\tprotected int keyTrustPeriod;\r\n\t\r\n\t\t\r\n\tpublic HybriKeyCache(Ehcache ehCacheNative, HybriCacheConfiguration hybriCacheConfig, RemoteCacheFactory remoteCacheFactory) {\r\n\t\tsuper(ehCacheNative, hybriCacheConfig, remoteCacheFactory);\r\n\t\tthis.keyTrustPeriod = getHybriCacheConfig().getKeyTrustPeriod();\r\n\t}\r\n\t\t\r\n\tpublic void removeBothHybriKeys(Object key){\r\n\t\tgetEhCache().evict(key);\r\n\t\tgetRemoteCache().evict(key);\r\n\t}\r\n\t\r\n\tpublic HybriKey getKeyRemote(Object key) {\r\n\t\tHybriKey hybriKey = getRemoteCache().get(key, HybriKey.class);\r\n\t\tif (hybriKey == null) {\r\n\t\t\thybriKey = new HybriKey();\r\n\t\t}\r\n\t\treturn hybriKey;\r\n\t}\r\n\tpublic void putKeyRemote(Object key, HybriKey hybriKey) {\r\n\t\tgetRemoteCache().put(key, hybriKey);\r\n\t}\r\n\t\r\n\tpublic HybriKey getKeyLocal(Object key) {\r\n\t\tHybriKey hybriKey = getEhCache().get(key, HybriKey.class);\r\n\t\tif (hybriKey == null) {\r\n\t\t\thybriKey = new HybriKey();\r\n\t\t}\r\n\t\treturn hybriKey;\r\n\t}\r\n\tpublic void putKeyLocal(Object key, HybriKey hybriKey) {\r\n\t\tgetEhCache().put(key, hybriKey);\r\n\t}\r\n\t\r\n\t\r\n\tpublic boolean isKeyRecent(HybriKey keyLocal) {\r\n\t\tlong currentTime = System.currentTimeMillis();\r\n\t\tboolean isRecent = keyLocal != null && !keyLocal.isUndefined() \r\n\t\t\t\t&& (currentTime - keyLocal.getLastAccessedTime()) < this.keyTrustPeriod;\r\n\t\t\r\n\t\tSystem.out.println(\"TIME DIFF: \" + (currentTime - keyLocal.getLastAccessedTime()));\r\n\t\treturn isRecent;\r\n\t}\r\n\tpublic boolean isKeyValid(HybriKey keyLocal, HybriKey keyRemote) {\r\n\t\treturn keyLocal != null && keyRemote != null\r\n\t\t\t\t&& !keyLocal.isUndefined() && !keyRemote.isUndefined()\r\n\t\t\t\t&& keyLocal.getRevision() == keyRemote.getRevision();\r\n\t}\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\r\n\t@Override\r\n\tpublic String getName() {\r\n\t\t// TODO Auto-generated method stub\r\n\t\treturn null;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic Object getNativeCache() {\r\n\t\t// TODO Auto-generated method stub\r\n\t\treturn null;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic ValueWrapper get(Object key) {\r\n\t\t// TODO Auto-generated method stub\r\n\t\treturn null;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic <T> T get(Object key, Class<T> type) {\r\n\t\t// TODO Auto-generated method stub\r\n\t\treturn null;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic <T> T get(Object key, Callable<T> valueLoader) {\r\n\t\t// TODO Auto-generated method stub\r\n\t\treturn null;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void put(Object key, Object value) {\r\n\t\t// TODO Auto-generated method stub\r\n\t\t\r\n\t}\r\n\r\n\t@Override\r\n\tpublic ValueWrapper putIfAbsent(Object key, Object value) {\r\n\t\t// TODO Auto-generated method stub\r\n\t\treturn null;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void evict(Object key) {\r\n\t\t// TODO Auto-generated method stub\r\n\t\t\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void clear() {\r\n\t\t// TODO Auto-generated method stub\r\n\t\t\r\n\t}\r\n\r\n\tpublic int getKeyTrustPeriod() {\r\n\t\treturn this.keyTrustPeriod;\r\n\t}\r\n\r\n\tpublic void setKeyTrustPeriod(int keyTrustPeriod) {\r\n\t\tthis.keyTrustPeriod = keyTrustPeriod;\r\n\t}\r\n\t\r\n\t\r\n\t\r\n\t\r\n\t\r\n\r\n}\r",
"public interface RemoteCacheFactory {\r\n\t\r\n\t@SuppressWarnings(\"rawtypes\")\r\n\tpublic RemoteCache getInstance(HybriCacheConfiguration conf);\r\n\r\n}\r",
"public class RedisRemoteCacheFactory implements RemoteCacheFactory {\r\n\r\n\t@Override\r\n\t@SuppressWarnings(\"rawtypes\")\r\n\tpublic RemoteCache getInstance(HybriCacheConfiguration conf) {\r\n\t\tRemoteCache remoteCache = null;\r\n\t\tif (conf.getCacheMode() == CacheMode.HASH) {\r\n\t\t\tremoteCache = new RedisRemoteHashCache(conf);\r\n\t\t}\r\n\t\telse {\r\n\t\t\tremoteCache = new RedisRemoteValueCache(conf);\r\n\t\t}\r\n\t\ttry {\r\n\t\t\tremoteCache.clear();\r\n\t\t}\r\n\t\tcatch(Exception ex) {\r\n\t\t\tthrow new RuntimeException(\"Cannot establish Redis connection!\", ex);\r\n\t\t}\r\n\t\treturn remoteCache;\r\n\t}\r\n\r\n}\r"
] | import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import org.hybricache.HybriCacheConfiguration.CacheMode;
import org.hybricache.HybriCacheConfiguration.CacheType;
import org.hybricache.key.HybriKeyCache;
import org.hybricache.remote.RemoteCacheFactory;
import org.hybricache.remote.redis.RedisRemoteCacheFactory;
import org.springframework.cache.Cache;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.transaction.AbstractTransactionSupportingCacheManager;
import org.springframework.util.StringUtils;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Status;
import net.sf.ehcache.config.CacheConfiguration;
import net.sf.ehcache.config.Configuration;
import net.sf.ehcache.config.PersistenceConfiguration;
import net.sf.ehcache.config.PersistenceConfiguration.Strategy;
import net.sf.ehcache.store.MemoryStoreEvictionPolicy;
| /**
*
*/
package org.hybricache;
/**
* The HybriCacheManager class
*
* @author Batir Akhmerov
* Created on Jan 26, 2017
*/
public class HybriCacheManager extends AbstractTransactionSupportingCacheManager {
public static final CacheConfiguration DEF_EHCACHE_CONFIG = new CacheConfiguration("defaultEhCache", 0)
.memoryStoreEvictionPolicy(MemoryStoreEvictionPolicy.LFU)
.eternal(false)
.timeToLiveSeconds(60)
.timeToIdleSeconds(30)
.diskExpiryThreadIntervalSeconds(0)
.persistence(new PersistenceConfiguration().strategy(Strategy.LOCALTEMPSWAP));
public static final HybriCacheConfiguration DEF_HYBRID_CACHE_CONFIG = new HybriCacheConfiguration("defaultEhCache", CacheType.HYBRID, 1000);
public static final RemoteCacheFactory DEF_REMOTE_CACHE_FACTORY = new RedisRemoteCacheFactory();
public static final String CACHE_KEY = "hybriKey";
public static final String CACHE_COMMON = "hybriCommon";
protected Map<String, Cache> caches = new HashMap<>();
protected HybriCacheConfiguration defaultHybriCacheConfiguration;
protected List<HybriCacheConfiguration> hybriCacheConfigurationList;
protected RemoteCacheFactory remoteCacheFactory;
protected EhCacheCacheManager localCacheManager;
private String remoteSeverHost;
private Integer remoteServerPort;
//private int remoteDatabaseMaxSize;
private int remoteDatabaseSize;
protected int getNextRemoteDatabaseIndex() {
return this.remoteDatabaseSize++;
}
protected void resetRemoteDatabaseSize() {
this.remoteDatabaseSize = 0;
}
public HybriCacheManager(EhCacheCacheManager localCacheManager, String remoteSeverHost, Integer remoteServerPort) {
this.localCacheManager = localCacheManager;
this.remoteSeverHost = remoteSeverHost;
this.remoteServerPort = remoteServerPort;
}
public Configuration getConfiguration() {
return this.localCacheManager.getCacheManager().getConfiguration();
}
@Override
protected Collection<Cache> loadCaches() {
Status status = this.localCacheManager.getCacheManager().getStatus();
if (!Status.STATUS_ALIVE.equals(status)) {
throw new IllegalStateException(
"An 'alive' EhCache CacheManager is required - current cache is " + status.toString());
}
resetRemoteDatabaseSize();
HybriCacheConfiguration systemHybriCacheConfig = new HybriCacheConfiguration(null, CacheType.HYBRID, 1000);
systemHybriCacheConfig.setDatabaseIndex(getNextRemoteDatabaseIndex());
setRemoteServer(systemHybriCacheConfig);
registerEhCache(CACHE_KEY, systemHybriCacheConfig, null);
systemHybriCacheConfig.setDatabaseIndex(getNextRemoteDatabaseIndex());
registerEhCache(CACHE_COMMON, systemHybriCacheConfig, null);
String[] names = this.localCacheManager.getCacheManager().getCacheNames();
Collection<Cache> cacheSet = new LinkedHashSet<>(names.length);
for (String cacheName : names) {
Ehcache ehcache = this.localCacheManager.getCacheManager().getEhcache(cacheName);
HybriCacheConfiguration hybriCacheConfig = findOrAddHybriCacheConfig(cacheName, ehcache.getCacheConfiguration());
HybriCache hybriCache = new HybriCache(ehcache, hybriCacheConfig, getRemoteCacheFactory(), createHybriKeyCacheIfNeeded(hybriCacheConfig));
this.caches.put(cacheName, hybriCache);
cacheSet.add(hybriCache);
}
// load caches declared in hybriCacheConfigurationList but missing in ehcache.xml
for (HybriCacheConfiguration hybriCacheConfig: this.hybriCacheConfigurationList) {
String cacheName = hybriCacheConfig.getCacheName();
if (this.caches.containsKey(hybriCacheConfig.getCacheName())) {
continue;
}
setRemoteServer(hybriCacheConfig);
hybriCacheConfig = registerEhCache(cacheName, hybriCacheConfig, null);
Ehcache ehcache = this.localCacheManager.getCacheManager().getEhcache(cacheName);
HybriCache hybriCache = new HybriCache(ehcache, hybriCacheConfig, getRemoteCacheFactory(), createHybriKeyCacheIfNeeded(hybriCacheConfig));
this.caches.put(cacheName, hybriCache);
cacheSet.add(hybriCache);
}
return cacheSet;
}
@Override
protected Cache getMissingCache(String name) {
return createHybriCache_Common(name);
}
| protected HybriKeyCache createHybriCache_Key(String cacheName) {
| 2 |
emina/kodkod | examples/kodkod/examples/alloy/RingElection.java | [
"public abstract class Expression extends Node {\n\t\n\t/** The universal relation: contains all atoms in a {@link kodkod.instance.Universe universe of discourse}. */\n\tpublic static final Expression UNIV = new ConstantExpression(\"univ\", 1);\n\t\n\t/** The identity relation: maps all atoms in a {@link kodkod.instance.Universe universe of discourse} to themselves. */\n\tpublic static final Expression IDEN = new ConstantExpression(\"iden\", 2);\n\t\n\t/** The empty relation: contains no atoms. */\n\tpublic static final Expression NONE = new ConstantExpression(\"none\", 1);\n\t\n\t/** The integer relation: contains all atoms {@link kodkod.instance.Bounds bound} to integers */\n\tpublic static final Expression INTS = new ConstantExpression(\"ints\", 1);\n\t\n /**\n * Constructs a leaf expression\n * @ensures no this.children'\n */\n Expression() { }\n\n /**\n * Returns the join of this and the specified expression. The effect\n * of this method is the same as calling this.compose(JOIN, expr).\n * @return this.compose(JOIN, expr)\n */\n public final Expression join(Expression expr) {\n return compose(JOIN,expr);\n }\n \n /**\n * Returns the product of this and the specified expression. The effect\n * of this method is the same as calling this.compose(PRODUCT, expr).\n * @return this.compose(PRODUCT, expr)\n */\n public final Expression product(Expression expr) {\n return compose(PRODUCT,expr);\n }\n \n /**\n * Returns the union of this and the specified expression. The effect\n * of this method is the same as calling this.compose(UNION, expr).\n * @return this.compose(UNION, expr)\n */\n public final Expression union(Expression expr) {\n \treturn compose(UNION,expr);\n }\n \n /**\n * Returns the difference of this and the specified expression. The effect\n * of this method is the same as calling this.compose(DIFFERENCE, expr).\n * @return this.compose(DIFFERENCE, expr)\n */\n public final Expression difference(Expression expr) {\n \treturn compose(DIFFERENCE,expr);\n }\n \n /**\n * Returns the intersection of this and the specified expression. The effect\n * of this method is the same as calling this.compose(INTERSECTION, expr).\n * @return this.compose(INTERSECTION, expr)\n */\n public final Expression intersection(Expression expr) {\n \treturn compose(INTERSECTION,expr);\n }\n \n /**\n * Returns the relational override of this with the specified expression. The effect\n * of this method is the same as calling this.compose(OVERRIDE, expr).\n * @return this.compose(OVERRIDE, expr)\n */\n public final Expression override(Expression expr) {\n \treturn compose(OVERRIDE,expr);\n }\n \n /**\n * Returns the composition of this and the specified expression, using the\n * given binary operator.\n * @requires op in ExprOperator.BINARY\n * @return {e: Expression | e.left = this and e.right = expr and e.op = this }\n */\n public final Expression compose(ExprOperator op, Expression expr) {\n \treturn new BinaryExpression(this, op, expr);\n }\n \n /**\n * Returns the union of the given expressions. The effect of this method is the\n * same as calling compose(UNION, exprs).\n * @return compose(UNION, exprs)\n */\n public static Expression union(Expression...exprs) { \n \treturn compose(UNION, exprs);\n }\n \n /**\n * Returns the union of the given expressions. The effect of this method is the\n * same as calling compose(UNION, exprs).\n * @return compose(UNION, exprs)\n */\n public static Expression union(Collection<? extends Expression> exprs) { \n \treturn compose(UNION, exprs);\n }\n \n /**\n * Returns the intersection of the given expressions. The effect of this method is the\n * same as calling compose(INTERSECTION, exprs).\n * @return compose(INTERSECTION, exprs)\n */\n public static Expression intersection(Expression...exprs) { \n \treturn compose(INTERSECTION, exprs);\n }\n \n /**\n * Returns the intersection of the given expressions. The effect of this method is the\n * same as calling compose(INTERSECTION, exprs).\n * @return compose(INTERSECTION, exprs)\n */\n public static Expression intersection(Collection<? extends Expression> exprs) { \n \treturn compose(INTERSECTION, exprs);\n }\n \n /**\n * Returns the product of the given expressions. The effect of this method is the\n * same as calling compose(PRODUCT, exprs).\n * @return compose(PRODUCT, exprs)\n */\n public static Expression product(Expression...exprs) { \n \treturn compose(PRODUCT, exprs);\n }\n \n /**\n * Returns the product of the given expressions. The effect of this method is the\n * same as calling compose(PRODUCT, exprs).\n * @return compose(PRODUCT, exprs)\n */\n public static Expression product(Collection<? extends Expression> exprs) { \n \treturn compose(PRODUCT, exprs);\n }\n \n /**\n * Returns the override of the given expressions. The effect of this method is the\n * same as calling compose(OVERRIDE, exprs).\n * @return compose(OVERRIDE, exprs)\n */\n public static Expression override(Expression...exprs) { \n \treturn compose(OVERRIDE, exprs);\n }\n \n /**\n * Returns the override of the given expressions. The effect of this method is the\n * same as calling compose(OVERRIDE, exprs).\n * @return compose(OVERRIDE, exprs)\n */\n public static Expression override(Collection<? extends Expression> exprs) { \n \treturn compose(OVERRIDE, exprs);\n }\n \n /**\n * Returns the composition of the given expressions using the given operator. \n * @requires exprs.length = 2 => op.binary(), exprs.length > 2 => op.nary()\n * @return exprs.length=1 => exprs[0] else {e: Expression | e.children = exprs and e.op = this }\n */\n public static Expression compose(ExprOperator op, Expression...exprs) { \n \tswitch(exprs.length) { \n \tcase 0 : \tthrow new IllegalArgumentException(\"Expected at least one argument: \" + Arrays.toString(exprs));\n \tcase 1 : \treturn exprs[0];\n \tcase 2 : \treturn new BinaryExpression(exprs[0], op, exprs[1]);\n \tdefault : \treturn new NaryExpression(op, Containers.copy(exprs, new Expression[exprs.length]));\n \t}\n }\n \n /**\n * Returns the composition of the given expressions using the given operator. \n * @requires exprs.size() = 2 => op.binary(), exprs.size() > 2 => op.nary()\n * @return exprs.size()=1 => exprs.iterator().next() else {e: Expression | e.children = exprs.toArray() and e.op = this }\n */\n public static Expression compose(ExprOperator op, Collection<? extends Expression> exprs) { \n \tswitch(exprs.size()) { \n \tcase 0 : \tthrow new IllegalArgumentException(\"Expected at least one argument: \" + exprs);\n \tcase 1 : \treturn exprs.iterator().next();\n \tcase 2 :\n \t\tfinal Iterator<? extends Expression> itr = exprs.iterator();\n \t\treturn new BinaryExpression(itr.next(), op, itr.next());\n \tdefault : \t\t\t\n \t\treturn new NaryExpression(op, exprs.toArray(new Expression[exprs.size()]));\n \t}\n }\n \n \n \n /**\n * Returns the transpose of this. The effect of this method is the same\n * as calling this.apply(TRANSPOSE).\n * @return this.apply(TRANSPOSE)\n */\n public final Expression transpose() {\n return apply(TRANSPOSE);\n }\n \n /**\n * Returns the transitive closure of this. The effect of this method is the same\n * as calling this.apply(CLOSURE).\n * @return this.apply(CLOSURE)\n */\n public final Expression closure() {\n return apply(CLOSURE);\n }\n \n /**\n * Returns the reflexive transitive closure of this. The effect of this \n * method is the same\n * as calling this.apply(REFLEXIVE_CLOSURE).\n * @return this.apply(REFLEXIVE_CLOSURE)\n */\n public final Expression reflexiveClosure() {\n \treturn apply(REFLEXIVE_CLOSURE);\n }\n \n /**\n * Returns the expression that results from applying the given unary operator\n * to this. \n * @requires op.unary()\n * @return {e: Expression | e.expression = this && e.op = this }\n * @throws IllegalArgumentException this.arity != 2\n */\n public final Expression apply(ExprOperator op) {\n \treturn new UnaryExpression(op, this);\n }\n \n /**\n * Returns the projection of this expression onto the specified columns.\n * @return {e: Expression | e = project(this, columns) }\n * @throws IllegalArgumentException columns.length < 1\n */\n public final Expression project(IntExpression... columns) {\n \treturn new ProjectExpression(this, columns);\n }\n \n /**\n * Returns the cardinality of this expression. The effect of this method is the\n * same as calling this.apply(CARDINALITY). \n * @return this.apply(CARDINALITY)\n */\n public final IntExpression count() {\n \treturn apply(CARDINALITY);\n }\n \n /**\n * Returns the sum of the integer atoms in this expression. The effect of this method is the\n * same as calling this.apply(SUM). \n * @return this.apply(SUM)\n */\n public final IntExpression sum() {\n \treturn apply(SUM);\n }\n \n /**\n * Returns the cast of this expression to an integer expression,\n * that represents either the cardinality of this expression (if op is CARDINALITY)\n * or the sum of the integer atoms it contains (if op is SUM).\n * @return {e: IntExpression | e.op = op && e.expression = this} \n */\n public final IntExpression apply(ExprCastOperator op) { \n \treturn new ExprToIntCast(this, op);\n }\n \n /**\n * Returns the formula 'this = expr'. The effect of this method is the same \n * as calling this.compare(EQUALS, expr).\n * @return this.compare(EQUALS, expr)\n */\n public final Formula eq(Expression expr) {\n \treturn compare(EQUALS, expr);\n }\n \n /**\n * Returns the formula 'this in expr'. The effect of this method is the same \n * as calling this.compare(SUBSET, expr).\n * @return this.compare(SUBSET, expr)\n */\n public final Formula in(Expression expr) {\n \treturn compare(SUBSET, expr);\n }\n \n /**\n * Returns the formula that represents the comparison of this and the\n * given expression using the given comparison operator.\n * @return {f: Formula | f.left = this && f.right = expr && f.op = op}\n */\n public final Formula compare(ExprCompOperator op, Expression expr) {\n \treturn new ComparisonFormula(this, op, expr);\n }\n \n /**\n * Returns the formula 'some this'. The effect of this method is the same as calling\n * this.apply(SOME).\n * @return this.apply(SOME)\n */\n public final Formula some() {\n return apply(SOME);\n }\n \n /**\n * Returns the formula 'no this'. The effect of this method is the same as calling\n * this.apply(NO).\n * @return this.apply(NO)\n */\n public final Formula no() {\n return apply(NO);\n }\n \n /**\n * Returns the formula 'one this'. The effect of this method is the same as calling\n * this.apply(ONE).\n * @return this.apply(ONE)\n */\n public final Formula one() {\n return apply(ONE);\n }\n \n /**\n * Returns the formula 'lone this'. The effect of this method is the same as calling\n * this.apply(LONE).\n * @return this.apply(LONE)\n */\n public final Formula lone() {\n return apply(LONE);\n }\n \n /**\n * Returns the formula that results from applying the specified multiplicity to\n * this expression. The SET multiplicity is not allowed.\n * @return {f: Formula | f.multiplicity = mult && f.expression = this}\n * @throws IllegalArgumentException mult = SET\n */\n public final Formula apply(Multiplicity mult) {\n \treturn new MultiplicityFormula(mult, this);\n }\n \n /**\n * Returns the arity of this expression.\n * @return this.arity\n */\n public abstract int arity();\n \n /**\n * Accepts the given visitor and returns the result.\n * @see kodkod.ast.Node#accept(kodkod.ast.visitor.ReturnVisitor)\n */\n public abstract <E, F, D, I> E accept(ReturnVisitor<E, F, D, I> visitor);\n }",
"public final class Variable extends LeafExpression {\n\n\t/**\n\t * Constructs a variable with the specified name and arity 1.\n\t * @ensures this.name' = name && this.arity' = 1\n\t */\n\tprivate Variable(String name) {\n\t\tsuper(name, 1);\n\t}\n\n\t/**\n\t * Constructs a variable with the specified name and arity.\n\t * @ensures this.name' = name && this.arity' = arity\n\t */\n\tprivate Variable(String name, int arity) {\n\t\tsuper(name, arity);\n\t}\n\n\t/**\n\t * Returns a new variable with the specified name and arity 1.\n\t * @ensures this.name' = name && this.arity' = 1\n\t */\n\tpublic static Variable unary(String name) {\n\t\treturn new Variable(name);\n\t}\n\n\t/**\n\t * Returns a new variable with the specified name and arity.\n\t * @ensures this.name' = name && this.arity' = arity\n\t * @throws IllegalArgumentException arity < 1\n\t */\n\tpublic static Variable nary(String name, int arity) {\n\t\treturn new Variable(name, arity);\n\t}\n\n\t/**\n\t * Returns the declaration that constrains this variable to \n\t * be bound to at most one element of the given expression: 'this: lone expr'.\n\t * @return {d: Decl | d.variable = this && d.multiplicity = LONE && d.expression = expr }\n\t * @throws NullPointerException expr = null\n\t * @throws IllegalArgumentException this.arity != expr.arity || expr.arity != 1\n\t */\n\tpublic Decl loneOf(Expression expr) {\n\t\treturn new Decl(this, Multiplicity.LONE, expr);\n\t}\n\n\t/**\n\t * Returns the declaration that constrains this variable to \n\t * be bound to exactly one element of the given expression: 'this: one expr'.\n\t * @return {d: Decl | d.variable = this && d.multiplicity = ONE && d.expression = expr }\n\t * @throws NullPointerException expr = null\n\t * @throws IllegalArgumentException this.arity != expr.arity || expr.arity != 1\n\t */\n\tpublic Decl oneOf(Expression expr) {\n\t\treturn new Decl(this, Multiplicity.ONE, expr);\n\t}\n\n\t/**\n\t * Returns the declaration that constrains this variable to \n\t * be bound to at least one element of the given expression: 'this: some expr'.\n\t * @return {d: Decl | d.variable = this && d.multiplicity = SOME && d.expression = expr }\n\t * @throws NullPointerException expr = null\n\t * @throws IllegalArgumentException this.arity != expr.arity || expr.arity != 1\n\t */\n\tpublic Decl someOf(Expression expr) {\n\t\treturn new Decl(this, Multiplicity.SOME, expr);\n\t}\n\n\t/**\n\t * Returns the declaration that constrains this variable to \n\t * be bound to a subset of the elements in the given expression: 'this: set expr'.\n\t * @return {d: Decl | d.variable = this && d.multiplicity = SET && d.expression = expr }\n\t * @throws NullPointerException expr = null\n\t * @throws IllegalArgumentException this.arity != expr.arity \n\t */\n\tpublic Decl setOf(Expression expr) {\n\t\treturn new Decl(this, Multiplicity.SET, expr);\n\t}\n\n\t/**\n\t * Returns the declaration that constrains this variable to \n\t * be bound to the specified number of the elements in the given expression: 'this: mult expr'.\n\t * @return {d: Decl | d.variable = this && d.multiplicity = mult && d.expression = expr }\n\t * @throws NullPointerException expression = null || mult = null\n\t * @throws IllegalArgumentException mult = NO\n\t * @throws IllegalArgumentException mult in ONE + LONE + SOME && expr.arity != 1\n\t * @throws IllegalArgumentException this.arity != expr.arity\n\t */\n\tpublic Decl declare(Multiplicity mult, Expression expr) {\n\t\treturn new Decl(this, mult, expr);\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t * @see kodkod.ast.Expression#accept(kodkod.ast.visitor.ReturnVisitor)\n\t */\n\tpublic <E, F, D, I> E accept(ReturnVisitor<E, F, D, I> visitor) {\n\t\treturn visitor.visit(this);\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t * @see kodkod.ast.Node#accept(kodkod.ast.visitor.VoidVisitor)\n\t */\n\tpublic void accept(VoidVisitor visitor) {\n\t\tvisitor.visit(this);\n\t}\n\n}",
"public final class Solution {\n\tprivate final Outcome outcome;\n\tprivate final Statistics stats;\n\tprivate final Instance instance;\n\tprivate final Proof proof;\n\n\t\n\t/**\n\t * Constructs a Solution from the given values.\n\t * @requires outcome != null && stats != null\n\t * @requires outcome = SATISFIABLE || TRIVIALLY_SATISFIABLE => instance != null\n\t */\n\tprivate Solution(Outcome outcome, Statistics stats, Instance instance, Proof proof) {\n\t\tassert outcome != null && stats != null;\n\t\tthis.outcome = outcome;\n\t\tthis.stats = stats;\n\t\tthis.instance = instance;\n\t\tthis.proof = proof;\n\t}\n\t\n\t/**\n\t * Returns a new Solution with a SATISFIABLE outcome, given stats and instance.\n\t * @return {s: Solution | s.outcome() = SATISFIABLE && s.stats() = stats && s.instance() = instance }\n\t */\n\tstatic Solution satisfiable(Statistics stats, Instance instance) {\n\t\treturn new Solution(Outcome.SATISFIABLE, stats, instance, null);\n\t}\n\t\n\t/**\n\t * Returns a new Solution with a TRIVIALLY_SATISFIABLE outcome, given stats and instance.\n\t * @return {s: Solution | s.outcome() = TRIVIALLY_SATISFIABLE && s.stats() = stats && s.instance() = instance }\n\t */\n\tstatic Solution triviallySatisfiable(Statistics stats, Instance instance) {\n\t\treturn new Solution(Outcome.TRIVIALLY_SATISFIABLE, stats, instance, null);\n\t}\n\t\n\t/**\n\t * Returns a new Solution with a UNSATISFIABLE outcome, given stats and proof.\n\t * @return {s: Solution | s.outcome() = UNSATISFIABLE && s.stats() = stats && s.proof() = proof }\n\t */\n\tstatic Solution unsatisfiable(Statistics stats, Proof proof) {\n\t\treturn new Solution(Outcome.UNSATISFIABLE, stats, null, proof);\n\t}\n\t\n\t/**\n\t * Returns a new Solution with a TRIVIALLY_UNSATISFIABLE outcome, given stats and proof.\n\t * @return {s: Solution | s.outcome() = TRIVIALLY_UNSATISFIABLE && s.stats() = stats && s.proof() = proof }\n\t */\n\tstatic Solution triviallyUnsatisfiable(Statistics stats, Proof proof) {\n\t\treturn new Solution(Outcome.TRIVIALLY_UNSATISFIABLE, stats, null, proof);\n\t}\n\t\t\n\t/**\n\t * Returns the outcome of the attempt to find\n\t * a model for this.formula. If the outcome is \n\t * SATISFIABLE or TRIVIALLY_SATISFIABLE, a satisfying \n\t * instance can be obtained by calling {@link #instance()}.\n\t * If the formula is UNSATISFIABLE, a proof of unsatisfiability\n\t * can be obtained by calling {@link #proof()} provided that\n\t * translation logging was enabled and the unsatisfiability was\n\t * determined using a core extracting \n\t * {@link kodkod.engine.satlab.SATSolver sat solver}.\n\t * Lastly, if the returned Outcome is\n\t * or TRIVIALLY_UNSATISFIABLE, a proof of unsatisfiability can\n\t * be obtained by calling {@link #proof()} provided that\n\t * translation logging was enabled.\n\t * @return an Outcome instance designating the \n\t * satisfiability of this.formula with respect to this.bounds\n\t */\n\tpublic Outcome outcome() {\n\t\treturn outcome;\n\t}\n\t\n\t/**\n\t * Returns true iff this solution has a (trivially) satisfiable outcome.\n\t * @return this.outcome = Outcome.SATISFIABLE || this.outcome = Outcome.TRIVIALLY_SATISFIABLE\n\t */\n\tpublic final boolean sat() {\n\t\treturn outcome==Outcome.SATISFIABLE || outcome==Outcome.TRIVIALLY_SATISFIABLE;\n\t}\n\t\n\t/**\n\t * Returns true iff this solution has a (trivially) unsatisfiable outcome.\n\t * @return this.outcome = Outcome.UNSATISFIABLE || this.outcome = Outcome.TRIVIALLY_UNSATISFIABLE\n\t */\n\tpublic final boolean unsat() {\n\t\treturn outcome==Outcome.UNSATISFIABLE || outcome==Outcome.TRIVIALLY_UNSATISFIABLE;\n\t}\n\t\n\t/**\n\t * Returns a satisfiying instance for this.formula, if the\n\t * value returned by {@link #outcome() this.outcome()} is either\n\t * SATISFIABLE or TRIVIALLY_SATISFIABLE. Otherwise returns null.\n\t * @return a satisfying instance for this.formula, if one exists.\n\t */\n\tpublic Instance instance() {\n\t\treturn instance;\n\t}\n\n\t/**\n\t * Returns a proof of this.formula's unsatisfiability if the value \n\t * returned by {@link #outcome() this.outcome()} is UNSATISFIABLE or\n\t * TRIVIALLY_UNSATISFIABLE, translation logging was enabled during solving, \n\t * and a core extracting {@link kodkod.engine.satlab.SATProver sat solver} (if any)\n\t * was used to determine unsatisfiability.\n\t * Otherwise, null is returned. \n\t * @return a proof of this.formula's unsatisfiability, if one is available.\n\t */\n\tpublic Proof proof() {\n\t\treturn proof;\n\t}\n\t\n\t/**\n\t * Returns the statistics gathered while solving\n\t * this.formula.\n\t * @return the statistics gathered while solving\n\t * this.formula.\n\t */\n\tpublic Statistics stats() {\n\t\treturn stats;\n\t}\n\t\n\t/**\n\t * Returns a string representation of this Solution.\n\t * @return a string representation of this Solution.\n\t */\n\tpublic String toString() {\n\t\tfinal StringBuilder b = new StringBuilder();\n\t\tb.append(\"---OUTCOME---\\n\");\n\t\tb.append(outcome);\n\t\tb.append(\"\\n\");\n\t\tif (instance!=null) {\n\t\t\tb.append(\"\\n---INSTANCE---\\n\");\n\t\t\tb.append(instance);\n\t\t\tb.append(\"\\n\");\n\t\t}\n\t\tif (proof!=null) {\n\t\t\tb.append(\"\\n---PROOF---\\n\");\n\t\t\tb.append(proof);\n\t\t\tb.append(\"\\n\");\n\t\t}\n\t\tb.append(\"\\n---STATS---\\n\");\n\t\tb.append(stats);\n\t\tb.append(\"\\n\");\n\t\treturn b.toString();\n\t}\n\t\n\t/**\n\t * Enumerates the possible outcomes of an attempt\n\t * to find a model for a FOL formula.\n\t */\n\tpublic static enum Outcome {\n\t\t/** The formula is satisfiable with respect to the specified bounds. */\n\t\tSATISFIABLE,\n\t\t/** The formula is unsatisfiable with respect to the specified bounds. */\n\t\tUNSATISFIABLE,\n\t\t/** \n\t\t * The formula is trivially satisfiable with respect to the specified bounds: \n\t\t * a series of simple transformations reduces the formula to the constant TRUE. \n\t\t **/\n\t\tTRIVIALLY_SATISFIABLE,\n\t\t/**\n\t\t * The formula is trivially unsatisfiable with respect to the specified bounds:\n\t\t * a series of simple transformations reduces the formula to the constant FALSE. \n\t\t */\n\t\tTRIVIALLY_UNSATISFIABLE;\n\t\t\n\t}\n\t\n}",
"public final class Solver implements KodkodSolver {\n\tprivate final Options options;\n\n\t/**\n\t * Constructs a new Solver with the default options.\n\t * @ensures this.options' = new Options()\n\t */\n\tpublic Solver() {\n\t\tthis.options = new Options();\n\t}\n\n\t/**\n\t * Constructs a new Solver with the given options.\n\t * @ensures this.options' = options\n\t * @throws NullPointerException options = null\n\t */\n\tpublic Solver(Options options) {\n\t\tif (options == null)\n\t\t\tthrow new NullPointerException();\n\t\tthis.options = options;\n\t}\n\n\t/**\n\t * Returns the Options object used by this Solver\n\t * to guide translation of formulas from first-order\n\t * logic to cnf.\n\t * @return this.options\n\t */\n\tpublic Options options() {\n\t\treturn options;\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t * @see kodkod.engine.KodkodSolver#free()\n\t */\n\tpublic void free() {}\n\t\n\t/**\n\t * Attempts to satisfy the given {@code formula} and {@code bounds} with respect to \n\t * {@code this.options} or, optionally, prove the problem's unsatisfiability. If the method \n\t * completes normally, the result is a {@linkplain Solution solution} containing either an \n\t * {@linkplain Instance instance} of the given problem or, optionally, a {@linkplain Proof proof} of \n\t * its unsatisfiability. An unsatisfiability\n\t * proof will be constructed iff {@code this.options.solver} specifies a {@linkplain SATProver} and \n\t * {@code this.options.logTranslation > 0}.\n\t * \n\t * @return some sol: {@link Solution} | \n\t * some sol.instance() => \n\t * sol.instance() in MODELS(formula, bounds, this.options) else \n\t * UNSAT(formula, bound, this.options) \n\t * \n\t * @throws NullPointerException formula = null || bounds = null\n\t * @throws UnboundLeafException the formula contains an undeclared variable or a relation not mapped by the given bounds\n\t * @throws HigherOrderDeclException the formula contains a higher order declaration that cannot\n\t * be skolemized, or it can be skolemized but {@code this.options.skolemDepth} is insufficiently large\n\t * @throws AbortedException this solving task was aborted \n\t * @see Options\n\t * @see Solution\n\t * @see Instance\n\t * @see Proof\n\t */\n\tpublic Solution solve(Formula formula, Bounds bounds) throws HigherOrderDeclException, UnboundLeafException, AbortedException {\n\t\t\n\t\tfinal long startTransl = System.currentTimeMillis();\n\t\t\n\t\ttry {\t\t\t\n\t\t\tfinal Translation.Whole translation = Translator.translate(formula, bounds, options);\n\t\t\tfinal long endTransl = System.currentTimeMillis();\n\t\t\t\n\t\t\tif (translation.trivial())\n\t\t\t\treturn trivial(translation, endTransl - startTransl);\n\n\t\t\tfinal SATSolver cnf = translation.cnf();\n\t\t\t\n\t\t\toptions.reporter().solvingCNF(translation.numPrimaryVariables(), cnf.numberOfVariables(), cnf.numberOfClauses());\n\t\t\tfinal long startSolve = System.currentTimeMillis();\n\t\t\tfinal boolean isSat = cnf.solve();\n\t\t\tfinal long endSolve = System.currentTimeMillis();\n\n\t\t\tfinal Statistics stats = new Statistics(translation, endTransl - startTransl, endSolve - startSolve);\n\t\t\treturn isSat ? sat(translation, stats) : unsat(translation, stats);\n\t\t\t\n\t\t} catch (SATAbortedException sae) {\n\t\t\tthrow new AbortedException(sae);\n\t\t}\n\t}\n\t\n\t/**\n\t * Attempts to find all solutions to the given formula with respect to the specified bounds or\n\t * to prove the formula's unsatisfiability.\n\t * If the operation is successful, the method returns an iterator over n Solution objects. The outcome\n\t * of the first n-1 solutions is SAT or trivially SAT, and the outcome of the nth solution is UNSAT\n\t * or trivially UNSAT. Note that an unsatisfiability\n\t * proof will be constructed for the last solution iff this.options specifies the use of a core extracting SATSolver.\n\t * Additionally, the CNF variables in the proof can be related back to the nodes in the given formula \n\t * iff this.options has variable tracking enabled. Translation logging also requires that \n\t * there are no subnodes in the given formula that are both syntactically shared and contain free variables. \n\t * \n\t * @return an iterator over all the Solutions to the formula with respect to the given bounds\n\t * @throws NullPointerException formula = null || bounds = null\n\t * @throws kodkod.engine.fol2sat.UnboundLeafException the formula contains an undeclared variable or\n\t * a relation not mapped by the given bounds\n\t * @throws kodkod.engine.fol2sat.HigherOrderDeclException the formula contains a higher order declaration that cannot\n\t * be skolemized, or it can be skolemized but this.options.skolemize is false.\n\t * @throws AbortedException this solving task was interrupted with a call to Thread.interrupt on this thread\n\t * @throws IllegalStateException !this.options.solver().incremental()\n\t * @see Solution\n\t * @see Options\n\t * @see Proof\n\t */\n\tpublic Iterator<Solution> solveAll(final Formula formula, final Bounds bounds) \n\t\tthrows HigherOrderDeclException, UnboundLeafException, AbortedException {\n\t\t\n\t\tif (!options.solver().incremental())\n\t\t\tthrow new IllegalArgumentException(\"cannot enumerate solutions without an incremental solver.\");\n\t\t\n\t\treturn new SolutionIterator(formula, bounds, options);\n\t\t\n\t}\n\n\t/**\n\t * {@inheritDoc}\n\t * @see java.lang.Object#toString()\n\t */\n\tpublic String toString() {\n\t\treturn options.toString();\n\t}\n\t\n\t/**\n\t * Returns the result of solving a sat formula.\n\t * @param bounds Bounds with which solve() was called\n\t * @param translation the translation\n\t * @param stats translation / solving stats\n\t * @return the result of solving a sat formula.\n\t */\n\tprivate static Solution sat(Translation.Whole translation, Statistics stats) {\n\t\tfinal Solution sol = Solution.satisfiable(stats, translation.interpret());\n\t\ttranslation.cnf().free();\n\t\treturn sol;\n\t}\n\n\t/**\n\t * Returns the result of solving an unsat formula.\n\t * @param translation the translation \n\t * @param stats translation / solving stats\n\t * @return the result of solving an unsat formula.\n\t */\n\tprivate static Solution unsat(Translation.Whole translation, Statistics stats) {\n\t\tfinal SATSolver cnf = translation.cnf();\n\t\tfinal TranslationLog log = translation.log();\n\t\tif (cnf instanceof SATProver && log != null) {\n\t\t\treturn Solution.unsatisfiable(stats, new ResolutionBasedProof((SATProver) cnf, log));\n\t\t} else { // can free memory\n\t\t\tfinal Solution sol = Solution.unsatisfiable(stats, null);\n\t\t\tcnf.free();\n\t\t\treturn sol;\n\t\t}\n\t}\n\t\n\t/**\n\t * Returns the result of solving a trivially (un)sat formula.\n\t * @param translation trivial translation produced as the result of {@code translation.formula} \n\t * simplifying to a constant with respect to {@code translation.bounds}\n\t * @param translTime translation time\n\t * @return the result of solving a trivially (un)sat formula.\n\t */\n\tprivate static Solution trivial(Translation.Whole translation, long translTime) {\n\t\tfinal Statistics stats = new Statistics(0, 0, 0, translTime, 0);\n\t\tfinal Solution sol;\n\t\tif (translation.cnf().solve()) {\n\t\t\tsol = Solution.triviallySatisfiable(stats, translation.interpret());\n\t\t} else {\n\t\t\tsol = Solution.triviallyUnsatisfiable(stats, trivialProof(translation.log()));\n\t\t}\n\t\ttranslation.cnf().free();\n\t\treturn sol;\n\t}\n\t\n\t/**\n\t * Returns a proof for the trivially unsatisfiable log.formula,\n\t * provided that log is non-null. Otherwise returns null.\n\t * @requires log != null => log.formula is trivially unsatisfiable\n\t * @return a proof for the trivially unsatisfiable log.formula,\n\t * provided that log is non-null. Otherwise returns null.\n\t */\n\tprivate static Proof trivialProof(TranslationLog log) {\n\t\treturn log==null ? null : new TrivialProof(log);\n\t}\n\t\t\n\t/**\n\t * An iterator over all solutions of a model.\n\t * @author Emina Torlak\n\t */\n\tprivate static final class SolutionIterator implements Iterator<Solution> {\n\t\tprivate Translation.Whole translation;\n\t\tprivate long translTime;\n\t\tprivate int trivial;\n\t\t\n\t\t/**\n\t\t * Constructs a solution iterator for the given formula, bounds, and options.\n\t\t */\n\t\tSolutionIterator(Formula formula, Bounds bounds, Options options) {\n\t\t\tthis.translTime = System.currentTimeMillis();\n\t\t\tthis.translation = Translator.translate(formula, bounds, options);\n\t\t\tthis.translTime = System.currentTimeMillis() - translTime;\n\t\t\tthis.trivial = 0;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Returns true if there is another solution.\n\t\t * @see java.util.Iterator#hasNext()\n\t\t */\n\t\tpublic boolean hasNext() { return translation != null; }\n\t\t\n\t\t/**\n\t\t * Returns the next solution if any.\n\t\t * @see java.util.Iterator#next()\n\t\t */\n\t\tpublic Solution next() {\n\t\t\tif (!hasNext()) throw new NoSuchElementException();\t\t\t\n\t\t\ttry {\n\t\t\t\treturn translation.trivial() ? nextTrivialSolution() : nextNonTrivialSolution();\n\t\t\t} catch (SATAbortedException sae) {\n\t\t\t\ttranslation.cnf().free();\n\t\t\t\tthrow new AbortedException(sae);\n\t\t\t}\n\t\t}\n\n\t\t/** @throws UnsupportedOperationException */\n\t\tpublic void remove() { throw new UnsupportedOperationException(); }\n\t\t\n\t\t/**\n\t\t * Solves {@code translation.cnf} and adds the negation of the\n\t\t * found model to the set of clauses. The latter has the \n\t\t * effect of forcing the solver to come up with the next solution\n\t\t * or return UNSAT. If {@code this.translation.cnf.solve()} is false, \n\t\t * sets {@code this.translation} to null.\n\t\t * @requires this.translation != null\n\t\t * @ensures this.translation.cnf is modified to eliminate\n\t\t * the current solution from the set of possible solutions\n\t\t * @return current solution\n\t\t */\n\t\tprivate Solution nextNonTrivialSolution() {\n\t\t\tfinal Translation.Whole transl = translation;\n\t\t\t\n\t\t\tfinal SATSolver cnf = transl.cnf();\n\t\t\tfinal int primaryVars = transl.numPrimaryVariables();\n\t\t\t\n\t\t\ttransl.options().reporter().solvingCNF(primaryVars, cnf.numberOfVariables(), cnf.numberOfClauses());\n\t\t\t\n\t\t\tfinal long startSolve = System.currentTimeMillis();\n\t\t\tfinal boolean isSat = cnf.solve();\n\t\t\tfinal long endSolve = System.currentTimeMillis();\n\n\t\t\tfinal Statistics stats = new Statistics(transl, translTime, endSolve - startSolve);\n\t\t\tfinal Solution sol;\n\t\t\t\n\t\t\tif (isSat) {\t\t\t\n\t\t\t\t// extract the current solution; can't use the sat(..) method because it frees the sat solver\n\t\t\t\tsol = Solution.satisfiable(stats, transl.interpret());\n\t\t\t\t// add the negation of the current model to the solver\n\t\t\t\tfinal int[] notModel = new int[primaryVars];\n\t\t\t\tfor(int i = 1; i <= primaryVars; i++) {\n\t\t\t\t\tnotModel[i-1] = cnf.valueOf(i) ? -i : i;\n\t\t\t\t}\n\t\t\t\tcnf.addClause(notModel);\n\t\t\t} else {\n\t\t\t\tsol = unsat(transl, stats); // this also frees up solver resources, if any\n\t\t\t\ttranslation = null; // unsat, no more solutions\n\t\t\t}\n\t\t\treturn sol;\n\t\t}\n\t\t\n\t\t/**\n\t\t * Returns the trivial solution corresponding to the trivial translation stored in {@code this.translation},\n\t\t * and if {@code this.translation.cnf.solve()} is true, sets {@code this.translation} to a new translation \n\t\t * that eliminates the current trivial solution from the set of possible solutions. The latter has the effect \n\t\t * of forcing either the translator or the solver to come up with the next solution or return UNSAT.\n\t\t * If {@code this.translation.cnf.solve()} is false, sets {@code this.translation} to null.\n\t\t * @requires this.translation != null\n\t\t * @ensures this.translation is modified to eliminate the current trivial solution from the set of possible solutions\n\t\t * @return current solution\n\t\t */\n\t\tprivate Solution nextTrivialSolution() {\n\t\t\tfinal Translation.Whole transl = this.translation;\n\t\t\t\n\t\t\tfinal Solution sol = trivial(transl, translTime); // this also frees up solver resources, if unsat\n\t\t\t\n\t\t\tif (sol.instance()==null) {\n\t\t\t\ttranslation = null; // unsat, no more solutions\n\t\t\t} else {\n\t\t\t\ttrivial++;\n\t\t\t\t\n\t\t\t\tfinal Bounds bounds = transl.bounds();\n\t\t\t\tfinal Bounds newBounds = bounds.clone();\n\t\t\t\tfinal List<Formula> changes = new ArrayList<Formula>();\n\n\t\t\t\tfor(Relation r : bounds.relations()) {\n\t\t\t\t\tfinal TupleSet lower = bounds.lowerBound(r); \n\t\t\t\t\t\n\t\t\t\t\tif (lower != bounds.upperBound(r)) { // r may change\n\t\t\t\t\t\tif (lower.isEmpty()) { \n\t\t\t\t\t\t\tchanges.add(r.some());\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tfinal Relation rmodel = Relation.nary(r.name()+\"_\"+trivial, r.arity());\n\t\t\t\t\t\t\tnewBounds.boundExactly(rmodel, lower);\t\n\t\t\t\t\t\t\tchanges.add(r.eq(rmodel).not());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// nothing can change => there can be no more solutions (besides the current trivial one).\n\t\t\t\t// note that transl.formula simplifies to the constant true with respect to \n\t\t\t\t// transl.bounds, and that newBounds is a superset of transl.bounds.\n\t\t\t\t// as a result, finding the next instance, if any, for transl.formula.and(Formula.or(changes)) \n\t\t\t\t// with respect to newBounds is equivalent to finding the next instance of Formula.or(changes) alone.\n\t\t\t\tfinal Formula formula = changes.isEmpty() ? Formula.FALSE : Formula.or(changes);\n\t\t\t\t\n\t\t\t\tfinal long startTransl = System.currentTimeMillis();\n\t\t\t\ttranslation = Translator.translate(formula, newBounds, transl.options());\n\t\t\t\ttranslTime += System.currentTimeMillis() - startTransl;\n\t\t\t} \n\t\t\treturn sol;\n\t\t}\n\t\t\n\t}\n}",
"public abstract class SATFactory {\n\t\n\t/**\n\t * Constructs a new instance of SATFactory.\n\t */\n\tprotected SATFactory() {}\n\t\n\t/**\n\t * Returns true iff the given factory generates solvers that \n\t * are available for use on this system.\n\t * @return true iff the given factory generates solvers that \n\t * are available for use on this system.\n\t */\n\tpublic static final boolean available(SATFactory factory) {\n\t\tSATSolver solver = null;\n\t\ttry {\n\t\t\tsolver = factory.instance();\n\t\t\tsolver.addVariables(1);\n\t\t\tsolver.addClause(new int[]{1});\n\t\t\treturn solver.solve();\n\t\t} catch (RuntimeException|UnsatisfiedLinkError t) {\t\n\t\t\treturn false;\n\t\t} finally {\n\t\t\tif (solver!=null) {\n\t\t\t\tsolver.free();\n\t\t\t}\n\t\t}\n\t}\n\t\n\t/**\n\t * The factory that produces instances of the default sat4j solver.\n\t * @see org.sat4j.core.ASolverFactory#defaultSolver()\n\t */\n\tpublic static final SATFactory DefaultSAT4J = new SATFactory() { \n\t\tpublic SATSolver instance() { \n\t\t\treturn new SAT4J(SolverFactory.instance().defaultSolver()); \n\t\t}\n\t\tpublic String toString() { return \"DefaultSAT4J\"; }\n\t};\n\t\n\t/**\n\t * The factory that produces instances of the \"light\" sat4j solver. The\n\t * light solver is suitable for solving many small instances of SAT problems.\n\t * @see org.sat4j.core.ASolverFactory#lightSolver()\n\t */\n\tpublic static final SATFactory LightSAT4J = new SATFactory() {\n\t\tpublic SATSolver instance() { \n\t\t\treturn new SAT4J(SolverFactory.instance().lightSolver()); \n\t\t}\n\t\tpublic String toString() { return \"LightSAT4J\"; }\n\t};\n\t\n\t/**\n\t * The factory that produces instances of Niklas Eén and Niklas Sörensson's\n\t * MiniSat solver.\n\t */\n\tpublic static final SATFactory MiniSat = new SATFactory() {\n\t\tpublic SATSolver instance() {\n\t\t\treturn new MiniSat();\n\t\t}\n\t\tpublic String toString() { return \"MiniSat\"; }\n\t};\n\t\n\t/**\n\t * The factory the produces {@link SATProver proof logging} \n\t * instances of the MiniSat solver. Note that core\n\t * extraction can incur a significant time overhead during solving,\n\t * so if you do not need this functionality, use the {@link #MiniSat} factory\n\t * instead.\n\t */\n\tpublic static final SATFactory MiniSatProver = new SATFactory() {\n\t\tpublic SATSolver instance() { \n\t\t\treturn new MiniSatProver(); \n\t\t}\n\t\t@Override\n\t\tpublic boolean prover() { return true; }\n\t\tpublic String toString() { return \"MiniSatProver\"; }\n\t};\n\t\n\t/**\n\t * The factory that produces instances of Gilles Audemard and Laurent Simon's \n\t * Glucose solver.\n\t */\n\tpublic static final SATFactory Glucose = new SATFactory() {\n\t\tpublic SATSolver instance() {\n\t\t\treturn new Glucose();\n\t\t}\n\t\tpublic String toString() { return \"Glucose\"; }\n\t};\n\t\n\t/**\n\t * The factory that produces instances of Armin Biere's\n\t * Lingeling solver.\n\t */\n\tpublic static final SATFactory Lingeling = new SATFactory() {\n\t\tpublic SATSolver instance() {\n\t\t\treturn new Lingeling();\n\t\t}\n\t\tpublic boolean incremental() { return false; }\n\t\tpublic String toString() { return \"Lingeling\"; }\n\t};\n\t\n\t/**\n\t * Returns a SATFactory that produces SATSolver wrappers for Armin Biere's Plingeling\n\t * solver. This is a parallel solver that is invoked as an external program rather than \n\t * via the Java Native Interface. As a result, it cannot be used incrementally. Its\n\t * external factory manages the creation and deletion of temporary files automatically.\n\t * A statically compiled version of plingeling is assumed to be available in a\n\t * java.library.path directory. The effect of this method is the same as calling\n\t * {@link #plingeling(Integer, Boolean) plingeling(null, null)}.\n\t * @return SATFactory that produces SATSolver wrappers for the Plingeling solver\n\t */\n\tpublic static final SATFactory plingeling() {\n\t\treturn plingeling(null, null);\n\t}\n\t\n\t/**\n\t * Returns a SATFactory that produces SATSolver wrappers for Armin Biere's Plingeling\n\t * solver. This is a parallel solver that is invoked as an external program rather than \n\t * via the Java Native Interface. As a result, it cannot be used incrementally. Its\n\t * external factory manages the creation and deletion of temporary files automatically.\n\t * A statically compiled version of plingeling is assumed to be available in a\n\t * java.library.path directory. \n\t * \n\t * <p>Plingling takes as input two optional parameters: {@code threads}, specifying how\n\t * many worker threads to use, and {@code portfolio}, specifying whether the threads should\n\t * run in portfolio mode (no sharing of clauses) or sharing mode. If {@code threads}\n\t * is null, the solver uses one worker per core. If {@code portfolio} is null, it is set to \n\t * true by default.</p>\n\t * \n\t * @requires threads != null => numberOfThreads > 0\n\t * \n\t * @return SATFactory that produces SATSolver wrappers for the Plingeling solver\n\t */\n\tpublic static final SATFactory plingeling(Integer threads, Boolean portfolio) {\n\t\t\n\t\tfinal List<String> opts = new ArrayList<String>(3);\n\t\tif (threads!=null) {\n\t\t\tif (threads < 1)\n\t\t\t\tthrow new IllegalArgumentException(\"Number of threads must be at least 1: numberOfThreads=\" + threads);\n\t\t\topts.add(\"-t\");\n\t\t\topts.add(threads.toString());\n\t\t}\n\t\tif (portfolio!=null && portfolio)\n\t\t\topts.add(\"-p\");\n\t\t\n\t\tfinal String executable = findStaticLibrary(\"plingeling\");\n\t\treturn externalFactory(executable==null ? \"plingeling\" : executable, \n\t\t\t\tnull, opts.toArray(new String[opts.size()]));\n\t\n\t}\n\t\n\t/**\n\t * Searches the {@code java.library.path} for an executable with the given name. Returns a fully \n\t * qualified path to the first found executable. Otherwise returns null.\n\t * @return a fully qualified path to an executable with the given name, or null if no executable \n\t * is found.\n\t */\n\tprivate static String findStaticLibrary(String name) { \n\t\tfinal String[] dirs = System.getProperty(\"java.library.path\").split(System.getProperty(\"path.separator\"));\n\t\t\n\t\tfor(int i = dirs.length-1; i >= 0; i--) {\n\t\t\tfinal File file = new File(dirs[i]+File.separator+name);\n\t\t\tif (file.canExecute())\n\t\t\t\treturn file.getAbsolutePath();\n\t\t}\n\t\t\n\t\treturn null;\n\t}\n\t\n\t/**\n\t * Returns a SATFactory that produces instances of the specified\n\t * SAT4J solver. For the list of available SAT4J solvers see\n\t * {@link org.sat4j.core.ASolverFactory#solverNames() org.sat4j.core.ASolverFactory#solverNames()}.\n\t * @requires solverName is a valid solver name\n\t * @return a SATFactory that returns the instances of the specified\n\t * SAT4J solver\n\t * @see org.sat4j.core.ASolverFactory#solverNames()\n\t */\n\tpublic static final SATFactory sat4jFactory(final String solverName) {\n\t\treturn new SATFactory() {\n\t\t\t@Override\n\t\t\tpublic SATSolver instance() {\n\t\t\t\treturn new SAT4J(SolverFactory.instance().createSolverByName(solverName));\n\t\t\t}\n\t\t\tpublic String toString() { return solverName; }\n\t\t};\n\t}\n\t\n\t/**\n\t * Returns a SATFactory that produces SATSolver wrappers for the external\n\t * SAT solver specified by the executable parameter. The solver's input\n\t * and output formats must conform to the \n\t * <a href=\"http://www.satcompetition.org/2011/rules.pdf\">SAT competition standards</a>. The solver\n\t * will be called with the specified options, and it is expected to write properly formatted\n\t * output to standard out. If the {@code cnf} string is non-null, it will be \n\t * used as the file name for generated CNF files by all solver instances that the factory generates. \n\t * If {@code cnf} null, each solver instance will use an automatically generated temporary file, which \n\t * will be deleted when the solver instance is garbage-collected. The {@code cnf} file, if provided, is not \n\t * automatically deleted; it is the caller's responsibility to delete it when no longer needed. \n\t * External solvers are never incremental.\n\t * @return SATFactory that produces SATSolver wrappers for the specified external\n\t * SAT solver\n\t */\n\tpublic static final SATFactory externalFactory(final String executable, final String cnf, final String... options) {\n\t\treturn new SATFactory() {\n\n\t\t\t@Override\n\t\t\tpublic SATSolver instance() {\n\t\t\t\tif (cnf != null) {\n\t\t\t\t\treturn new ExternalSolver(executable, cnf, false, options);\n\t\t\t\t} else {\n\t\t\t\t\ttry {\n\t\t\t\t\t\treturn new ExternalSolver(executable, \n\t\t\t\t\t\t\t\tFile.createTempFile(\"kodkod\", String.valueOf(executable.hashCode())).getAbsolutePath(), \n\t\t\t\t\t\t\t\ttrue, options);\n\t\t\t\t\t} catch (IOException e) {\n\t\t\t\t\t\tthrow new SATAbortedException(\"Could not create a temporary file.\", e);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\t@Override\n\t\t\tpublic boolean incremental() {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\t\n\t\t\tpublic String toString() {\n\t\t\t\treturn (new File(executable)).getName();\n\t\t\t}\n\t\t};\n\t}\n\t\n\t\n\t/**\n\t * Returns an instance of a SATSolver produced by this factory.\n\t * @return a SATSolver instance\n\t */\n\tpublic abstract SATSolver instance();\n\t\n\t/**\n\t * Returns true if the solvers returned by this.instance() are\n\t * {@link SATProver SATProvers}. Otherwise returns false.\n\t * @return true if the solvers returned by this.instance() are\n\t * {@link SATProver SATProvers}. Otherwise returns false.\n\t */\n\tpublic boolean prover() {\n\t\treturn false;\n\t}\n\t\n\t/**\n\t * Returns true if the solvers returned by this.instance() are incremental;\n\t * i.e. if clauses/variables can be added to the solver between multiple\n\t * calls to solve().\n\t * @return true if the solvers returned by this.instance() are incremental\n\t */\n\tpublic boolean incremental() {\n\t\treturn true;\n\t}\n\n}",
"public final class Bounds implements Cloneable {\n\tprivate final TupleFactory factory;\n\tprivate final Map<Relation, TupleSet> lowers, uppers;\n\tprivate final SparseSequence<TupleSet> intbounds;\n\tprivate final Set<Relation> relations;\n\t\n\t/**\n\t * Constructs a Bounds object with the given factory and mappings.\n\t */\n\tprivate Bounds(TupleFactory factory, Map<Relation, TupleSet> lower, Map<Relation, TupleSet> upper, SparseSequence<TupleSet> intbounds) {\n\t\tthis.factory = factory;\n\t\tthis.lowers = lower;\n\t\tthis.uppers = upper;\n\t\tthis.intbounds = intbounds;\n\t\tthis.relations = relations(lowers, uppers);\n\t}\n\t\n\t/**\n\t * Constructs new Bounds over the given universe.\n\t * @ensures this.universe' = universe && no this.relations' && no this.intBound'\n\t * @throws NullPointerException universe = null\n\t */\n\tpublic Bounds(Universe universe) {\n\t\tthis.factory = universe.factory();\n\t\tthis.lowers = new LinkedHashMap<Relation, TupleSet>();\n\t\tthis.uppers = new LinkedHashMap<Relation, TupleSet>();\n\t\tthis.intbounds = new TreeSequence<TupleSet>();\n\t\tthis.relations = relations(lowers, uppers);\n\t}\n\t\n\t/**\n\t * Returns a set view of the relations mapped by the given lower/upper bounds.\n\t * @requires lowers.keySet().equals(uppers.keySet())\n\t * @return a set view of the relations mapped by the given lower/upper bounds\n\t */\n\tprivate static Set<Relation> relations(final Map<Relation, TupleSet> lowers, final Map<Relation, TupleSet> uppers) {\n\t\treturn new AbstractSet<Relation>() {\n\n\t\t\tpublic Iterator<Relation> iterator() {\n\t\t\t\treturn new Iterator<Relation>() {\n\t\t\t\t\tfinal Iterator<Relation> itr = uppers.keySet().iterator();\n\t\t\t\t\tRelation last = null;\n\t\t\t\t\tpublic boolean hasNext() { return itr.hasNext(); }\n\t\t\t\t\tpublic Relation next() { return last = itr.next(); }\n\t\t\t\t\tpublic void remove() {\n\t\t\t\t\t\titr.remove();\n\t\t\t\t\t\tlowers.remove(last);\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tpublic int size() { return uppers.size(); }\t\t\t\n\t\t\tpublic boolean contains(Object key) { return uppers.containsKey(key); }\n\t\t\t\n\t\t\tpublic boolean remove(Object key) { \n\t\t\t\treturn (uppers.remove(key) != null) && (lowers.remove(key) != null); \n\t\t\t}\n\t\t\tpublic boolean removeAll(Collection<?> c) {\n\t\t\t\treturn uppers.keySet().removeAll(c) && lowers.keySet().removeAll(c);\n\t\t\t}\n\t\t\tpublic boolean retainAll(Collection<?> c) {\n\t\t\t\treturn uppers.keySet().retainAll(c) && lowers.keySet().retainAll(c);\n\t\t\t}\n\t\t};\n\t}\n\t\n\t/**\n\t * Returns this.universe.\n\t * @return this.universe\n\t */\n\tpublic Universe universe() { return factory.universe(); }\n\n\t/**\n\t * Returns the set of all relations bound by this Bounds.\n\t * The returned set does not support the add operation.\n\t * It supports removal iff this is not an unmodifiable Bounds.\n\t * @return this.relations\n\t */\n\tpublic Set<Relation> relations() { \n\t\treturn relations; \n\t}\n\t\n\t/**\n\t * Returns the set of all integers bound by this Bounds.\n\t * The returned set does not support the add operation.\n\t * It supports removal iff this is not an unmodifiable Bounds.\n\t * @return this.intBounds.TupleSet\n\t */\n\tpublic IntSet ints() {\n\t\treturn intbounds.indices();\n\t}\n\t\n\t/**\n\t * Returns the set of tuples that r must contain (the lower bound on r's contents).\n\t * If r is not mapped by this, null is returned.\n\t * @return r in this.relations => lowerBound[r], null\n\t */\n\tpublic TupleSet lowerBound(Relation r) {\n\t\treturn lowers.get(r);\n\t}\n\t\n\t/**\n\t * Returns a map view of this.lowerBound. The returned map is not modifiable.\n\t * @return a map view of this.lowerBound\n\t */\n\tpublic Map<Relation, TupleSet> lowerBounds() {\n\t\treturn unmodifiableMap(lowers);\n\t}\n\t\n\t/**\n\t * Returns the set of tuples that r may contain (the upper bound on r's contents).\n\t * If r is not mapped by this, null is returned.\n\t * @return r in this.relations => upperBound[r], null\n\t */\n\tpublic TupleSet upperBound(Relation r) {\n\t\treturn uppers.get(r);\n\t}\n\t\n\t/**\n\t * Returns a map view of this.upperBound. The returned map is not modifiable.\n\t * @return a map view of this.upperBound\n\t */\n\tpublic Map<Relation, TupleSet> upperBounds() {\n\t\treturn unmodifiableMap(uppers);\n\t}\n\t\n\t/**\n\t * Returns the set of tuples representing the given integer. If i is not\n\t * mapped by this, null is returned.\n\t * @return this.intBound[i]\n\t */\n\tpublic TupleSet exactBound(int i) {\n\t\treturn intbounds.get(i);\n\t}\n\t\n\t/**\n\t * Returns a sparse sequence view of this.intBound. The returned sequence\n\t * is not modifiable.\n\t * @return a sparse sequence view of this.intBound\n\t */\n\tpublic SparseSequence<TupleSet> intBounds() {\n\t\treturn unmodifiableSequence(intbounds);\n\t}\n\t\n\t/**\n\t * @throws IllegalArgumentException arity != bound.arity\n\t * @throws IllegalArgumentException bound.universe != this.universe\n\t */\n\tprivate void checkBound(int arity, TupleSet bound) {\n\t\tif (arity != bound.arity())\n\t\t\tthrow new IllegalArgumentException(\"bound.arity != r.arity\");\n\t\tif (!bound.universe().equals(factory.universe()))\n\t\t\tthrow new IllegalArgumentException(\"bound.universe != this.universe\");\t\n\t}\n\t\n\t/**\n\t * Sets both the lower and upper bounds of the given relation to \n\t * the given set of tuples. \n\t * \n\t * @requires tuples.arity = r.arity && tuples.universe = this.universe\n\t * @ensures this.relations' = this.relations + r \n\t * this.lowerBound' = this.lowerBound' ++ r->tuples &&\n\t * this.upperBound' = this.lowerBound' ++ r->tuples\n\t * @throws NullPointerException r = null || tuples = null \n\t * @throws IllegalArgumentException tuples.arity != r.arity || tuples.universe != this.universe\n\t */\n\tpublic void boundExactly(Relation r, TupleSet tuples) {\n\t\tcheckBound(r.arity(), tuples);\n\t\tfinal TupleSet unmodifiableTuplesCopy = tuples.clone().unmodifiableView();\n\t\tlowers.put(r, unmodifiableTuplesCopy);\n\t\tuppers.put(r, unmodifiableTuplesCopy);\n\t}\n\t\n\t/**\n\t * Sets the lower and upper bounds for the given relation. \n\t * \n\t * @requires lower.tuples in upper.tuples && lower.arity = upper.arity = r.arity &&\n\t * lower.universe = upper.universe = this.universe \n\t * @ensures this.relations' = this.relations + r &&\n\t * this.lowerBound' = this.lowerBound ++ r->lower &&\n\t * this.upperBound' = this.upperBound ++ r->upper\n\t * @throws NullPointerException r = null || lower = null || upper = null\n\t * @throws IllegalArgumentException lower.arity != r.arity || upper.arity != r.arity\n\t * @throws IllegalArgumentException lower.universe != this.universe || upper.universe != this.universe\n\t * @throws IllegalArgumentException lower.tuples !in upper.tuples \n\t */\n\tpublic void bound(Relation r, TupleSet lower, TupleSet upper) {\n\t\tif (!upper.containsAll(lower))\n\t\t\tthrow new IllegalArgumentException(\"lower.tuples !in upper.tuples\");\n\t\tif (upper.size()==lower.size()) { \n\t\t\t// upper.containsAll(lower) && upper.size()==lower.size() => upper.equals(lower)\n\t\t\tboundExactly(r, lower);\n\t\t} else {\n\t\t\tcheckBound(r.arity(), lower);\n\t\t\tcheckBound(r.arity(), upper);\t\t\n\t\t\tlowers.put(r, lower.clone().unmodifiableView());\n\t\t\tuppers.put(r, upper.clone().unmodifiableView());\n\t\t}\n\t}\n\t\n\t/**\n\t * Makes the specified tupleset the upper bound on the contents of the given relation. \n\t * The lower bound automatically become an empty tupleset with the same arity as\n\t * the relation. \n\t * \n\t * @requires upper.arity = r.arity && upper.universe = this.universe\n\t * @ensures this.relations' = this.relations + r \n\t * this.lowerBound' = this.lowerBound ++ r->{s: TupleSet | s.universe = this.universe && s.arity = r.arity && no s.tuples} && \n\t * this.upperBound' = this.upperBound ++ r->upper\n\t * @throws NullPointerException r = null || upper = null \n\t * @throws IllegalArgumentException upper.arity != r.arity || upper.universe != this.universe\n\t */\n\tpublic void bound(Relation r, TupleSet upper) {\n\t\tcheckBound(r.arity(), upper);\n\t\tlowers.put(r, factory.noneOf(r.arity()).unmodifiableView());\n\t\tuppers.put(r, upper.clone().unmodifiableView());\n\t}\n\t\n\t/**\n\t * Makes the specified tupleset an exact bound on the relational value\n\t * that corresponds to the given integer.\n\t * @requires ibound.arity = 1 && i.bound.size() = 1\n\t * @ensures this.intBound' = this.intBound' ++ i -> ibound\n\t * @throws NullPointerException ibound = null\n\t * @throws IllegalArgumentException ibound.arity != 1 || ibound.size() != 1\n\t * @throws IllegalArgumentException ibound.universe != this.universe\n\t */\n\tpublic void boundExactly(int i, TupleSet ibound) {\n\t\tcheckBound(1, ibound);\n\t\tif (ibound.size() != 1)\n\t\t\tthrow new IllegalArgumentException(\"ibound.size != 1: \" + ibound);\n\t\tintbounds.put(i, ibound.clone().unmodifiableView());\n\t}\n\t\n\n\t/**\n\t * Returns an unmodifiable view of this Bounds object.\n\t * @return an unmodifiable view of his Bounds object.\n\t */\n\tpublic Bounds unmodifiableView() {\n\t\treturn new Bounds(factory, unmodifiableMap(lowers), unmodifiableMap(uppers), unmodifiableSequence(intbounds));\n\t}\n\t\n\t/**\n\t * Returns a deep (modifiable) copy of this Bounds object.\n\t * @return a deep (modifiable) copy of this Bounds object.\n\t */\n\tpublic Bounds clone() {\n\t\ttry {\n\t\t\treturn new Bounds(factory, new LinkedHashMap<Relation, TupleSet>(lowers), \n\t\t\t\t\tnew LinkedHashMap<Relation, TupleSet>(uppers), intbounds.clone());\n\t\t} catch (CloneNotSupportedException cnse) {\n\t\t\tthrow new InternalError(); // should not be reached\n\t\t}\n\t}\n\t\n\t/**\n\t * @see java.lang.Object#toString()\n\t */\n\tpublic String toString() {\n\t\tfinal StringBuilder str = new StringBuilder();\n\t\tstr.append(\"relation bounds:\");\n\t\tfor(Map.Entry<Relation, TupleSet> entry: lowers.entrySet()) {\n\t\t\tstr.append(\"\\n \");\n\t\t\tstr.append(entry.getKey());\n\t\t\tstr.append(\": [\");\n\t\t\tstr.append(entry.getValue());\n\t\t\tTupleSet upper = uppers.get(entry.getKey());\n\t\t\tif (!upper.equals(entry.getValue())) {\n\t\t\t\tstr.append(\", \");\n\t\t\t\tstr.append(upper);\n\t\t\t} \n\t\t\tstr.append(\"]\");\n\t\t}\n\t\tstr.append(\"\\nint bounds: \");\n\t\tstr.append(\"\\n \");\n\t\tstr.append(intbounds);\n\t\treturn str.toString();\n\t}\n}"
] | import java.util.ArrayList;
import java.util.List;
import kodkod.ast.Expression;
import kodkod.ast.Formula;
import kodkod.ast.Relation;
import kodkod.ast.Variable;
import kodkod.engine.Solution;
import kodkod.engine.Solver;
import kodkod.engine.satlab.SATFactory;
import kodkod.instance.Bounds;
import kodkod.instance.TupleFactory;
import kodkod.instance.TupleSet;
import kodkod.instance.Universe; | package kodkod.examples.alloy;
/**
* KodKod encoding of the following leader election algorithm:
*
* <pre>
* module internal/ringElection
* open util/ordering[Time] as TO
* open util/ordering[Process] as PO
*
* sig Time {}
* sig Process {
* succ: Process,
* toSend: Process -> Time,
* elected: set Time }
*
* fact Ring {all p: Process | Process in p.^succ}
*
* pred init (t: Time) {all p: Process | p.toSend.t = p}
*
* pred step (t, t': Time, p: Process) {
* let from = p.toSend, to = p.succ.toSend |
* some id: from.t {
* from.t' = from.t - id
* to.t' = to.t + (id - PO/prevs(p.succ)) } }
*
* pred skip (t, t': Time, p: Process) {p.toSend.t = p.toSend.t'}
*
* fact Traces {
* init (TO/first ())
* all t: Time - TO/last() | let t' = TO/next (t) |
* all p: Process | step (t, t', p) or step (t, t', succ.p) or skip (t, t', p) }
*
* fact DefineElected {
* no elected.TO/first()
* all t: Time - TO/first()|
* elected.t = {p: Process | p in p.toSend.t - p.toSend.(TO/prev(t))} }
*
*
* pred progress () {
* all t: Time - TO/last() | let t' = TO/next (t) |
* some Process.toSend.t => some p: Process | not skip (t, t', p) }
*
* assert AtLeastOneElected { progress () => some elected.Time }
*
* pred looplessPath () {no disj t, t': Time | toSend.t = toSend.t'}
*
* assert AtMostOneElected {lone elected.Time}
*
* check AtMostOneElected for 3 Process, 7 Time
* run looplessPath for 13 Time, 3 Process
* </pre>
* @author Emina Torlak
*/
public final class RingElection {
private final Relation Process, Time, succ, toSend, elected;
private final Relation pfirst, plast, pord, tfirst, tlast, tord;
/**
* Constructs an instance of the RingElection example.
*/
public RingElection() {
Process = Relation.unary("Process");
Time = Relation.unary("Time");
succ = Relation.binary("succ");
toSend = Relation.ternary("toSend");
elected = Relation.binary("elected");
pfirst = Relation.unary("pfirst");
plast = Relation.unary("plast");
pord = Relation.binary("pord");
tfirst = Relation.unary("tfirst");
tlast = Relation.unary("tlast");
tord = Relation.binary("tord");
}
/**
* Returns the declaration constraints.
* @return <pre>
* sig Time {}
* sig Process {
* succ: Process,
* toSend: Process -> Time,
* elected: set Time }
* </pre>
*/
public Formula declarations() {
final Formula ordTime = tord.totalOrder(Time, tfirst, tlast);
final Formula ordProcess = pord.totalOrder(Process, pfirst, plast);
final Formula succFunction = succ.function(Process, Process);
final Formula electedDomRange = elected.in(Process.product(Time));
return Formula.and(ordTime, ordProcess, succFunction, electedDomRange);
}
/**
* Returns the fact Ring.
* @return <pre>fact Ring {all p: Process | Process in p.^succ}</pre>
*/
public Formula ring() {
final Variable p = Variable.unary("p");
return Process.in(p.join(succ.closure())).forAll(p.oneOf(Process));
}
/**
* Returns the init predicate.
* @return <pre> pred init (t: Time) {all p: Process | p.toSend.t = p} </pre>
*/
public Formula init(Expression t) {
final Variable p = Variable.unary("p");
return p.join(toSend).join(t).eq(p).forAll(p.oneOf(Process));
}
/**
* Returns the step predicate.
* @return
* <pre>
* pred step (t, t': Time, p: Process) {
* let from = p.toSend, to = p.succ.toSend |
* some id: from.t {
* from.t' = from.t - id
* to.t' = to.t + (id - PO/prevs(p.succ)) } }
* </pre>
*/
public Formula step(Expression t1, Expression t2, Expression p) {
final Expression from = p.join(toSend);
final Expression to = p.join(succ).join(toSend);
final Variable id = Variable.unary("id");
final Expression prevs = (p.join(succ)).join((pord.transpose()).closure());
final Formula f1 = from.join(t2).eq(from.join(t1).difference(id));
final Formula f2 = to.join(t2).eq(to.join(t1).union(id.difference(prevs)));
return f1.and(f2).forSome(id.oneOf(from.join(t1)));
}
/**
* Returns the skip predicate
* @return <pre>pred skip (t, t': Time, p: Process) {p.toSend.t = p.toSend.t'}<pre>
*/
public Formula skip(Expression t1, Expression t2, Expression p) {
return p.join(toSend).join(t1).eq(p.join(toSend).join(t2));
}
/**
* Returns the Traces fact.
* @return <pre>
* fact Traces {
* init (TO/first ())
* all t: Time - TO/last() | let t' = TO/next (t) |
* all p: Process | step (t, t', p) or step (t, t', succ.p) or skip (t, t', p) }
* </pre>
*/
public Formula traces() {
final Variable t1 = Variable.unary("t");
final Expression t2 = t1.join(tord);
final Variable p = Variable.unary("p");
final Formula f = step(t1, t2, p).or(step(t1, t2, succ.join(p))).or(skip(t1, t2, p));
final Formula fAll = f.forAll(p.oneOf(Process)).forAll(t1.oneOf(Time.difference(tlast)));
return init(tfirst).and(fAll);
}
/**
* Return DefineElected fact.
* @return <pre>
* fact DefineElected {
* no elected.TO/first()
* all t: Time - TO/first()|
* elected.t = {p: Process | p in p.toSend.t - p.toSend.(TO/prev(t))} }
* </pre>
*/
public Formula defineElected() {
final Variable t = Variable.unary("t");
final Formula f1 = elected.join(tfirst).no();
final Variable p = Variable.unary("p");
final Formula c = p.in(p.join(toSend).join(t).difference(p.join(toSend).join(t.join(tord.transpose()))));
final Expression comprehension = c.comprehension(p.oneOf(Process));
final Formula f2 = elected.join(t).eq(comprehension).forAll(t.oneOf(Time.difference(tfirst)));
return f1.and(f2);
}
/**
* Returns the progress predicate.
* @return <pre>
* pred progress () {
* all t: Time - TO/last() | let t' = TO/next (t) |
* some Process.toSend.t => some p: Process | not skip (t, t', p) }
* </pre>
*/
public Formula progress() {
final Variable t1 = Variable.unary("t");
final Expression t2 = t1.join(tord);
final Variable p = Variable.unary("p");
final Formula f1 = Process.join(toSend).join(t1).some().implies(skip(t1, t2, p).not().forSome(p.oneOf(Process)));
return f1.forAll(t1.oneOf(Time.difference(tlast)));
}
/**
* Returns the looplessPath predicate
* @return <pre>pred looplessPath () {no disj t, t': Time | toSend.t = toSend.t'}</pre>
*/
public Formula looplessPath() {
final Variable t1 = Variable.unary("t");
final Variable t2 = Variable.unary("t'");
// all t, t': Time | some t&t' || !(toSend.t = toSend.t')
final Formula f1 = t1.intersection(t2).some().or(toSend.join(t1).eq(toSend.join(t2)).not());
return f1.forAll(t1.oneOf(Time).and(t2.oneOf(Time)));
}
/**
* Returns the AtLeastOneElected assertion.
* @return <pre>assert AtLeastOneElected { progress () => some elected.Time }</pre>
*/
public Formula atLeastOneElected() {
return progress().implies(elected.join(Time).some());
}
/**
* Returns the atMostOneElected assertion
* @return <pre>assert AtMostOneElected {lone elected.Time}</pre>
*/
public Formula atMostOneElected() {
return elected.join(Time).lone();
}
/**
* Returns the declarations and facts of the model
* @return the declarations and facts of the model
*/
public Formula invariants() {
return declarations().and(ring()).and(traces()).and(defineElected());
}
/**
* Returns the conjunction of the invariants and the negation of atMostOneElected.
* @return invariants() && !atMostOneElected()
*/
public Formula checkAtMostOneElected() {
return invariants().and(atMostOneElected().not());
}
/**
* Returns a bounds object with scope processes and times.
* @return bounds object with scope processes and times.
*/ | public Bounds bounds(int scope) { | 5 |
zavakid/mushroom | src/main/java/com/zavakid/mushroom/impl/MetricsSinkAdapter.java | [
"public abstract class MetricsFilter implements MetricsPlugin {\n\n public abstract void init(SubsetConfiguration conf);\n\n /**\n * Whether to accept the name\n * \n * @param name to filter on\n * @return true to accept; false otherwise.\n */\n public abstract boolean accepts(String name);\n\n /**\n * Whether to accept the tag\n * \n * @param tag to filter on\n * @return true to accept; false otherwise\n */\n public abstract boolean accepts(MetricsTag tag);\n\n /**\n * Whether to accept the tags\n * \n * @param tags to filter on\n * @return true to accept; false otherwise\n */\n public abstract boolean accepts(Iterable<MetricsTag> tags);\n\n /**\n * Whether to accept the record\n * \n * @param record to filter on\n * @return true to accept; false otherwise.\n */\n public boolean accepts(MetricsRecord record) {\n return accepts(record.tags());\n }\n\n}",
"public abstract class MetricsRecordBuilder {\n\n /**\n * Add a metrics tag\n * \n * @param name of the tag\n * @param description of the tag\n * @param value of the tag\n * @return self\n */\n public abstract MetricsRecordBuilder tag(String name, String description, String value);\n\n /**\n * Add an immutable metrics tag object\n * \n * @param tag a pre-made tag object (potentially save an object construction)\n * @return self\n */\n public abstract MetricsRecordBuilder add(MetricsTag tag);\n\n /**\n * Set the context tag\n * \n * @param value of the context\n * @return self\n */\n public abstract MetricsRecordBuilder setContext(String value);\n\n /**\n * Add an int counter metric\n * \n * @param name of the metric\n * @param description of the metric\n * @param value of the metric\n * @return self\n */\n public abstract MetricsRecordBuilder addCounter(String name, String description, int value);\n\n /**\n * Add an long counter metric\n * \n * @param name of the metric\n * @param description of the metric\n * @param value of the metric\n * @return self\n */\n public abstract MetricsRecordBuilder addCounter(String name, String description, long value);\n\n /**\n * Add an int delta metric\n * \n * @param name of the metric\n * @param description of the metric\n * @param value of the metric\n * @return self\n */\n public abstract MetricsRecordBuilder addDelta(String name, String description, int value);\n\n /**\n * Add an long delta metric\n * \n * @param name of the metric\n * @param description of the metric\n * @param value of the metric\n * @return self\n */\n public abstract MetricsRecordBuilder addDelta(String name, String description, long value);\n\n /**\n * Add a int gauge metric\n * \n * @param name of the metric\n * @param description of the metric\n * @param value of the metric\n * @return self\n */\n public abstract MetricsRecordBuilder addGauge(String name, String description, int value);\n\n /**\n * Add a long gauge metric\n * \n * @param name of the metric\n * @param description of the metric\n * @param value of the metric\n * @return self\n */\n public abstract MetricsRecordBuilder addGauge(String name, String description, long value);\n\n /**\n * Add a float gauge metric\n * \n * @param name of the metric\n * @param description of the metric\n * @param value of the metric\n * @return self\n */\n public abstract MetricsRecordBuilder addGauge(String name, String description, float value);\n\n /**\n * Add a double gauge metric\n * \n * @param name of the metric\n * @param description of the metric\n * @param value of the metric\n * @return self\n */\n public abstract MetricsRecordBuilder addGauge(String name, String description, double value);\n\n /**\n * Add a pre-made immutable metric object\n * \n * @param metric the pre-made metric to save an object construction\n * @return self\n */\n public abstract MetricsRecordBuilder add(Metric metric);\n}",
"public interface MetricsSink extends MetricsPlugin {\n\n /**\n * Put a metrics record in the sink\n * \n * @param record the record to put\n */\n void putMetrics(MetricsRecord record);\n\n /**\n * Flush any buffered metrics\n */\n void flush();\n\n}",
"public class MetricMutableCounterInt extends MetricMutableCounter<Integer> {\n\n private volatile int value;\n\n /**\n * Construct a mutable int counter\n * \n * @param name of the counter\n * @param description of the counter\n * @param initValue the initial value of the counter\n */\n public MetricMutableCounterInt(String name, String description, int initValue){\n super(name, description);\n this.value = initValue;\n }\n\n public synchronized void incr() {\n ++value;\n setChanged();\n }\n\n /**\n * Increment the value by a delta\n * \n * @param delta of the increment\n */\n public synchronized void incr(int delta) {\n value += delta;\n setChanged();\n }\n\n public void snapshot(MetricsRecordBuilder builder, boolean all) {\n if (all || changed()) {\n builder.addCounter(name, description, value);\n clearChanged();\n }\n }\n\n}",
"public class MetricMutableGaugeInt extends MetricMutableGauge<Integer> {\n\n private volatile int value;\n\n /**\n * Construct a mutable int gauge metric\n * \n * @param name of the gauge\n * @param description of the gauge\n * @param initValue the initial value of the gauge\n */\n public MetricMutableGaugeInt(String name, String description, int initValue){\n super(name, description);\n this.value = initValue;\n }\n\n public synchronized void incr() {\n ++value;\n setChanged();\n }\n\n /**\n * Increment by delta\n * \n * @param delta of the increment\n */\n public synchronized void incr(int delta) {\n value += delta;\n setChanged();\n }\n\n public synchronized void decr() {\n --value;\n setChanged();\n }\n\n /**\n * decrement by delta\n * \n * @param delta of the decrement\n */\n public synchronized void decr(int delta) {\n value -= delta;\n setChanged();\n }\n\n /**\n * Set the value of the metric\n * \n * @param value to set\n */\n public void set(int value) {\n this.value = value;\n setChanged();\n }\n\n public void snapshot(MetricsRecordBuilder builder, boolean all) {\n if (all || changed()) {\n builder.addGauge(name, description, value);\n clearChanged();\n }\n }\n\n}",
"public class MetricMutableStat extends MetricMutable {\n\n private final String numSamplesName, numSamplesDesc;\n private final String avgValueName, avgValueDesc;\n private final String stdevValueName, stdevValueDesc;\n private final String iMinValueName, iMinValueDesc;\n private final String iMaxValueName, iMaxValueDesc;\n private final String minValueName, minValueDesc;\n private final String maxValueName, maxValueDesc;\n\n private final SampleStat intervalStat = new SampleStat();\n private final SampleStat prevStat = new SampleStat();\n private final SampleStat.MinMax minMax = new SampleStat.MinMax();\n private long numSamples = 0;\n private boolean extended = false;\n\n /**\n * Construct a sample statistics metric\n * \n * @param name of the metric\n * @param description of the metric\n * @param sampleName of the metric (e.g. \"ops\")\n * @param valueName of the metric (e.g. \"time\", \"latency\")\n * @param extended create extended stats (stdev, min/max etc.) by default.\n */\n public MetricMutableStat(String name, String description, String sampleName, String valueName, boolean extended){\n super(name, description);\n String desc = StringUtils.uncapitalize(description);\n numSamplesName = name + \"_num_\" + sampleName;\n numSamplesDesc = \"Number of \" + sampleName + \" for \" + desc;\n avgValueName = name + \"_avg_\" + valueName;\n avgValueDesc = \"Average \" + valueName + \" for \" + desc;\n stdevValueName = name + \"_stdev_\" + valueName;\n stdevValueDesc = \"Standard deviation of \" + valueName + \" for \" + desc;\n iMinValueName = name + \"_imin_\" + valueName;\n iMinValueDesc = \"Interval min \" + valueName + \" for \" + desc;\n iMaxValueName = name + \"_imax_\" + valueName;\n iMaxValueDesc = \"Interval max \" + valueName + \" for \" + desc;\n minValueName = name + \"_min_\" + valueName;\n minValueDesc = \"Min \" + valueName + \" for \" + desc;\n maxValueName = name + \"_max_\" + valueName;\n maxValueDesc = \"Max \" + valueName + \" for \" + desc;\n this.extended = extended;\n }\n\n /**\n * Construct a snapshot stat metric with extended stat off by default\n * \n * @param name of the metric\n * @param description of the metric\n * @param sampleName of the metric (e.g. \"ops\")\n * @param valueName of the metric (e.g. \"time\", \"latency\")\n */\n public MetricMutableStat(String name, String description, String sampleName, String valueName){\n this(name, description, sampleName, valueName, false);\n }\n\n /**\n * Add a number of samples and their sum to the running stat\n * \n * @param numSamples number of samples\n * @param sum of the samples\n */\n public synchronized void add(long numSamples, long sum) {\n intervalStat.add(numSamples, sum);\n setChanged();\n }\n\n /**\n * Add a snapshot to the metric\n * \n * @param value of the metric\n */\n public synchronized void add(long value) {\n intervalStat.add(value);\n minMax.add(value);\n setChanged();\n }\n\n public synchronized void snapshot(MetricsRecordBuilder builder, boolean all) {\n if (all || changed()) {\n numSamples += intervalStat.numSamples();\n builder.addCounter(numSamplesName, numSamplesDesc, numSamples);\n builder.addGauge(avgValueName, avgValueDesc, lastStat().mean());\n if (extended) {\n builder.addGauge(stdevValueName, stdevValueDesc, lastStat().stddev());\n builder.addGauge(iMinValueName, iMinValueDesc, lastStat().min());\n builder.addGauge(iMaxValueName, iMaxValueDesc, lastStat().max());\n builder.addGauge(minValueName, minValueDesc, minMax.min());\n builder.addGauge(maxValueName, maxValueDesc, minMax.max());\n }\n if (changed()) {\n intervalStat.copyTo(prevStat);\n intervalStat.reset();\n clearChanged();\n }\n }\n }\n\n private SampleStat lastStat() {\n return changed() ? intervalStat : prevStat;\n }\n\n /**\n * Reset the all time min max of the metric\n */\n public void resetMinMax() {\n minMax.reset();\n }\n\n}",
"public class MetricsRegistry {\n\n /** key for the context tag */\n public static final String CONTEXT_KEY = \"context\";\n /** description for the context tag */\n public static final String CONTEXT_DESC = \"Metrics context\";\n\n private final LinkedHashMap<String, MetricMutable> metricsMap = new LinkedHashMap<String, MetricMutable>();\n private final LinkedHashMap<String, MetricsTag> tagsMap = new LinkedHashMap<String, MetricsTag>();\n private final String name;\n private final MetricMutableFactory mf;\n\n /**\n * Construct the registry with a record name\n * \n * @param name of the record of the metrics\n */\n public MetricsRegistry(String name){\n this.name = name;\n this.mf = new MetricMutableFactory();\n }\n\n /**\n * Construct the registry with a name and a metric factory\n * \n * @param name of the record of the metrics\n * @param factory for creating new mutable metrics\n */\n public MetricsRegistry(String name, MetricMutableFactory factory){\n this.name = name;\n this.mf = factory;\n }\n\n /**\n * @return the name of the metrics registry\n */\n public String name() {\n return name;\n }\n\n /**\n * Get a metric by name\n * \n * @param name of the metric\n * @return the metric object\n */\n public MetricMutable get(String name) {\n return metricsMap.get(name);\n }\n\n /**\n * Create a mutable integer counter\n * \n * @param name of the metric\n * @param description of the metric\n * @param initValue of the metric\n * @return a new counter object\n */\n public MetricMutableCounterInt newCounter(String name, String description, int initValue) {\n checkMetricName(name);\n MetricMutableCounterInt ret = mf.newCounter(name, description, initValue);\n metricsMap.put(name, ret);\n return ret;\n }\n\n /**\n * Create a mutable long integer counter\n * \n * @param name of the metric\n * @param description of the metric\n * @param initValue of the metric\n * @return a new counter object\n */\n public MetricMutableCounterLong newCounter(String name, String description, long initValue) {\n checkMetricName(name);\n MetricMutableCounterLong ret = mf.newCounter(name, description, initValue);\n metricsMap.put(name, ret);\n return ret;\n }\n\n /**\n * Create a mutable integer gauge\n * \n * @param name of the metric\n * @param description of the metric\n * @param initValue of the metric\n * @return a new gauge object\n */\n public MetricMutableGaugeInt newGauge(String name, String description, int initValue) {\n checkMetricName(name);\n MetricMutableGaugeInt ret = mf.newGauge(name, description, initValue);\n metricsMap.put(name, ret);\n return ret;\n }\n\n /**\n * Create a mutable long integer gauge\n * \n * @param name of the metric\n * @param description of the metric\n * @param initValue of the metric\n * @return a new gauge object\n */\n public MetricMutableGaugeLong newGauge(String name, String description, long initValue) {\n checkMetricName(name);\n MetricMutableGaugeLong ret = mf.newGauge(name, description, initValue);\n metricsMap.put(name, ret);\n return ret;\n }\n\n /**\n * Create a mutable integer delta\n * \n * @param name of the metric\n * @param description of the metric\n * @param initValue of the metric\n * @return a new counter object\n */\n public MetricMutableDeltaInt newDelta(String name, String description, int initValue) {\n checkMetricName(name);\n MetricMutableDeltaInt ret = mf.newDelta(name, description, initValue);\n metricsMap.put(name, ret);\n return ret;\n }\n\n /**\n * Create a mutable long integer delta\n * \n * @param name of the metric\n * @param description of the metric\n * @param initValue of the metric\n * @return a new counter object\n */\n public MetricMutableDeltaLong newDelta(String name, String description, long initValue) {\n checkMetricName(name);\n MetricMutableDeltaLong ret = mf.newDelta(name, description, initValue);\n metricsMap.put(name, ret);\n return ret;\n }\n\n /**\n * Create a mutable metric with stats\n * \n * @param name of the metric\n * @param description of the metric\n * @param sampleName of the metric (e.g., \"ops\")\n * @param valueName of the metric (e.g., \"time\" or \"latency\")\n * @param extended produce extended stat (stdev, min/max etc.) if true.\n * @return a new metric object\n */\n public MetricMutableStat newStat(String name, String description, String sampleName, String valueName,\n boolean extended) {\n checkMetricName(name);\n MetricMutableStat ret = mf.newStat(name, description, sampleName, valueName, extended);\n metricsMap.put(name, ret);\n return ret;\n }\n\n /**\n * Create a mutable metric with stats\n * \n * @param name of the metric\n * @param description of the metric\n * @param sampleName of the metric (e.g., \"ops\")\n * @param valueName of the metric (e.g., \"time\" or \"latency\")\n * @return a new metric object\n */\n public MetricMutableStat newStat(String name, String description, String sampleName, String valueName) {\n return newStat(name, description, sampleName, valueName, false);\n }\n\n /**\n * Create a mutable metric with stats using the name only\n * \n * @param name of the metric\n * @return a new metric object\n */\n public MetricMutableStat newStat(String name) {\n return newStat(name, \"\", \"ops\", \"time\", false);\n }\n\n /**\n * Increment a metric by name.\n * \n * @param name of the metric\n */\n public void incr(String name) {\n incr(name, mf);\n }\n\n /**\n * Increment a metric by name.\n * \n * @param name of the metric\n * @param factory to lazily create the metric if not null\n */\n public void incr(String name, MetricMutableFactory factory) {\n MetricMutable m = metricsMap.get(name);\n\n if (m != null) {\n if (m instanceof MetricMutableGauge<?>) {\n ((MetricMutableGauge<?>) m).incr();\n } else if (m instanceof MetricMutableCounter<?>) {\n ((MetricMutableCounter<?>) m).incr();\n } else {\n throw new MetricsException(\"Unsupported incr() for metric \" + name);\n }\n } else if (factory != null) {\n metricsMap.put(name, factory.newMetric(name));\n incr(name, null);\n } else {\n throw new MetricsException(\"Metric \" + name + \" doesn't exist\");\n }\n }\n\n /**\n * Decrement a metric by name.\n * \n * @param name of the metric\n */\n public void decr(String name) {\n decr(name, mf);\n }\n\n /**\n * Decrement a metric by name.\n * \n * @param name of the metric\n * @param factory to lazily create the metric if not null\n */\n public void decr(String name, MetricMutableFactory factory) {\n MetricMutable m = metricsMap.get(name);\n\n if (m != null) {\n if (m instanceof MetricMutableGauge<?>) {\n ((MetricMutableGauge<?>) m).decr();\n } else {\n throw new MetricsException(\"Unsupported decr() for metric \" + name);\n }\n } else if (factory != null) {\n metricsMap.put(name, factory.newMetric(name));\n decr(name, null);\n } else {\n throw new MetricsException(\"Metric \" + name + \" doesn't exist\");\n }\n }\n\n /**\n * Add a value to a metric by name.\n * \n * @param name of the metric\n * @param value of the snapshot to add\n */\n public void add(String name, long value) {\n add(name, value, mf);\n }\n\n /**\n * Decrement a metric by name.\n * \n * @param name of the metric\n * @param value of the snapshot to add\n * @param factory to lazily create the metric if not null\n */\n public void add(String name, long value, MetricMutableFactory factory) {\n MetricMutable m = metricsMap.get(name);\n\n if (m != null) {\n if (m instanceof MetricMutableStat) {\n ((MetricMutableStat) m).add(value);\n } else {\n throw new MetricsException(\"Unsupported add(value) for metric \" + name);\n }\n } else if (factory != null) {\n metricsMap.put(name, factory.newStat(name));\n add(name, value, null);\n } else {\n throw new MetricsException(\"Metric \" + name + \" doesn't exist\");\n }\n }\n\n /**\n * Set the metrics context tag\n * \n * @param name of the context\n * @return the registry itself as a convenience\n */\n public MetricsRegistry setContext(String name) {\n return tag(CONTEXT_KEY, CONTEXT_DESC, name);\n }\n\n /**\n * Add a tag to the metrics\n * \n * @param name of the tag\n * @param description of the tag\n * @param value of the tag\n * @return the registry (for keep adding tags)\n */\n public MetricsRegistry tag(String name, String description, String value) {\n return tag(name, description, value, false);\n }\n\n /**\n * Add a tag to the metrics\n * \n * @param name of the tag\n * @param description of the tag\n * @param value of the tag\n * @param override existing tag if true\n * @return the registry (for keep adding tags)\n */\n public MetricsRegistry tag(String name, String description, String value, boolean override) {\n if (!override) checkTagName(name);\n tagsMap.put(name, new MetricsTag(name, description, value));\n return this;\n }\n\n /**\n * Get the tags\n * \n * @return the tags set\n */\n public Set<Entry<String, MetricsTag>> tags() {\n return tagsMap.entrySet();\n }\n\n /**\n * Get the metrics\n * \n * @return the metrics set\n */\n public Set<Entry<String, MetricMutable>> metrics() {\n return metricsMap.entrySet();\n }\n\n private void checkMetricName(String name) {\n if (metricsMap.containsKey(name)) {\n throw new MetricsException(\"Metric name \" + name + \" already exists!\");\n }\n }\n\n private void checkTagName(String name) {\n if (tagsMap.containsKey(name)) {\n throw new MetricsException(\"Tag \" + name + \" already exists!\");\n }\n }\n\n /**\n * Sample all the mutable metrics and put the snapshot in the builder\n * \n * @param builder to contain the metrics snapshot\n * @param all get all the metrics even if the values are not changed.\n */\n public void snapshot(MetricsRecordBuilder builder, boolean all) {\n for (Entry<String, MetricsTag> entry : tags()) {\n builder.add(entry.getValue());\n }\n for (Entry<String, MetricMutable> entry : metrics()) {\n entry.getValue().snapshot(builder, all);\n }\n }\n}",
"public class Contracts {\n\n private Contracts(){\n }\n\n /**\n * Check that a reference is not null.\n * \n * @param <T> type of the reference\n * @param ref the reference to check\n * @param msg the error message\n * @throws NullPointerException if {@code ref} is null\n * @return the checked reference for convenience\n */\n public static <T> T checkNotNull(T ref, Object msg) {\n if (ref == null) {\n throw new NullPointerException(String.valueOf(msg) + \": \" + ref.getClass().getName());\n }\n return ref;\n }\n\n /**\n * Check the state expression for false conditions\n * \n * @param expression the boolean expression to check\n * @param msg the error message if {@code expression} is false\n * @throws IllegalStateException if {@code expression} is false\n */\n public static void checkState(boolean expression, Object msg) {\n if (!expression) {\n throw new IllegalStateException(String.valueOf(msg));\n }\n }\n\n /**\n * Check an argument for false conditions\n * \n * @param <T> type of the argument\n * @param arg the argument to check\n * @param expression the boolean expression for the condition\n * @param msg the error message if {@code expression} is false\n * @return the argument for convenience\n */\n public static <T> T checkArg(T arg, boolean expression, Object msg) {\n if (!expression) {\n throw new IllegalArgumentException(String.valueOf(msg) + \": \" + arg);\n }\n return arg;\n }\n\n /**\n * Check an argument for false conditions\n * \n * @param arg the argument to check\n * @param expression the boolean expression for the condition\n * @param msg the error message if {@code expression} is false\n * @return the argument for convenience\n */\n public static int checkArg(int arg, boolean expression, Object msg) {\n if (!expression) {\n throw new IllegalArgumentException(String.valueOf(msg) + \": \" + arg);\n }\n return arg;\n }\n\n /**\n * Check an argument for false conditions\n * \n * @param arg the argument to check\n * @param expression the boolean expression for the condition\n * @param msg the error message if {@code expression} is false\n * @return the argument for convenience\n */\n public static long checkArg(long arg, boolean expression, Object msg) {\n if (!expression) {\n throw new IllegalArgumentException(String.valueOf(msg));\n }\n return arg;\n }\n\n /**\n * Check an argument for false conditions\n * \n * @param arg the argument to check\n * @param expression the boolean expression for the condition\n * @param msg the error message if {@code expression} is false\n * @return the argument for convenience\n */\n public static float checkArg(float arg, boolean expression, Object msg) {\n if (!expression) {\n throw new IllegalArgumentException(String.valueOf(msg) + \": \" + arg);\n }\n return arg;\n }\n\n /**\n * Check an argument for false conditions\n * \n * @param arg the argument to check\n * @param expression the boolean expression for the condition\n * @param msg the error message if {@code expression} is false\n * @return the argument for convenience\n */\n public static double checkArg(double arg, boolean expression, Object msg) {\n if (!expression) {\n throw new IllegalArgumentException(String.valueOf(msg) + \": \" + arg);\n }\n return arg;\n }\n}"
] | import com.zavakid.mushroom.lib.MetricsRegistry;
import com.zavakid.mushroom.util.Contracts;
import java.util.Random;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.zavakid.mushroom.MetricsFilter;
import com.zavakid.mushroom.MetricsRecordBuilder;
import com.zavakid.mushroom.MetricsSink;
import com.zavakid.mushroom.lib.MetricMutableCounterInt;
import com.zavakid.mushroom.lib.MetricMutableGaugeInt;
import com.zavakid.mushroom.lib.MetricMutableStat; | firstRetryDelay = Contracts.checkArg(retryDelay, retryDelay > 0, "retry delay");
this.retryBackoff = Contracts.checkArg(retryBackoff, retryBackoff > 1, "backoff factor");
this.retryCount = retryCount;
this.queue = new SinkQueue<MetricsBuffer>(
Contracts.checkArg(queueCapacity, queueCapacity > 0, "queue capacity"));
latency = registry.newStat("sink." + name + ".latency", "Sink end to end latency", "ops", "time");
dropped = registry.newCounter("sink." + name + ".dropped", "Dropped updates per sink", 0);
qsize = registry.newGauge("sink." + name + ".qsize", "Queue size", 0);
sinkThread = new Thread() {
@Override
public void run() {
publishMetricsFromQueue();
}
};
sinkThread.setName(name);
sinkThread.setDaemon(true);
}
boolean putMetrics(MetricsBuffer buffer, long logicalTime) {
if (logicalTime % period == 0) {
LOG.debug("enqueue, logicalTime=" + logicalTime);
if (queue.enqueue(buffer)) {
qsize.set(queue.size());
return true;
}
dropped.incr();
return false;
}
return true; // OK
}
void publishMetricsFromQueue() {
int retryDelay = firstRetryDelay;
int n = retryCount;
int minDelay = Math.min(500, retryDelay * 1000); // millis
Random rng = new Random(System.nanoTime());
while (!stopping) {
try {
queue.consumeAll(consumer);
retryDelay = firstRetryDelay;
n = retryCount;
inError = false;
} catch (InterruptedException e) {
LOG.info(name + " thread interrupted.");
} catch (Exception e) {
if (n > 0) {
int awhile = rng.nextInt(retryDelay * 1000 - minDelay) + minDelay;
if (!inError) {
LOG.error("Got sink exception, retry in " + awhile + "ms", e);
}
retryDelay *= retryBackoff;
try {
Thread.sleep(awhile);
} catch (InterruptedException e2) {
LOG.info(name + " thread interrupted while waiting for retry", e2);
}
--n;
} else {
if (!inError) {
LOG.error("Got sink exception and over retry limit, " + "suppressing further error messages", e);
}
queue.clear();
inError = true; // Don't keep complaining ad infinitum
}
} finally {
qsize.set(queue.size());
}
}
}
void publishMetrics(MetricsBuffer buffer) {
long ts = 0;
for (MetricsBuffer.Entry entry : buffer) {
LOG.debug("sourceFilter=" + sourceFilter);
if (sourceFilter == null || sourceFilter.accepts(entry.name())) {
for (MetricsRecordImpl record : entry.records()) {
if ((context == null || context.equals(record.context()))
&& (recordFilter == null || recordFilter.accepts(record))) {
if (LOG.isDebugEnabled()) {
LOG.debug("Pushing record " + entry.name() + "." + record.context() + "." + record.name()
+ " to " + name);
}
sink.putMetrics(metricFilter == null ? record : new MetricsRecordFiltered(record, metricFilter));
if (ts == 0) ts = record.timestamp();
}
}
}
}
if (ts > 0) {
sink.flush();
latency.add(System.currentTimeMillis() - ts);
}
LOG.debug("Done");
}
void start() {
sinkThread.start();
LOG.info("Sink " + name + " started");
}
void stop() {
stopping = true;
sinkThread.interrupt();
try {
sinkThread.join();
} catch (InterruptedException e) {
LOG.warn("Stop interrupted", e);
}
}
String name() {
return name;
}
String description() {
return description;
}
| void snapshot(MetricsRecordBuilder rb, boolean all) { | 1 |
lemire/javaewah | src/test/java/com/googlecode/javaewah32/EWAHCompressedBitmap32Test.java | [
"public interface ChunkIterator {\n\n /**\n * Is there more?\n *\n * @return true, if there is more, false otherwise\n */\n boolean hasNext();\n\n /**\n * Return the next bit\n *\n * @return the bit\n */\n boolean nextBit();\n\n /**\n * Return the length of the next bit\n *\n * @return the length\n */\n int nextLength();\n\n /**\n * Move the iterator at the next different bit\n */\n void move();\n\n /**\n * Move the iterator at the next ith bit\n *\n * @param bits the number of bits to skip\n */\n void move(int bits);\n\n}",
"public final class FastAggregation {\n\n /** Private constructor to prevent instantiation */\n private FastAggregation() {}\n\n /**\n * Compute the and aggregate using a temporary uncompressed bitmap.\n *\n * This function does not seek to match the \"sizeinbits\" attributes\n * of the input bitmaps.\n *\n * @param bitmaps the source bitmaps\n * @param bufSize buffer size used during the computation in 64-bit\n * words (per input bitmap)\n * @return the or aggregate.\n */\n public static EWAHCompressedBitmap bufferedand(final int bufSize,\n final EWAHCompressedBitmap... bitmaps) {\n EWAHCompressedBitmap answer = new EWAHCompressedBitmap();\n bufferedandWithContainer(answer, bufSize, bitmaps);\n return answer;\n }\n\n /**\n * Compute the and aggregate using a temporary uncompressed bitmap.\n * \n * This function does not seek to match the \"sizeinbits\" attributes\n * of the input bitmaps.\n *\n * @param container where the aggregate is written\n * @param bufSize buffer size used during the computation in 64-bit\n * words (per input bitmap)\n * @param bitmaps the source bitmaps\n */\n public static void bufferedandWithContainer(\n final BitmapStorage container, final int bufSize,\n final EWAHCompressedBitmap... bitmaps) {\n\n java.util.LinkedList<IteratingBufferedRunningLengthWord> al = new java.util.LinkedList<IteratingBufferedRunningLengthWord>();\n for (EWAHCompressedBitmap bitmap : bitmaps) {\n al.add(new IteratingBufferedRunningLengthWord(bitmap));\n }\n\n long[] hardbitmap = new long[bufSize * bitmaps.length];\n\n for (IteratingRLW i : al)\n if (i.size() == 0) {\n al.clear();\n break;\n }\n\n while (!al.isEmpty()) {\n Arrays.fill(hardbitmap, ~0l);\n long effective = Integer.MAX_VALUE;\n for (IteratingRLW i : al) {\n int eff = IteratorAggregation.inplaceand(\n hardbitmap, i);\n if (eff < effective)\n effective = eff;\n }\n for (int k = 0; k < effective; ++k)\n container.addWord(hardbitmap[k]);\n for (IteratingRLW i : al)\n if (i.size() == 0) {\n al.clear();\n break;\n }\n }\n }\n\n /**\n * Compute the or aggregate using a temporary uncompressed bitmap.\n *\n * @param bitmaps the source bitmaps\n * @param bufSize buffer size used during the computation in 64-bit\n * words\n * @return the or aggregate.\n */\n public static EWAHCompressedBitmap bufferedor(final int bufSize,\n final EWAHCompressedBitmap... bitmaps) {\n EWAHCompressedBitmap answer = new EWAHCompressedBitmap();\n bufferedorWithContainer(answer, bufSize, bitmaps);\n return answer;\n }\n\n /**\n * Compute the or aggregate using a temporary uncompressed bitmap.\n *\n * @param container where the aggregate is written\n * @param bufSize buffer size used during the computation in 64-bit\n * words\n * @param bitmaps the source bitmaps\n */\n public static void bufferedorWithContainer(\n final BitmapStorage container, final int bufSize,\n final EWAHCompressedBitmap... bitmaps) {\n int range = 0;\n EWAHCompressedBitmap[] sbitmaps = bitmaps.clone();\n Arrays.sort(sbitmaps, new Comparator<EWAHCompressedBitmap>() {\n @Override\n public int compare(EWAHCompressedBitmap a,\n EWAHCompressedBitmap b) {\n return b.sizeInBits() - a.sizeInBits();\n }\n });\n\n java.util.ArrayList<IteratingBufferedRunningLengthWord> al = new java.util.ArrayList<IteratingBufferedRunningLengthWord>();\n for (EWAHCompressedBitmap bitmap : sbitmaps) {\n if (bitmap.sizeInBits() > range)\n range = bitmap.sizeInBits();\n al.add(new IteratingBufferedRunningLengthWord(bitmap));\n }\n long[] hardbitmap = new long[bufSize];\n int maxr = al.size();\n while (maxr > 0) {\n long effective = 0;\n for (int k = 0; k < maxr; ++k) {\n if (al.get(k).size() > 0) {\n int eff = IteratorAggregation\n .inplaceor(hardbitmap,\n al.get(k));\n if (eff > effective)\n effective = eff;\n } else\n maxr = k;\n }\n for (int k = 0; k < effective; ++k)\n container.addWord(hardbitmap[k]);\n Arrays.fill(hardbitmap, 0);\n\n }\n container.setSizeInBitsWithinLastWord(range);\n }\n\n /**\n * Compute the xor aggregate using a temporary uncompressed bitmap.\n *\n * @param bitmaps the source bitmaps\n * @param bufSize buffer size used during the computation in 64-bit\n * words\n * @return the xor aggregate.\n */\n public static EWAHCompressedBitmap bufferedxor(final int bufSize,\n final EWAHCompressedBitmap... bitmaps) {\n EWAHCompressedBitmap answer = new EWAHCompressedBitmap();\n bufferedxorWithContainer(answer, bufSize, bitmaps);\n return answer;\n }\n\n /**\n * Compute the xor aggregate using a temporary uncompressed bitmap.\n * \n *\n * @param container where the aggregate is written\n * @param bufSize buffer size used during the computation in 64-bit\n * words\n * @param bitmaps the source bitmaps\n */\n public static void bufferedxorWithContainer(\n final BitmapStorage container, final int bufSize,\n final EWAHCompressedBitmap... bitmaps) {\n int range = 0;\n EWAHCompressedBitmap[] sbitmaps = bitmaps.clone();\n Arrays.sort(sbitmaps, new Comparator<EWAHCompressedBitmap>() {\n @Override\n public int compare(EWAHCompressedBitmap a,\n EWAHCompressedBitmap b) {\n return b.sizeInBits() - a.sizeInBits();\n }\n });\n\n java.util.ArrayList<IteratingBufferedRunningLengthWord> al = new java.util.ArrayList<IteratingBufferedRunningLengthWord>();\n for (EWAHCompressedBitmap bitmap : sbitmaps) {\n if (bitmap.sizeInBits() > range)\n range = bitmap.sizeInBits();\n al.add(new IteratingBufferedRunningLengthWord(bitmap));\n }\n long[] hardbitmap = new long[bufSize];\n int maxr = al.size();\n while (maxr > 0) {\n long effective = 0;\n for (int k = 0; k < maxr; ++k) {\n if (al.get(k).size() > 0) {\n int eff = IteratorAggregation.inplacexor(hardbitmap, al.get(k));\n if (eff > effective)\n effective = eff;\n } else\n maxr = k;\n }\n for (int k = 0; k < effective; ++k)\n container.addWord(hardbitmap[k]);\n Arrays.fill(hardbitmap, 0);\n }\n container.setSizeInBitsWithinLastWord(range);\n }\n\n /**\n * Uses a priority queue to compute the or aggregate.\n * \n * This algorithm runs in linearithmic time (O(n log n)) with respect to the number of bitmaps.\n *\n * @param <T> a class extending LogicalElement (like a compressed\n * bitmap)\n * @param bitmaps bitmaps to be aggregated\n * @return the or aggregate\n */\n @SuppressWarnings({\"rawtypes\", \"unchecked\"})\n public static <T extends LogicalElement> T or(T... bitmaps) {\n PriorityQueue<T> pq = new PriorityQueue<T>(bitmaps.length,\n new Comparator<T>() {\n @Override\n public int compare(T a, T b) {\n return a.sizeInBytes()\n - b.sizeInBytes();\n }\n }\n );\n Collections.addAll(pq, bitmaps);\n while (pq.size() > 1) {\n T x1 = pq.poll();\n T x2 = pq.poll();\n pq.add((T) x1.or(x2));\n }\n return pq.poll();\n }\n\n /**\n * Uses a priority queue to compute the or aggregate.\n * \n * The content of the container is overwritten.\n * \n * This algorithm runs in linearithmic time (O(n log n)) with respect to the number of bitmaps.\n *\n * @param container where we write the result\n * @param bitmaps to be aggregated\n */\n public static void orToContainer(final BitmapStorage container,\n final EWAHCompressedBitmap... bitmaps) {\n if (bitmaps.length < 2)\n throw new IllegalArgumentException(\n \"We need at least two bitmaps\");\n PriorityQueue<EWAHCompressedBitmap> pq = new PriorityQueue<EWAHCompressedBitmap>(\n bitmaps.length, new Comparator<EWAHCompressedBitmap>() {\n @Override\n public int compare(EWAHCompressedBitmap a,\n EWAHCompressedBitmap b) {\n return a.sizeInBytes()\n - b.sizeInBytes();\n }\n }\n );\n Collections.addAll(pq, bitmaps);\n while (pq.size() > 2) {\n EWAHCompressedBitmap x1 = pq.poll();\n EWAHCompressedBitmap x2 = pq.poll();\n pq.add(x1.or(x2));\n }\n pq.poll().orToContainer(pq.poll(), container);\n }\n \n /**\n * Simple algorithm that computes the OR aggregate.\n * \n * @param bitmaps input bitmaps\n * @return new bitmap containing the aggregate\n */\n public static EWAHCompressedBitmap or(final EWAHCompressedBitmap... bitmaps) {\n PriorityQueue<EWAHCompressedBitmap> pq = new PriorityQueue<EWAHCompressedBitmap>(bitmaps.length,\n new Comparator<EWAHCompressedBitmap>() {\n @Override\n public int compare(EWAHCompressedBitmap a, EWAHCompressedBitmap b) {\n return a.sizeInBytes()\n - b.sizeInBytes();\n }\n }\n );\n Collections.addAll(pq, bitmaps);\n if(pq.isEmpty()) return new EWAHCompressedBitmap();\n while (pq.size() > 1) {\n EWAHCompressedBitmap x1 = pq.poll();\n EWAHCompressedBitmap x2 = pq.poll();\n pq.add(x1.or(x2));\n }\n return pq.poll();\n }\n \n /**\n * Simple algorithm that computes the XOR aggregate.\n * \n * @param bitmaps input bitmaps\n * @return new bitmap containing the aggregate\n */\n public static EWAHCompressedBitmap xor(final EWAHCompressedBitmap... bitmaps) {\n PriorityQueue<EWAHCompressedBitmap> pq = new PriorityQueue<EWAHCompressedBitmap>(bitmaps.length,\n new Comparator<EWAHCompressedBitmap>() {\n @Override\n public int compare(EWAHCompressedBitmap a, EWAHCompressedBitmap b) {\n return a.sizeInBytes()\n - b.sizeInBytes();\n }\n }\n );\n Collections.addAll(pq, bitmaps);\n if(pq.isEmpty()) return new EWAHCompressedBitmap();\n while (pq.size() > 1) {\n EWAHCompressedBitmap x1 = pq.poll();\n EWAHCompressedBitmap x2 = pq.poll();\n pq.add(x1.xor(x2));\n }\n return pq.poll();\n }\n \n /**\n * Simple algorithm that computes the OR aggregate.\n * \n * @param bitmaps input bitmaps\n * @return new bitmap containing the aggregate\n */\n public static EWAHCompressedBitmap or(final Iterator<EWAHCompressedBitmap> bitmaps) {\n PriorityQueue<EWAHCompressedBitmap> pq = new PriorityQueue<EWAHCompressedBitmap>(32,\n new Comparator<EWAHCompressedBitmap>() {\n @Override\n public int compare(EWAHCompressedBitmap a, EWAHCompressedBitmap b) {\n return a.sizeInBytes()\n - b.sizeInBytes();\n }\n }\n );\n while(bitmaps.hasNext())\n pq.add(bitmaps.next());\n if(pq.isEmpty()) return new EWAHCompressedBitmap();\n while (pq.size() > 1) {\n EWAHCompressedBitmap x1 = pq.poll();\n EWAHCompressedBitmap x2 = pq.poll();\n pq.add(x1.or(x2));\n }\n return pq.poll();\n }\n \n /**\n * Simple algorithm that computes the XOR aggregate.\n * \n * @param bitmaps input bitmaps\n * @return new bitmap containing the aggregate\n */\n public static EWAHCompressedBitmap xor(final Iterator<EWAHCompressedBitmap> bitmaps) {\n PriorityQueue<EWAHCompressedBitmap> pq = new PriorityQueue<EWAHCompressedBitmap>(32,\n new Comparator<EWAHCompressedBitmap>() {\n @Override\n public int compare(EWAHCompressedBitmap a, EWAHCompressedBitmap b) {\n return a.sizeInBytes()\n - b.sizeInBytes();\n }\n }\n );\n while(bitmaps.hasNext())\n pq.add(bitmaps.next());\n if(pq.isEmpty()) return new EWAHCompressedBitmap();\n while (pq.size() > 1) {\n EWAHCompressedBitmap x1 = pq.poll();\n EWAHCompressedBitmap x2 = pq.poll();\n pq.add(x1.xor(x2));\n }\n return pq.poll();\n }\n\n\n /**\n * Uses a priority queue to compute the xor aggregate.\n * \n * This algorithm runs in linearithmic time (O(n log n)) with respect to the number of bitmaps.\n *\n * @param <T> a class extending LogicalElement (like a compressed\n * bitmap)\n * @param bitmaps bitmaps to be aggregated\n * @return the xor aggregate\n */\n @SuppressWarnings({\"rawtypes\", \"unchecked\"})\n public static <T extends LogicalElement> T xor(T... bitmaps) {\n PriorityQueue<T> pq = new PriorityQueue<T>(bitmaps.length,\n new Comparator<T>() {\n\n @Override\n public int compare(T a, T b) {\n return a.sizeInBytes()\n - b.sizeInBytes();\n }\n }\n );\n Collections.addAll(pq, bitmaps);\n while (pq.size() > 1) {\n T x1 = pq.poll();\n T x2 = pq.poll();\n pq.add((T) x1.xor(x2));\n }\n return pq.poll();\n }\n\n /**\n * Uses a priority queue to compute the xor aggregate.\n * \n * The content of the container is overwritten.\n * \n * This algorithm runs in linearithmic time (O(n log n)) with respect to the number of bitmaps.\n *\n * @param container where we write the result\n * @param bitmaps to be aggregated\n */\n public static void xorToContainer(final BitmapStorage container,\n final EWAHCompressedBitmap... bitmaps) {\n if (bitmaps.length < 2)\n throw new IllegalArgumentException(\n \"We need at least two bitmaps\");\n PriorityQueue<EWAHCompressedBitmap> pq = new PriorityQueue<EWAHCompressedBitmap>(\n bitmaps.length, new Comparator<EWAHCompressedBitmap>() {\n @Override\n public int compare(EWAHCompressedBitmap a,\n EWAHCompressedBitmap b) {\n return a.sizeInBytes()\n - b.sizeInBytes();\n }\n }\n );\n Collections.addAll(pq, bitmaps);\n while (pq.size() > 2) {\n EWAHCompressedBitmap x1 = pq.poll();\n EWAHCompressedBitmap x2 = pq.poll();\n pq.add(x1.xor(x2));\n }\n pq.poll().xorToContainer(pq.poll(), container);\n }\n\n}",
"public interface IntIterator {\n\n /**\n * Is there more?\n *\n * @return true, if there is more, false otherwise\n */\n boolean hasNext();\n\n /**\n * Return the next integer\n *\n * @return the integer\n */\n int next();\n}",
"static int maxSizeInBits(final EWAHCompressedBitmap32... bitmaps) {\n int maxSizeInBits = 0;\n for(EWAHCompressedBitmap32 bitmap : bitmaps) {\n maxSizeInBits = Math.max(maxSizeInBits, bitmap.sizeInBits());\n }\n return maxSizeInBits;\n}",
"public static final int WORD_IN_BITS = 32;"
] | import com.googlecode.javaewah.ChunkIterator;
import com.googlecode.javaewah.FastAggregation;
import com.googlecode.javaewah.IntIterator;
import org.junit.Assert;
import org.junit.Test;
import java.io.*;
import java.nio.IntBuffer;
import java.util.*;
import static com.googlecode.javaewah32.EWAHCompressedBitmap32.maxSizeInBits;
import static com.googlecode.javaewah32.EWAHCompressedBitmap32.WORD_IN_BITS;
| Assert.assertEquals(i, iterator.next());
}
for(int i= WORD_IN_BITS; i< WORD_IN_BITS + WORD_IN_BITS/2; ++i) {
Assert.assertTrue(iterator.hasNext());
Assert.assertEquals(i, iterator.next());
}
Assert.assertFalse(iterator.hasNext());
}
@Test
public void reverseIntIterator() {
int[] positions = new int[] { 0, 1, 2, 3, 5, 8, 13, 21 };
EWAHCompressedBitmap32 bitmap = EWAHCompressedBitmap32.bitmapOf(positions);
IntIterator iterator = bitmap.reverseIntIterator();
for(int i=positions.length-1; i>=0; --i) {
Assert.assertTrue(iterator.hasNext());
Assert.assertEquals(positions[i], iterator.next());
}
Assert.assertFalse(iterator.hasNext());
}
@Test
public void reverseIntIteratorOverBitmapsOfOnes() {
EWAHCompressedBitmap32 bitmap = EWAHCompressedBitmap32.bitmapOf();
bitmap.setSizeInBits(WORD_IN_BITS, true);
IntIterator iterator = bitmap.reverseIntIterator();
for(int i= WORD_IN_BITS-1; i>=0; --i) {
Assert.assertTrue(iterator.hasNext());
Assert.assertEquals(i, iterator.next());
}
Assert.assertFalse(iterator.hasNext());
}
@Test
public void reverseIntIteratorOverBitmapsOfZeros() {
EWAHCompressedBitmap32 bitmap = EWAHCompressedBitmap32.bitmapOf();
bitmap.setSizeInBits(WORD_IN_BITS, false);
IntIterator iterator = bitmap.reverseIntIterator();
Assert.assertFalse(iterator.hasNext());
}
@Test
public void reverseIntIteratorOverBitmapsOfOnesAndZeros() {
EWAHCompressedBitmap32 bitmap = EWAHCompressedBitmap32.bitmapOf();
bitmap.setSizeInBits(WORD_IN_BITS-10, true);
bitmap.setSizeInBits(WORD_IN_BITS, false);
IntIterator iterator = bitmap.reverseIntIterator();
for(int i= WORD_IN_BITS-10; i>0; --i) {
Assert.assertTrue(iterator.hasNext());
Assert.assertEquals(i-1, iterator.next());
}
Assert.assertFalse(iterator.hasNext());
}
@Test
public void reverseIntIteratorOverMultipleRLWs() {
EWAHCompressedBitmap32 b = EWAHCompressedBitmap32.bitmapOf(1000, 100000, 100000 + WORD_IN_BITS);
IntIterator iterator = b.reverseIntIterator();
Assert.assertTrue(iterator.hasNext());
Assert.assertEquals(100000 + WORD_IN_BITS, iterator.next());
Assert.assertTrue(iterator.hasNext());
Assert.assertEquals(100000, iterator.next());
Assert.assertTrue(iterator.hasNext());
Assert.assertEquals(1000, iterator.next());
Assert.assertFalse(iterator.hasNext());
}
@Test
public void reverseIntIteratorOverMixedRunningLengthWords() {
EWAHCompressedBitmap32 b = new EWAHCompressedBitmap32();
b.setSizeInBits(WORD_IN_BITS, true);
b.set(WORD_IN_BITS + 5);
IntIterator iterator = b.reverseIntIterator();
Assert.assertTrue(iterator.hasNext());
Assert.assertEquals(WORD_IN_BITS+5, iterator.next());
for(int i= WORD_IN_BITS-1; i>=0; --i) {
Assert.assertTrue(iterator.hasNext());
Assert.assertEquals(i, iterator.next());
}
Assert.assertFalse(iterator.hasNext());
}
@Test
public void reverseIntIteratorOverConsecutiveLiteralsInSameRunningLengthWord() {
EWAHCompressedBitmap32 b = new EWAHCompressedBitmap32();
b.setSizeInBits(WORD_IN_BITS, true);
b.setSizeInBits(2*WORD_IN_BITS, false);
b.setSizeInBits(3*WORD_IN_BITS, true);
b.set(3*WORD_IN_BITS+5);
b.set(5*WORD_IN_BITS-1);
IntIterator iterator = b.reverseIntIterator();
Assert.assertTrue(iterator.hasNext());
Assert.assertEquals(5*WORD_IN_BITS - 1, iterator.next());
Assert.assertTrue(iterator.hasNext());
Assert.assertEquals(3*WORD_IN_BITS+5, iterator.next());
for(int i=3*WORD_IN_BITS-1; i>=2*WORD_IN_BITS; --i) {
Assert.assertTrue(iterator.hasNext());
Assert.assertEquals(i, iterator.next());
}
for(int i= WORD_IN_BITS-1; i>=0; --i) {
Assert.assertTrue(iterator.hasNext());
Assert.assertEquals(i, iterator.next());
}
Assert.assertFalse(iterator.hasNext());
}
@Test
public void isEmpty() {
EWAHCompressedBitmap32 bitmap = EWAHCompressedBitmap32.bitmapOf();
bitmap.setSizeInBits(1000, false);
Assert.assertTrue(bitmap.isEmpty());
bitmap.set(1001);
Assert.assertFalse(bitmap.isEmpty());
}
@Test
public void issue58() {
EWAHCompressedBitmap32 bitmap = EWAHCompressedBitmap32.bitmapOf(52344, 52344 + 9);
| ChunkIterator iterator = bitmap.chunkIterator();
| 0 |
bafomdad/realfilingcabinet | com/bafomdad/realfilingcabinet/integration/WailaRFC.java | [
"public class BlockManaCabinet extends Block implements IFilingCabinet {\n\t\n\tpublic static final PropertyDirection FACING = BlockHorizontal.FACING;\n\n\tpublic BlockManaCabinet() {\n\t\t\n\t\tsuper(Material.ROCK);\n\t\tsetRegistryName(\"manacabinet\");\n\t\tsetTranslationKey(RealFilingCabinet.MOD_ID + \".manacabinet\");\n\t\tsetHardness(5.0F);\n\t\tsetResistance(1000.0F);\n\t\tsetCreativeTab(TabRFC.instance);\n\t\t\n\t\tsetDefaultState(blockState.getBaseState().withProperty(FACING, EnumFacing.NORTH));\n\t}\n\t\n\t@Override\n\tprotected BlockStateContainer createBlockState() {\n\t\t\n\t\treturn new BlockStateContainer(this, FACING);\n\t}\n\t\n @Override\n public boolean isSideSolid(IBlockState state, IBlockAccess world, BlockPos pos, EnumFacing side) {\n \t\n \tif (side == EnumFacing.DOWN || side.getIndex() == state.getValue(FACING).getIndex()) {\n \t\treturn false;\n \t}\n \treturn true;\n }\n \n @Override\n public boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) {\n \t\n \tif (hand == EnumHand.MAIN_HAND) {\n \tTileEntity tile = world.getTileEntity(pos);\n \tif (tile != null && tile instanceof TileManaCabinet)\n \t\trightClick(tile, player, facing, hitX, hitY, hitZ);\n \t\n return true;\n \t}\n \treturn false;\n }\n \n\t@Override\n\tpublic void onBlockPlacedBy(World world, BlockPos pos, IBlockState state, EntityLivingBase entity, ItemStack stack) {\n\t\t\n\t\tworld.setBlockState(pos, state.withProperty(FACING, entity.getHorizontalFacing().getOpposite()), 2);\n\t\tTileEntity tile = world.getTileEntity(pos);\n\t\tif (tile instanceof TileManaCabinet) {\n\t\t\tif (stack.hasTagCompound())\n\t\t\t\t((TileManaCabinet)tile).readInv(stack.getTagCompound());\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic IBlockState getStateFromMeta(int meta) {\n\t\t\n\t\treturn getDefaultState().withProperty(FACING, EnumFacing.byHorizontalIndex(meta));\n\t}\n\t\n\t@Override\n\tpublic int getMetaFromState(IBlockState state) {\n\t\t\n\t\treturn state.getValue(FACING).getHorizontalIndex();\n\t}\n\t\n\t@Override\n public boolean removedByPlayer(IBlockState state, World world, BlockPos pos, EntityPlayer player, boolean willHarvest) {\n \t\n \tif (player.capabilities.isCreativeMode && !world.isRemote) {\n \t\tthis.harvestBlock(world, player, pos, state, world.getTileEntity(pos), player.getActiveItemStack());\n \t}\n \treturn willHarvest || super.removedByPlayer(state, world, pos, player, false);\n }\n\t\n\t@Override\n\tpublic void harvestBlock(World world, EntityPlayer player, BlockPos pos, IBlockState state, TileEntity tile, ItemStack stack) {\n\t\t\n\t\tsuper.harvestBlock(world, player, pos, state, tile, stack);\n\t\tworld.setBlockToAir(pos);\n\t}\n\t\n\t@Override\n\tpublic void getDrops(NonNullList<ItemStack> drops, IBlockAccess world, BlockPos pos, IBlockState state, int fortune) {\n\t\t\n\t\tItemStack s = new ItemStack(this);\n\t\tTileEntity tile = world.getTileEntity(pos);\n\t\tif (!(tile instanceof TileManaCabinet)) return;\n\t\t\n\t\tNBTTagCompound tag = new NBTTagCompound();\n\t\t((TileManaCabinet)tile).writeInv(tag, true);\n\t\tif (!tag.isEmpty()) {\n\t\t\ts.setTagCompound(tag);\n\t\t\tdrops.add(s);\n\t\t\treturn;\n\t\t}\n\t}\n\n\t@Override\n\tpublic void leftClick(TileEntity tile, EntityPlayer player) {}\n\n\t@Override\n\tpublic void rightClick(TileEntity tile, EntityPlayer player, EnumFacing side, float hitX, float hity, float hitZ) {\n\n\t\tTileManaCabinet tileMana = (TileManaCabinet)tile;\n\t\tItemStack stack = player.getHeldItem(EnumHand.MAIN_HAND);\n\t\t\n\t\tif (tileMana.isCabinetLocked()) {\n\t\t\tif (!tileMana.getCabinetOwner().equals(player.getUniqueID()) && !tileMana.hasKeyCopy(player, tileMana.getCabinetOwner()))\n\t\t\t\treturn;\n\t\t}\n\t\tif (!player.isSneaking() && !stack.isEmpty()) {\n\t\t\tif (stack.getItem() instanceof ItemKeys) {\n\t\t\t\tif (!tileMana.isCabinetLocked()) {\n\t\t\t\t\tif (stack.getItemDamage() == 0)\n\t\t\t\t\t\ttileMana.setOwner(player.getUniqueID());\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif (tileMana.getCabinetOwner().equals(player.getUniqueID()) && stack.getItemDamage() == 0) {\n\t\t\t\t\t\ttileMana.setOwner(null);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (tileMana.getCabinetOwner().equals(player.getUniqueID()) && stack.getItemDamage() == 1) {\n\t\t\t\t\t\tif (!stack.hasTagCompound() || (stack.hasTagCompound() && !stack.getTagCompound().hasKey(StringLibs.RFC_COPY))) {\n\t\t\t\t\t\t\tNBTUtils.setString(stack, StringLibs.RFC_COPY, player.getUniqueID().toString());\n\t\t\t\t\t\t\tNBTUtils.setString(stack, StringLibs.RFC_FALLBACK, player.getDisplayNameString());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (stack.getItem() == BotaniaRFC.manaFolder && tileMana.isOpen) {\n\t\t\t\tfor (int i = 0; i < tileMana.getInv().getSlots(); i++) {\n\t\t\t\t\tItemStack tileStack = tileMana.getInv().getStackInSlot(i);\n\t\t\t\t\tif (tileStack.isEmpty()) {\n\t\t\t\t\t\ttileMana.getInv().setStackInSlot(i, stack);\n\t\t\t\t\t\tplayer.setHeldItem(EnumHand.MAIN_HAND, ItemStack.EMPTY);\n\t\t\t\t\t\ttileMana.markBlockForRenderUpdate();\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tif (!player.isSneaking() && stack.isEmpty()) {\n\t\t\tif (!tileMana.getWorld().isRemote) {\n\t\t\t\tif (tileMana.isOpen)\n\t\t\t\t\ttileMana.isOpen = false;\n\t\t\t\telse\n\t\t\t\t\ttileMana.isOpen = true;\n\t\t\t\ttileMana.markDirty();\n\t\t\t}\n\t\t\ttileMana.markBlockForUpdate();\n\t\t}\n\t\tif (player.isSneaking() && stack.isEmpty() && tileMana.isOpen) {\n\t\t\tfor (int i = tileMana.getInv().getSlots() - 1; i >= 0; i--) {\n\t\t\t\tItemStack folder = tileMana.getInv().getStackInSlot(i);\n\t\t\t\tif (!folder.isEmpty()) {\n\t\t\t\t\ttileMana.getInv().setStackInSlot(i, ItemStack.EMPTY);\n\t\t\t\t\tplayer.setHeldItem(EnumHand.MAIN_HAND, folder);\n\t\t\t\t\ttileMana.markBlockForUpdate();\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\t@Override\n\t@SideOnly(Side.CLIENT)\n\tpublic boolean shouldSideBeRendered(IBlockState state, IBlockAccess world, BlockPos pos, EnumFacing side) {\n\t\t\n\t\treturn false;\n\t}\n\t\n\t@Override\n\tpublic boolean isBlockNormalCube(IBlockState state) {\n\t\t\n\t\treturn false;\n\t}\n\t\n\t@Override\n\tpublic boolean isOpaqueCube(IBlockState state) {\n\t\t\n\t\treturn false;\n\t}\n\t\n\t@Override\n public boolean isFullCube(IBlockState state) {\n \n\t\treturn false;\n }\n\t\n\t@Override\n public EnumBlockRenderType getRenderType(IBlockState state)\n {\n return EnumBlockRenderType.ENTITYBLOCK_ANIMATED;\n }\n\t\n\t@Override\n public float getPlayerRelativeBlockHardness(IBlockState state, EntityPlayer player, World world, BlockPos pos) {\n\t\t\n\t\tTileManaCabinet tileMana = (TileManaCabinet)world.getTileEntity(pos);\n\t\tif (tileMana != null && tileMana.isCabinetLocked()) {\n\t\t\tif (!tileMana.getCabinetOwner().equals(player.getUniqueID()))\n\t\t\t\treturn -1.0F;\n\t\t}\n\t\treturn ForgeHooks.blockStrength(state, player, world, pos);\n\t}\n\t\n\t@Override\n\tpublic TileEntity createNewTileEntity(World worldIn, int meta) {\n\n\t\treturn new TileManaCabinet();\n\t}\n}",
"@Optional.Interface(iface = \"com.jaquadro.minecraft.storagedrawers.api.storage.INetworked\", modid = RealFilingCabinet.STORAGEDRAWERS, striprefs = true)\npublic class BlockRFC extends Block implements IFilingCabinet, INetworked {\n\t\n\tstatic float f = 0.0625F;\n\tprotected static final AxisAlignedBB BASE_AABB = new AxisAlignedBB(0.0D + f, 0.0D, 0.0D + f, 1.0D - f, 1.0D - f, 1.0D - f);\n\n\tpublic static final PropertyDirection FACING = BlockHorizontal.FACING;\n\t\n\tpublic BlockRFC() {\n\t\t\n\t\tsuper(Material.IRON);\n\t\tsetRegistryName(\"modelcabinet\");\n\t\tsetTranslationKey(RealFilingCabinet.MOD_ID + \".filingcabinet\");\n\t\tsetHardness(5.0F);\n\t\tsetResistance(1000.0F);\n\t\tsetCreativeTab(TabRFC.instance);\n\t\t\n\t\tsetDefaultState(blockState.getBaseState().withProperty(FACING, EnumFacing.NORTH));\n\t}\n\t\n\t@Override\n\tprotected BlockStateContainer createBlockState() {\n\t\t\n\t\treturn new BlockStateContainer(this, FACING);\n\t}\n\t\n\t@Override\n\tpublic void addCollisionBoxToList(IBlockState state, World worldIn, BlockPos pos, AxisAlignedBB aabb, List<AxisAlignedBB> collidingBoxes, @Nullable Entity entityIn, boolean wat) {\n \n \taddCollisionBoxToList(pos, aabb, collidingBoxes, BASE_AABB);\n }\n\t\n @Override\n public void onEntityCollision(World world, BlockPos pos, IBlockState state, Entity entity) {\n \t\n \tTileEntityRFC tileRFC = (TileEntityRFC)world.getTileEntity(pos);\n \tif (UpgradeHelper.getUpgrade(tileRFC, StringLibs.TAG_MOB) == null)\n \t\treturn;\n \t\n \tif (!(entity instanceof EntityLivingBase) || entity instanceof EntityPlayer)\n \t\treturn;\n \t\n \tEntityLivingBase elb = (EntityLivingBase)entity;\n \tif (!elb.isNonBoss() || (elb.isChild() && !(elb instanceof EntityZombie)))\n \t\treturn;\n \t\n// \tResourceLocation res = EntityList.getKey(elb);\n \tfor (int i = 0; i < tileRFC.getInventory().getSlots(); i++) {\n \t\tItemStack folder = tileRFC.getInventory().getTrueStackInSlot(i);\n \t\tif (!folder.isEmpty() && folder.getItem() == RFCItems.folder) {\n \t\t\tObject obj = ItemFolder.getObject(folder);\n \t\t\tif (folder.getItemDamage() == 3 && obj != null) {\n \t\t\t\tif (obj.equals(entity.getClass())) {\n \t\t\t\t\tMobUtils.dropMobEquips(world, elb);\n \t\t\t\t\telb.setDead();\n \t\t\t\t\tItemFolder.add(folder, 1);\n \t\t\t\t\tbreak;\n \t\t\t\t}\n \t\t\t}\n \t\t}\n \t}\n }\n\t\n @Override\n\tpublic void onBlockClicked(World world, BlockPos pos, EntityPlayer player) {\n\t\t\n\t\tTileEntity tile = world.getTileEntity(pos);\n\t\tif (!world.isRemote && !player.capabilities.isCreativeMode) {\n\t\t\tif (tile instanceof TileEntityRFC)\n\t\t\t\tleftClick(tile, player);\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic boolean onBlockActivated(World world, BlockPos pos, IBlockState state, EntityPlayer player, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) {\n \t\n\t\tif (hand == EnumHand.MAIN_HAND) {\n\t\t\tTileEntity tile = world.getTileEntity(pos);\n\t \tif (tile instanceof TileEntityRFC)\n\t \t\trightClick(tile, player, facing, hitX, hitY, hitZ);\n\t \t\n\t \treturn true;\n\t\t}\n return false;\n }\n\t\n\t@Override\n\tpublic void onBlockPlacedBy(World world, BlockPos pos, IBlockState state, EntityLivingBase entity, ItemStack stack) {\n\t\t\n\t\tworld.setBlockState(pos, state.withProperty(FACING, entity.getHorizontalFacing().getOpposite()), 2);\n\t\tTileEntity tile = world.getTileEntity(pos);\n\t\tif (tile != null && tile instanceof TileEntityRFC) {\n\t\t\tif (stack.hasTagCompound())\n\t\t\t\t((TileEntityRFC)tile).readInv(stack.getTagCompound());\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic IBlockState getStateFromMeta(int meta) {\n\t\t\n\t\treturn getDefaultState().withProperty(FACING, EnumFacing.byHorizontalIndex(meta));\n\t}\n\t\n\t@Override\n\tpublic int getMetaFromState(IBlockState state) {\n\t\t\n\t\treturn state.getValue(FACING).getHorizontalIndex();\n\t}\n\t\n\t@Override\n public boolean removedByPlayer(IBlockState state, World world, BlockPos pos, EntityPlayer player, boolean willHarvest) {\n \t\n \tif (player.capabilities.isCreativeMode && !world.isRemote)\n \t\tthis.harvestBlock(world, player, pos, state, world.getTileEntity(pos), player.getActiveItemStack());\n\n \treturn willHarvest || super.removedByPlayer(state, world, pos, player, false);\n }\n\t\n\t@Override\n\tpublic void harvestBlock(World world, EntityPlayer player, BlockPos pos, IBlockState state, TileEntity tile, ItemStack stack) {\n\n\t\tsuper.harvestBlock(world, player, pos, state, tile, stack);\n\t\tworld.setBlockToAir(pos);\n\t}\n\t\n\t@Override\n\tpublic void breakBlock(World world, BlockPos pos, IBlockState state) {\n\t\t\n\t\tTileEntity tile = world.getTileEntity(pos);\n\t\tif (tile instanceof TileEntityRFC) {\n\t\t\tItemStack upgrade = UpgradeHelper.stackTest((TileEntityRFC)tile);\n\t\t\tif (!upgrade.isEmpty() && upgrade.getItemDamage() != ItemUpgrades.UpgradeType.LIFE.ordinal()) {\n\t\t\t\tif (upgrade.getCount() == 0)\n\t\t\t\t\tupgrade.setCount(1);\n\t\t\t\tInventoryHelper.spawnItemStack(world, pos.getX(), pos.getY(), pos.getZ(), upgrade);\n\t\t\t}\n\t\t}\n\t\tsuper.breakBlock(world, pos, state);\n\t}\n\t\n\t@Override\n\tpublic void getDrops(NonNullList<ItemStack> drops, IBlockAccess world, BlockPos pos, IBlockState state, int fortune) {\n\t\t\n\t\tItemStack s = new ItemStack(this);\n\t\tTileEntity tile = world.getTileEntity(pos);\n\t\tif (!(tile instanceof TileEntityRFC)) return;\n\t\t\n\t\tNBTTagCompound tag = new NBTTagCompound();\n\t\t((TileEntityRFC)tile).writeInv(tag, true);\n\t\tif (!tag.isEmpty()) {\n\t\t\ts.setTagCompound(tag);\n\t\t}\n\t\tdrops.add(s);\n\t\treturn;\n\t}\n\n\t@Override\n\tpublic TileEntity createNewTileEntity(World world, int meta) {\n\n\t\treturn new TileEntityRFC();\n\t}\n\n\t@Override\n\tpublic void leftClick(TileEntity tile, EntityPlayer player) {\n\t\t\n\t\tif (player.capabilities.isCreativeMode)\n\t\t\treturn;\n\t\t\n\t\tTileEntityRFC tileRFC = (TileEntityRFC)tile;\n\t\t\n\t\tif (tileRFC.isCabinetLocked()) {\n\t\t\tif (!tileRFC.getCabinetOwner().equals(player.getUniqueID())) {\n\t\t\t\tif (!tileRFC.hasKeyCopy(player, tileRFC.getCabinetOwner()))\n\t\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tif (player.isSneaking() && !player.getHeldItem(EnumHand.MAIN_HAND).isEmpty() && player.getHeldItem(EnumHand.MAIN_HAND).getItem() == RFCItems.magnifyingGlass) {\n\t\t\tif (!tileRFC.getWorld().isRemote) {\n\t\t\t\tUpgradeHelper.removeUpgrade(player, tileRFC);\n\t\t\t}\n\t\t\ttileRFC.markBlockForUpdate();\n\t\t\treturn;\n\t\t}\n\t\tif (UpgradeHelper.getUpgrade(tileRFC, StringLibs.TAG_CRAFT) == null) {\n\t\t\tStorageUtils.extractStackManually(tileRFC, player, player.isSneaking());\n\t\t\treturn;\n\t\t} else {\n\t\t\tItemStack toCraft = tileRFC.getFilter().copy();\n\t\t\tif (!tileRFC.getFilter().isEmpty() && toCraft.isItemDamaged())\n\t\t\t\ttoCraft.setItemDamage(0);\n\t\t\t\t\n\t\t\tif (AutocraftingUtils.canCraft(tileRFC.getFilter(), tileRFC)) {\n\t\t\t\tItemStack stack = toCraft;\n\t\t\t\tstack.setCount(AutocraftingUtils.getOutputSize());\n\t\t\t\tif (!UpgradeHelper.isCreative(tileRFC))\n\t\t\t\t\tAutocraftingUtils.doCraft(tileRFC.getFilter(), tileRFC.getInventory());\n\t\t\t\tItemHandlerHelper.giveItemToPlayer(player, stack);\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic void rightClick(TileEntity tile, EntityPlayer player, EnumFacing side, float hitX, float hitY, float hitZ) {\n\n\t\tTileEntityRFC tileRFC = (TileEntityRFC)tile;\n\t\tItemStack stack = player.getHeldItemMainhand();\n\t\t\n\t\tif (tileRFC.isCabinetLocked()) {\n\t\t\tif (!tileRFC.getCabinetOwner().equals(player.getUniqueID())) {\n\t\t\t\tif (!tileRFC.hasKeyCopy(player, tileRFC.getCabinetOwner()))\n\t\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tif (tileRFC.calcLastClick(player))\n\t\t\tStorageUtils.addAllStacksManually(tileRFC, player);\n\n\t\tif (!player.isSneaking() && !stack.isEmpty()) {\n\t\t\tif (stack.getItem() instanceof ItemKeys) {\n\t\t\t\tif (!tileRFC.isCabinetLocked()) {\n\t\t\t\t\tif (stack.getItemDamage() == 0)\n\t\t\t\t\t\ttileRFC.setOwner(player.getUniqueID());\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tif (tileRFC.getCabinetOwner().equals(player.getUniqueID()) && stack.getItemDamage() == 0) {\n\t\t\t\t\t\ttileRFC.setOwner(null);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (tileRFC.getCabinetOwner().equals(player.getUniqueID()) && stack.getItemDamage() == 1) {\n\t\t\t\t\t\tif (!stack.hasTagCompound() || (stack.hasTagCompound() && !stack.getTagCompound().hasKey(StringLibs.RFC_COPY))) {\n\t\t\t\t\t\t\tNBTUtils.setString(stack, StringLibs.RFC_COPY, player.getUniqueID().toString());\n\t\t\t\t\t\t\tNBTUtils.setString(stack, StringLibs.RFC_FALLBACK, player.getDisplayNameString());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (stack.getItem() instanceof IFolder && tileRFC.isOpen) {\n\t\t\t\tif (UpgradeHelper.getUpgrade(tileRFC, StringLibs.TAG_ENDER) != null) {\n\t\t\t\t\tif (stack.getItem() == RFCItems.folder && stack.getItemDamage() == FolderType.ENDER.ordinal())\n\t\t\t\t\t\tplayer.setHeldItem(EnumHand.MAIN_HAND, ItemStack.EMPTY);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (stack.getItemDamage() == FolderType.FLUID.ordinal() && UpgradeHelper.getUpgrade(tileRFC, StringLibs.TAG_FLUID) != null) {\n\t\t\t\t\tfor (int i = 0; i < tileRFC.getInventory().getSlots(); i++) {\n\t\t\t\t\t\tItemStack tileStack = tileRFC.getInventory().getTrueStackInSlot(i);\n\t\t\t\t\t\tif (tileStack.isEmpty()) {\n\t\t\t\t\t\t\ttileRFC.getInventory().setStackInSlot(i, stack);\n\t\t\t\t\t\t\tplayer.setHeldItem(EnumHand.MAIN_HAND, ItemStack.EMPTY);\n\t\t\t\t\t\t\ttileRFC.markBlockForUpdate();\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\telse if (!(stack.getItem() == RFCItems.folder && stack.getItemDamage() == 1) && !tileRFC.getWorld().isRemote) {\n\t\t\t\t\tif (UpgradeHelper.getUpgrade(tileRFC, StringLibs.TAG_FLUID) != null && !FluidUtils.canAcceptFluidContainer(stack))\n\t\t\t\t\t\treturn;\n\n\t\t\t\t\tfor (int i = 0; i < tileRFC.getInventory().getSlots(); i++) {\n\t\t\t\t\t\tItemStack tileStack = tileRFC.getInventory().getTrueStackInSlot(i);\n\t\t\t\t\t\tif (tileStack.isEmpty()) {\n\t\t\t\t\t\t\ttileRFC.getInventory().setStackInSlot(i, stack);\n\t\t\t\t\t\t\tplayer.setHeldItem(EnumHand.MAIN_HAND, ItemStack.EMPTY);\n\t\t\t\t\t\t\ttileRFC.markBlockForUpdate();\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (stack.getItem() instanceof IUpgrades) {\n\t\t\t\tif (!tileRFC.getWorld().isRemote) {\n\t\t\t\t\tUpgradeHelper.setUpgrade(player, tileRFC, stack);\n\t\t\t\t}\n\t\t\t\ttileRFC.markBlockForUpdate();\n\t\t\t\treturn;\n\t\t\t} else {\n\t\t\t\tStorageUtils.addStackManually(tileRFC, player, stack);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tif (!player.isSneaking() && stack.isEmpty()) {\t\n\t\t\tif (!tileRFC.getWorld().isRemote) {\n\t\t\t\ttileRFC.isOpen = !tileRFC.isOpen;\n\t\t\t\ttileRFC.markDirty();\n\t\t\t}\n\t\t\ttileRFC.markBlockForUpdate();\n\t\t}\n\t\tif (player.isSneaking() && stack.isEmpty() && tileRFC.isOpen) {\t\t\n\t\t\tif (UpgradeHelper.getUpgrade(tileRFC, StringLibs.TAG_ENDER) != null) {\n\t\t\t\tEnderUtils.extractEnderFolder(tileRFC, player);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tStorageUtils.folderExtract(tileRFC, player, side, hitX, hitY, hitZ);\n\t\t}\n\t}\n\t\n\t@Override\n\t@SideOnly(Side.CLIENT)\n\tpublic boolean shouldSideBeRendered(IBlockState state, IBlockAccess world, BlockPos pos, EnumFacing side) {\n\t\t\n\t\treturn false;\n\t}\n\t\n\t@Override\n\tpublic boolean isBlockNormalCube(IBlockState state) {\n\t\t\n\t\treturn false;\n\t}\n\t\n\t@Override\n\tpublic boolean isOpaqueCube(IBlockState state) {\n\t\t\n\t\treturn false;\n\t}\n\t\n\t@Override\n public boolean isFullCube(IBlockState state) {\n\t\t\n return false;\n }\n\t\n\t@Override\n public EnumBlockRenderType getRenderType(IBlockState state) {\n\t\t\n return EnumBlockRenderType.ENTITYBLOCK_ANIMATED;\n }\n\t\n\t@Override\n public float getPlayerRelativeBlockHardness(IBlockState state, EntityPlayer player, World world, BlockPos pos) {\n\t\t\n\t\tTileEntityRFC tileRFC = (TileEntityRFC)world.getTileEntity(pos);\n\t\tif (tileRFC != null && tileRFC.isCabinetLocked()) {\n\t\t\tif (!tileRFC.getCabinetOwner().equals(player.getUniqueID()))\n\t\t\t\treturn -1.0F;\n\t\t}\n\t\treturn ForgeHooks.blockStrength(state, player, world, pos);\n\t}\n\t\n\t// copied from vanilla furnace\n\t@Override\n @SuppressWarnings(\"incomplete-switch\")\n public void randomDisplayTick(IBlockState stateIn, World worldIn, BlockPos pos, Random rand) {\n \t\n\t\tTileEntity tile = worldIn.getTileEntity(pos);\n\t\tif (!(tile instanceof TileEntityRFC)) return;\n\t\t\n if (SmeltingUtils.isSmelting((TileEntityRFC)tile)) {\n EnumFacing enumfacing = (EnumFacing)stateIn.getValue(FACING);\n double d0 = (double)pos.getX() + 0.5D;\n double d1 = (double)pos.getY() + rand.nextDouble() * 6.0D / 16.0D;\n double d2 = (double)pos.getZ() + 0.5D;\n double d3 = 0.52D;\n double d4 = rand.nextDouble() * 0.6D - 0.3D;\n\n if (rand.nextDouble() < 0.1D)\n worldIn.playSound((double)pos.getX() + 0.5D, (double)pos.getY(), (double)pos.getZ() + 0.5D, SoundEvents.BLOCK_FURNACE_FIRE_CRACKLE, SoundCategory.BLOCKS, 1.0F, 1.0F, false);\n\n switch (enumfacing) {\n case WEST:\n worldIn.spawnParticle(EnumParticleTypes.SMOKE_NORMAL, d0 - 0.52D, d1, d2 + d4, 0.0D, 0.0D, 0.0D);\n worldIn.spawnParticle(EnumParticleTypes.FLAME, d0 - 0.52D, d1, d2 + d4, 0.0D, 0.0D, 0.0D);\n break;\n case EAST:\n worldIn.spawnParticle(EnumParticleTypes.SMOKE_NORMAL, d0 + 0.52D, d1, d2 + d4, 0.0D, 0.0D, 0.0D);\n worldIn.spawnParticle(EnumParticleTypes.FLAME, d0 + 0.52D, d1, d2 + d4, 0.0D, 0.0D, 0.0D);\n break;\n case NORTH:\n worldIn.spawnParticle(EnumParticleTypes.SMOKE_NORMAL, d0 + d4, d1, d2 - 0.52D, 0.0D, 0.0D, 0.0D);\n worldIn.spawnParticle(EnumParticleTypes.FLAME, d0 + d4, d1, d2 - 0.52D, 0.0D, 0.0D, 0.0D);\n break;\n case SOUTH:\n worldIn.spawnParticle(EnumParticleTypes.SMOKE_NORMAL, d0 + d4, d1, d2 + 0.52D, 0.0D, 0.0D, 0.0D);\n worldIn.spawnParticle(EnumParticleTypes.FLAME, d0 + d4, d1, d2 + 0.52D, 0.0D, 0.0D, 0.0D);\n }\n }\n }\n}",
"@Optional.Interface(iface = \"com.jaquadro.minecraft.storagedrawers.api.storage.IDrawerGroup\", modid = RealFilingCabinet.STORAGEDRAWERS, striprefs = true)\npublic class TileEntityRFC extends TileFilingCabinet implements ITickable, ILockableCabinet, IDrawerGroup {\n\n\tprivate InventoryRFC inv = new InventoryRFC(this, 8);\n\tprivate FluidRFC fluidinv = new FluidRFC(this);\n\t\n\tprivate UUID owner;\n\t\n\t// MISC variables\n\tprivate long lastClickTime;\n\tprivate UUID lastClickUUID;\n\t\n\t// NBT variables\n\tprivate int rfcHash = -1;\n\tpublic boolean isCreative = false;\n\tpublic String upgrades = \"\";\n\tpublic List<int[]> smeltingJobs = Lists.newArrayList();\n\tpublic int fuelTime = 0;\n\tpublic ItemStack uncraftableItem = ItemStack.EMPTY;\n\t\n\t// Rendering variables\n\tpublic static final float offsetSpeed = 0.1F;\n\tpublic boolean isOpen = false;\n\n\t@Override\n\tpublic void update() {\n\t\t\n\t\tif (isOpen) {\n\t\t\toffset -= offsetSpeed;\n\t\t\tif (offset <= -0.75F)\n\t\t\t\toffset = -0.75F;\n\t\t} else {\n\t\t\toffset += offsetSpeed;\n\t\t\tif (offset >= 0.05F)\n\t\t\t\toffset = 0.05F;\n\t\t}\n\t\tif (SmeltingUtils.canSmelt(this)) {\n//\t\t\tif (!world.isRemote) {\n\t\t\t\tSmeltingUtils.incrementSmeltTime(this);\n\t\t\t\tif (getWorld().getTotalWorldTime() % 40 == 0) {\n\t\t\t\t\tSmeltingUtils.createSmeltingJob(this);\n\t\t\t\t\tthis.markBlockForUpdate();\n\t\t\t\t}\n//\t\t\t}\n\t\t\treturn;\n\t\t}\n\t\tif (UpgradeHelper.getUpgrade(this, StringLibs.TAG_LIFE) != null) {\n\t\t\tif (!world.isRemote) {\n\t\t\t\tEntityCabinet cabinet = new EntityCabinet(world);\n\t\t\t\tIBlockState state = world.getBlockState(getPos());\n\t\t\t\tfloat angle = state.getActualState(world, pos).getValue(BlockHorizontal.FACING).getHorizontalAngle();\n\t\t\t\tcabinet.setPosition(pos.getX() + 0.5, pos.getY(), pos.getZ() + 0.5);\n\t\t\t\tcabinet.setRotationYawHead(angle);\n\t\t\t\t\n\t\t\t\tfor (int i = 0; i < this.getInventory().getSlots(); i++) {\n\t\t\t\t\tItemStack folder = this.getInventory().getTrueStackInSlot(i);\n\t\t\t\t\tif (folder != null) {\n\t\t\t\t\t\tcabinet.setInventory(i, folder.copy());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif (this.isCabinetLocked()) {\n\t\t\t\t\tUUID uuid = this.getCabinetOwner();\n\t\t\t\t\tcabinet.setOwnerId(uuid);\n\t\t\t\t} else\n\t\t\t\t\tcabinet.homePos = getPos().toLong();\n\t\t\t\t\n\t\t\t\tif (!cabinet.isLegit())\n\t\t\t\t\tcabinet.setLegit();\n\t\t\t\t\n\t\t\t\tworld.spawnEntity(cabinet);\n\t\t\t}\n\t\t\tworld.setBlockToAir(getPos());\n\t\t}\n\t}\n\t\n\t@Override\n public NBTTagCompound getUpdateTag() {\n\t\t\n\t\treturn writeToNBT(new NBTTagCompound());\n }\n\t\n\t@Nullable\n\t@Override\n\tpublic SPacketUpdateTileEntity getUpdatePacket() {\n\t\t\n\t\tNBTTagCompound nbtTag = new NBTTagCompound();\n\t\tthis.writeCustomNBT(nbtTag);\n\t\t\n\t\treturn new SPacketUpdateTileEntity(getPos(), 1, nbtTag);\n\t}\n\n\t@Override\n\tpublic void writeCustomNBT(NBTTagCompound tag) {\n\t\t\n\t\ttag.setTag(\"inventory\", inv.serializeNBT());\n\t\ttag.setBoolean(\"isOpen\", this.isOpen);\n\t\ttag.setBoolean(StringLibs.TAG_CREATIVE, this.isCreative);\n\t\ttag.setTag(StringLibs.RFC_CRAFTABLE, uncraftableItem.serializeNBT());\n\t\t\n\t\tif (owner != null)\n\t\t\ttag.setString(\"Own\", owner.toString());\n\t\tif (rfcHash != -1)\n\t\t\ttag.setInteger(StringLibs.RFC_HASH, rfcHash);\n\t\t\n\t\ttag.setString(StringLibs.RFC_UPGRADE, upgrades);\n\t\t\n\t\tSmeltingUtils.writeSmeltNBT(this, tag);\n\t}\n\t\n\t@Override\n\tpublic void readCustomNBT(NBTTagCompound tag) {\n\t\t\n\t\tinv.deserializeNBT(tag.getCompoundTag(\"inventory\"));\n\t\tthis.isOpen = tag.getBoolean(\"isOpen\");\n\t\tthis.isCreative = tag.getBoolean(StringLibs.TAG_CREATIVE);\n\t\tif (tag.hasKey(StringLibs.RFC_CRAFTABLE))\n\t\t\tthis.uncraftableItem = new ItemStack((NBTTagCompound) tag.getTag(StringLibs.RFC_CRAFTABLE));\n\t\t\n\t\tthis.owner = null;\n\t\tif (tag.hasKey(\"Own\"))\n\t\t\towner = UUID.fromString(tag.getString(\"Own\"));\n\t\tif (tag.hasKey(StringLibs.RFC_HASH))\n\t\t\trfcHash = tag.getInteger(StringLibs.RFC_HASH);\n\t\tupgrades = tag.getString(StringLibs.RFC_UPGRADE);\n\t\t\n\t\tSmeltingUtils.readSmeltNBT(this, tag);\n\t}\n\t\n\tpublic void readInv(NBTTagCompound nbt) {\n\t\t\n\t\tNBTTagList invList = nbt.getTagList(\"inventory\", 10);\n\t\tfor (int i = 0; i < invList.tagCount(); i++) {\n\t\t\tNBTTagCompound itemTag = invList.getCompoundTagAt(i);\n\t\t\tint slot = itemTag.getByte(\"Slot\");\n\t\t\tif (slot >= 0 && slot < inv.getSlots())\n\t\t\t\tinv.getStacks().set(slot, new ItemStack(itemTag));\n\t\t}\n\t}\n\t\n\tpublic void writeInv(NBTTagCompound nbt, boolean toItem) {\n\t\t\n\t\tboolean write = false;\n\t\tNBTTagList invList = new NBTTagList();\n\t\tfor (int i = 0; i < inv.getSlots(); i++) {\n\t\t\tif (!inv.getTrueStackInSlot(i).isEmpty()) {\n\t\t\t\tif (toItem)\n\t\t\t\t\twrite = true;\n\t\t\t\tNBTTagCompound itemTag = new NBTTagCompound();\n\t\t\t\titemTag.setByte(\"Slot\", (byte)i);\n\t\t\t\tinv.getTrueStackInSlot(i).writeToNBT(itemTag);\n\t\t\t\tinvList.appendTag(itemTag);\n\t\t\t}\n\t\t}\n\t\tif (!toItem || write)\n\t\t\tnbt.setTag(\"inventory\", invList);\n\t}\n\t\n\tpublic InventoryRFC getInventory() {\n\t\t\n\t\treturn inv;\n\t}\n\t\n\tpublic IFluidHandler getFluidInventory() {\n\t\t\n\t\treturn fluidinv;\n\t}\n\t\n\tpublic boolean calcLastClick(EntityPlayer player) {\n\t\t\n\t\tboolean bool = false;\n\t\t\n\t\tif (getWorld().getTotalWorldTime() - lastClickTime < 10 && player.getPersistentID().equals(lastClickUUID)) {\n\t\t\tbool = true;\n\t\t}\n\t\tlastClickTime = getWorld().getTotalWorldTime();\n\t\tlastClickUUID = player.getPersistentID();\n\t\t\n\t\treturn bool;\n\t}\n\t\n\tpublic boolean hasItemFrame() {\n\t\t\n\t\tAxisAlignedBB aabb = new AxisAlignedBB(pos.add(0, 1, 0), pos.add(1, 2, 1));\n\t\tList<EntityItemFrame> frames = this.getWorld().getEntitiesWithinAABB(EntityItemFrame.class, aabb);\n\t\tfor (EntityItemFrame frame : frames) {\n\t\t\tEnumFacing orientation = frame.getAdjustedHorizontalFacing();\n\t\t\tIBlockState state = getWorld().getBlockState(getPos());\n\t\t\tEnumFacing rfcOrientation = (EnumFacing)state.getValue(BlockRFC.FACING);\n\t\t\t\n\t\t\treturn frame != null && orientation == rfcOrientation;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tpublic ItemStack getFilter() {\n\t\t\n\t\tAxisAlignedBB aabb = new AxisAlignedBB(pos.add(0, 1, 0), pos.add(1, 2, 1));\n\t\tList<EntityItemFrame> frames = this.getWorld().getEntitiesWithinAABB(EntityItemFrame.class, aabb);\n\t\tfor (EntityItemFrame frame : frames) {\n\t\t\tEnumFacing orientation = frame.getAdjustedHorizontalFacing();\n\t\t\tIBlockState state = getWorld().getBlockState(getPos());\n\t\t\tEnumFacing rfcOrientation = (EnumFacing)state.getValue(BlockRFC.FACING);\n\t\t\tif (frame != null && !frame.getDisplayedItem().isEmpty() && (orientation == rfcOrientation)) {\n\t\t\t\tif (frame.getDisplayedItem().getItem() == RFCItems.filter) {\n\t\t\t\t\tint rotation = frame.getRotation();\n\t\t\t\t\treturn inv.getStackFromFolder(rotation);\n\t\t\t\t}\n\t\t\t\treturn frame.getDisplayedItem();\n\t\t\t}\n\t\t}\n\t\treturn ItemStack.EMPTY;\n\t}\n\t\n\t@Override\n\tpublic boolean hasCapability(@Nonnull Capability<?> cap, EnumFacing side) {\n\t\t\n\t\tif (cap == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY && UpgradeHelper.getUpgrade(this, StringLibs.TAG_FLUID) != null)\n\t\t\treturn cap == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY;\n\t\tif (cap == DRAWER_GROUP_CAPABILITY && !UpgradeHelper.hasUpgrade(this))\n\t\t\treturn cap == DRAWER_GROUP_CAPABILITY;\n\t\t\n\t\treturn cap == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY;\n\t}\n\t\n\t@Override\n\tpublic <T> T getCapability(@Nonnull Capability<T> cap, EnumFacing side) {\n\t\t\n\t\tif (cap == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) {\n\t\t\treturn CapabilityItemHandler.ITEM_HANDLER_CAPABILITY.cast(inv);\n\t\t}\n\t\tif (cap == CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY)\n\t\t\treturn CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY.cast(fluidinv);\n\t\tif (cap == DRAWER_GROUP_CAPABILITY)\n\t\t\treturn (T) this;\n\t\t\n\t\treturn super.getCapability(cap, side);\n\t}\n\n\t@Override\n\tpublic UUID getCabinetOwner() {\n\n\t\treturn owner;\n\t}\n\n\t@Override\n\tpublic boolean setOwner(UUID owner) {\n\n\t\tif ((this.owner != null && !this.owner.equals(owner)) || (owner != null && !owner.equals(this.owner))) {\n\t\t\tthis.owner = owner;\n\t\t\t\n\t\t\tif (getWorld() != null && !getWorld().isRemote) {\n\t\t\t\tmarkDirty();\n\t\t\t\tthis.markBlockForUpdate();\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic boolean isCabinetLocked() {\n\n\t\treturn getCabinetOwner() != null;\n\t}\n\t\n\tpublic boolean hasKeyCopy(EntityPlayer player, UUID uuid) {\n\t\t\n\t\tfor (int i = 0; i < player.inventory.mainInventory.size(); i++) {\n\t\t\tItemStack keyCopy = player.inventory.mainInventory.get(i);\n\t\t\tif (keyCopy.isEmpty())\n\t\t\t\tcontinue;\n\t\t\tif (keyCopy.getItem() == RFCItems.keys && keyCopy.getItemDamage() == 1) {\n\t\t\t\tif (keyCopy.hasTagCompound() && keyCopy.getTagCompound().hasKey(StringLibs.RFC_COPY)) {\n\t\t\t\t\treturn uuid.equals(UUID.fromString(NBTUtils.getString(keyCopy, StringLibs.RFC_COPY, \"\")));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tpublic void setHash(TileEntity tile) {\n\t\t\n\t\tthis.rfcHash = EnderUtils.createHash(this);\n\t}\n\t\n\tpublic int getHash(TileEntityRFC tile) {\n\t\t\n\t\treturn this.rfcHash;\n\t}\n\n/**\n * Storage Drawers Integration begins here\n */\n\t@CapabilityInject(IDrawerGroup.class)\n\tstatic Capability<IDrawerGroup> DRAWER_GROUP_CAPABILITY = null;\n\t\n\t@Override\n\tpublic int getDrawerCount() {\n\n\t\treturn this.inv.getSlots();\n\t}\n\n\[email protected](modid = RealFilingCabinet.STORAGEDRAWERS)\n\t@Override\n\tpublic IDrawer getDrawer(int slot) {\n\n\t\treturn new CabinetData(this, slot);\n\t}\n\n\t@Override\n\tpublic int[] getAccessibleDrawerSlots() {\n\n\t\treturn new int[this.inv.getSlots()];\n\t}\n}",
"@Optional.InterfaceList({\n\[email protected](iface = \"vazkii.botania.api.mana.IManaReceiver\", modid = \"botania\"),\n\[email protected](iface = \"vazkii.botania.api.mana.spark.ISparkAttachable\", modid = \"botania\")\n})\npublic class TileManaCabinet extends TileFilingCabinet implements ITickable, ILockableCabinet, IManaReceiver, ISparkAttachable {\n\n\tprivate ItemStackHandler inv = new ItemStackHandler(8);\n\tprivate UUID owner;\n\t\n\tpublic static final float offsetSpeed = 0.1F;\n\tpublic boolean isOpen = false;\n\t\n\t@Override\n\tpublic void update() {\n\t\t\n\t\tif (isOpen) {\n\t\t\toffset -= offsetSpeed;\n\t\t\tif (offset <= -0.75F)\n\t\t\t\toffset = -0.75F;\n\t\t} else {\n\t\t\toffset += offsetSpeed;\n\t\t\tif (offset >= 0.05F)\n\t\t\t\toffset = 0.05F;\n\t\t}\n\t}\n\t\n\t@Override\n public NBTTagCompound getUpdateTag() {\n\t\t\n\t\treturn writeToNBT(new NBTTagCompound());\n }\n\t\n\t@Nullable\n\t@Override\n\tpublic SPacketUpdateTileEntity getUpdatePacket() {\n\t\t\n\t\tNBTTagCompound nbtTag = new NBTTagCompound();\n\t\tthis.writeCustomNBT(nbtTag);\n\t\t\n\t\treturn new SPacketUpdateTileEntity(getPos(), 1, nbtTag);\n\t}\n\t\n\t@Override\n\tpublic void writeCustomNBT(NBTTagCompound tag) {\n\t\t\n\t\ttag.setTag(\"inventory\", getInv().serializeNBT());\n\t\ttag.setBoolean(\"isOpen\", this.isOpen);\n\t\n\t\tif (owner != null)\n\t\t\ttag.setString(\"Own\", owner.toString());\n\t}\n\t\n\t@Override\n\tpublic void readCustomNBT(NBTTagCompound tag) {\n\t\t\n\t\tgetInv().deserializeNBT(tag.getCompoundTag(\"inventory\"));\n\t\tthis.isOpen = tag.getBoolean(\"isOpen\");\n\t\t\n\t\tthis.owner = null;\n\t\tif (tag.hasKey(\"Own\"))\n\t\t\towner = UUID.fromString(tag.getString(\"Own\"));\n\t}\n\t\n\tpublic void readInv(NBTTagCompound nbt) {\n\t\t\n\t\tNBTTagList invList = nbt.getTagList(\"inventory\", 10);\n\t\tfor (int i = 0; i < invList.tagCount(); i++) {\n\t\t\tNBTTagCompound itemTag = invList.getCompoundTagAt(i);\n\t\t\tint slot = itemTag.getByte(\"Slot\");\n\t\t\tif (slot >= 0 && slot < getInv().getSlots()) {\n\t\t\t\tgetInv().setStackInSlot(slot, new ItemStack(itemTag));\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic void writeInv(NBTTagCompound nbt, boolean toItem) {\n\t\t\n\t\tboolean write = false;\n\t\tNBTTagList invList = new NBTTagList();\n\t\tfor (int i = 0; i < getInv().getSlots(); i++) {\n\t\t\tif (getInv().getStackInSlot(i) != ItemStack.EMPTY)\n\t\t\t{\n\t\t\t\tif (toItem)\n\t\t\t\t\twrite = true;\n\t\t\t\tNBTTagCompound itemTag = new NBTTagCompound();\n\t\t\t\titemTag.setByte(\"Slot\", (byte)i);\n\t\t\t\tgetInv().getStackInSlot(i).writeToNBT(itemTag);\n\t\t\t\tinvList.appendTag(itemTag);\n\t\t\t}\n\t\t}\n\t\tif (!toItem || write)\n\t\t\tnbt.setTag(\"inventory\", invList);\n\t}\n\t\n\t@Override\n\tpublic boolean hasCapability(@Nonnull Capability<?> cap, @Nonnull EnumFacing side) {\n\t\t\n\t\treturn cap == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY;\n\t}\n\t\n\t@Override\n\tpublic <T> T getCapability(@Nonnull Capability<T> cap, @Nonnull EnumFacing side) {\n\t\t\n\t\tif (cap == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY)\n\t\t\treturn CapabilityItemHandler.ITEM_HANDLER_CAPABILITY.cast(getInv());\n\t\t\n\t\treturn super.getCapability(cap, side);\n\t}\n\t\n\t@Override\n\tpublic UUID getCabinetOwner() {\n\n\t\treturn owner;\n\t}\n\n\t@Override\n\tpublic boolean setOwner(UUID owner) {\n\n\t\tif ((this.owner != null && !this.owner.equals(owner)) || (owner != null && !owner.equals(this.owner))) {\n\t\t\tthis.owner = owner;\n\t\t\tif (world != null && !world.isRemote) {\t\n\t\t\t\tmarkDirty();\n\t\t\t\tthis.markBlockForUpdate();\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\t\n\t@Override\n\tpublic boolean isCabinetLocked() {\n\n\t\treturn getCabinetOwner() != null;\n\t}\n\t\n\tpublic boolean hasKeyCopy(EntityPlayer player, UUID uuid) {\n\t\t\n\t\tfor (int i = 0; i < player.inventory.mainInventory.size(); i++) {\n\t\t\tItemStack keyCopy = player.inventory.mainInventory.get(i);\n\t\t\tif (keyCopy.isEmpty())\n\t\t\t\tcontinue;\n\t\t\tif (keyCopy.getItem() == RFCItems.keys && keyCopy.getItemDamage() == 1) {\n\t\t\t\tif (keyCopy.hasTagCompound() && keyCopy.getTagCompound().hasKey(StringLibs.RFC_COPY)) {\n\t\t\t\t\treturn uuid.equals(UUID.fromString(NBTUtils.getString(keyCopy, StringLibs.RFC_COPY, \"\")));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tpublic ItemStackHandler getInv() {\n\t\t\n\t\treturn inv;\n\t}\n\n\t// BOTANIA IMPL\n\tlong MAX_MANA_INTERNAL = ItemManaFolder.getMaxManaFolder() * 8;\n//\tint MAX_VANILLA_MANA_POOL = 1000000;\n\t\n\tpublic long getTotalInternalManaPool() {\n\t\t\n\t\tlong total = 0;\n\t\tfor (int i = 0; i < this.getInv().getSlots(); i++) {\n\t\t\tItemStack stack = this.getInv().getStackInSlot(i);\n\t\t\tif (!stack.isEmpty() && stack.getItem() instanceof IManaItem)\n\t\t\t\ttotal += ItemManaFolder.getManaSize(stack);\n\t\t}\n\t\treturn total;\n\t}\n\t\n\tpublic int getManaFromFolder() {\n\t\t\n\t\tfor (int i = 0; i < this.getInv().getSlots(); i++) {\n\t\t\tItemStack stack = this.getInv().getStackInSlot(i);\n\t\t\tif (!stack.isEmpty() && stack.getItem() instanceof IManaItem) {\n\t\t\t\tint manaSize = ItemManaFolder.getManaSize(stack);\n\t\t\t\tif (manaSize >= 0)\n\t\t\t\t\treturn manaSize;\n\t\t\t}\n\t\t}\n\t\treturn -1;\n\t}\n\t\n\tpublic void addManaToFolder(int mana) {\n\t\t\n\t\tfor (int i = 0; i < this.getInv().getSlots(); i++){\n\t\t\tItemStack stack = this.getInv().getStackInSlot(i);\n\t\t\tif (!stack.isEmpty() && stack.getItem() instanceof IManaItem) {\n\t\t\t\tif (mana > 0 && ItemManaFolder.isManaFolderFull(stack))\n\t\t\t\t\tcontinue;\n\t\t\t\t\n\t\t\t\tif (mana < 0 && ItemManaFolder.getManaSize(stack) <= 0)\n\t\t\t\t\tcontinue;\n\t\t\t\t\n\t\t\t\tItemManaFolder.addManaToFolder(stack, mana);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic boolean canRecieveManaFromBursts() {\n\n\t\treturn getManaFromFolder() != -1;\n\t}\n\n\t@Override\n\tpublic boolean isFull() {\n\n\t\treturn getTotalInternalManaPool() == MAX_MANA_INTERNAL || getManaFromFolder() == -1;\n\t}\n\n\t@Override\n\tpublic void recieveMana(int mana) {\n\n\t\tint manaToAdd = Math.min(ItemManaFolder.getMaxManaFolder(), mana);\n\t\tthis.addManaToFolder(manaToAdd);\n\t}\n\n\t@Override\n\tpublic int getCurrentMana() {\n\n\t\treturn getManaFromFolder();\n\t}\n\n\t@Override\n\tpublic boolean areIncomingTranfersDone() {\n\n\t\treturn false;\n\t}\n\n\t@Override\n\tpublic void attachSpark(ISparkEntity arg0) {}\n\n\t@Override\n\tpublic boolean canAttachSpark(ItemStack arg0) {\n\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic ISparkEntity getAttachedSpark() {\n\n\t\tList sparks = world.getEntitiesWithinAABB(Entity.class, new AxisAlignedBB(pos.up(), pos.up().add(1, 1, 1)), Predicates.instanceOf(ISparkEntity.class));\n\t\tif (sparks.size() == 1) {\n\t\t\tEntity e = (Entity)sparks.get(0);\n\t\t\treturn (ISparkEntity)e;\n\t\t}\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic int getAvailableSpaceForMana() {\n\n\t\tif (getTotalInternalManaPool() == this.MAX_MANA_INTERNAL)\n\t\t\treturn 0;\n\t\t\n\t\treturn 1000;\n\t}\n}",
"public class StringLibs {\n\n\t// UPGRADES\n\tpublic static String RFC_UPGRADE = \"RFC_upgrade\";\n\tpublic static String TAG_CREATIVE = \"TAG_creativeUpgrade\";\n\tpublic static String TAG_ENDER = \"TAG_enderUpgrade\";\n\tpublic static String TAG_CRAFT = \"TAG_craftingUpgrade\";\n\tpublic static String TAG_OREDICT = \"TAG_oredictUpgrade\";\n\tpublic static String TAG_MOB = \"TAG_mobUpgrade\";\n\tpublic static String TAG_FLUID = \"TAG_fluidUpgrade\";\n\tpublic static String TAG_LIFE = \"TAG_lifeUpgrade\";\n\tpublic static String TAG_SMELT = \"TAG_smeltingUpgrade\";\n\t\n\t// ENDER FOLDER\n\tpublic static String RFC_SLOTINDEX = \"RFC_slotindex\";\n\tpublic static String RFC_TILEPOS = \"RFC_tilepos\";\n\tpublic static String RFC_DIM = \"RFC_dim\";\n\tpublic static String RFC_HASH = \"RFC_enderhash\";\n\t\n\t// UUID\n\tpublic static String RFC_OWNER = \"Own\";\n\tpublic static String RFC_COPY = \"OwnCopy\";\n\tpublic static String RFC_FALLBACK = \"RFC_playername\";\n\t\n\t// MISC\n\tpublic static String RFC_TAPED = \"RFC_whiteoutTaped\";\n\tpublic static String RFC_PLACEMODE = \"RFC_placeMode\";\n\tpublic static String RFC_IGNORENBT = \"RFC_ignoreNBT\";\n\tpublic static String RFC_CRAFTABLE = \"RFC_isCraftable\";\n\t\n\t// ENTITY\n\tpublic static String RFC_MOBUPGRADE = \"RFC_mobUpgrade\";\n}",
"public class UpgradeHelper {\n\t\n\tprivate static Map<ItemStack, String> upgrades = new HashMap<ItemStack, String>();\n\n\t/**\n\t * Put this in init phase or sometime after you've registered all your items. Stack must implement IUpgrades, and tag must not be empty.\n\t * @param stack\n\t * @param tag\n\t */\n\tpublic static void registerUpgrade(ItemStack stack, String tag) {\n\t\t\n\t\tif (!stack.isEmpty() && stack.getItem() instanceof IUpgrades && !tag.isEmpty())\n\t\t\tupgrades.put(stack, tag);\n\t\telse throw new IllegalArgumentException(\"[RealFilingCabinet]: Register upgrades: ItemStack is not an instance of IUpgrades, or the string tag is empty\");\n\t}\n\t\n\t/**\n\t * Conditional checking for whether the tile already has an upgrade installed, excluding creative upgrade\n\t * @param tile\n\t * @return\n\t */\n\tpublic static boolean hasUpgrade(TileEntityRFC tile) {\n\t\t\n\t\tif (!(tile.getBlockType() instanceof IFilingCabinet))\n\t\t\treturn false;\n\t\t\n\t\treturn !tile.upgrades.isEmpty();\n\t}\n\t\n\t/**\n\t * Conditional checking for whether the tile has an creative upgrade installed\n\t * @param tile\n\t * @return\n\t */\n\tpublic static boolean isCreative(TileEntityRFC tile) {\n\t\t\n\t\treturn tile.isCreative;\n\t}\n\t\n\t/**\n\t * Check if the tile has an upgrade installed, using a nbt tag string\n\t * @param tile\n\t * @param tag\n\t * @return String\n\t */\n\tpublic static String getUpgrade(TileEntityRFC tile, String tag) {\n\t\t\n\t\tif (!hasUpgrade(tile))\n\t\t\treturn null;\n\t\t\n\t\tString str = tile.upgrades;\n\t\tif (str.equals(tag))\n\t\t\treturn str;\n\t\t\n\t\treturn null;\n\t}\n\t\n\t/**\n\t * Sets the upgrade into the tile, if it allows for it, including creative upgrade\n\t * @param player\n\t * @param tile\n\t * @param upgrade\n\t */\n\tpublic static void setUpgrade(EntityPlayer player, TileEntityRFC tile, ItemStack upgrade) {\n\t\t\n\t\tif (tile.getWorld().isRemote || !(upgrade.getItem() instanceof IUpgrades))\n\t\t\treturn;\n\t\t\n\t\tif (!((IUpgrades)upgrade.getItem()).canApply(tile, upgrade, player))\n\t\t\treturn;\n\n\t\tString key = stringTest(upgrade);\n\t\t\n\t\tif (key != null && key.equals(StringLibs.TAG_CREATIVE)) {\n\t\t\ttile.isCreative = true;\n\t\t\tif (!player.capabilities.isCreativeMode)\n\t\t\t\tupgrade.shrink(1);\n\t\t\ttile.markDirty();\n\t\t\treturn;\n\t\t}\n\t\tif (hasUpgrade(tile))\n\t\t\treturn;\n\t\t\t\n\t\tif (key != null) {\n\t\t\t\n\t\t\ttile.upgrades = key;\n\t\t\tif (!player.capabilities.isCreativeMode)\n\t\t\t\tupgrade.shrink(1);\n\t\t\tif (upgrade.getItem() == RFCItems.upgrades && upgrade.getItemDamage() == ItemUpgrades.UpgradeType.ENDER.ordinal())\n\t\t\t\ttile.setHash(tile);\n\t\t\ttile.markDirty();\n\t\t}\n\t}\n\t\n\t/**\n\t * Removes an upgrade from the tile, including creative upgrade\n\t * @param player\n\t * @param tile\n\t */\n\tpublic static void removeUpgrade(EntityPlayer player, TileEntityRFC tile) {\n\t\t\n\t\tif ((!hasUpgrade(tile) && !isCreative(tile)))\n\t\t\treturn;\n\n\t\tItemStack creative = creativeTest(tile);\n\t\tif (!creative.isEmpty()) {\n\t\t\t\n\t\t\ttile.isCreative = false;\n\t\t\tif (!player.inventory.addItemStackToInventory(creative))\n\t\t\t\tplayer.dropItem(creative.getItem(), 1);\n\t\t\ttile.markDirty();\n\t\t\treturn;\n\t\t}\n\t\tItemStack upgrade = stackTest(tile);\n\t\tif (!upgrade.isEmpty()) {\n\t\t\t\n\t\t\tItemStack newStack = new ItemStack(upgrade.getItem(), 1, upgrade.getItemDamage());\n\t\t\tif (!player.inventory.addItemStackToInventory(newStack))\n\t\t\t\tplayer.dropItem(newStack.getItem(), 1);\n\t\t}\n\t\ttile.upgrades = \"\";\n\t\ttile.markDirty();\n\t}\n\t\n\tprivate static String stringTest(ItemStack upgrade) {\n\t\t\n\t\tList<ItemStack> keys = new ArrayList(upgrades.keySet());\n\t\tfor (ItemStack is : keys) {\n\t\t\tif (ItemStack.areItemsEqual(upgrade, is)) {\n\t\t\t\tString str = upgrades.get(is);\n\t\t\t\treturn str;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}\n\t\n\tpublic static ItemStack stackTest(TileEntityRFC tile) {\n\t\t\n\t\tString str = tile.upgrades;\n\t\tif (str.isEmpty())\n\t\t\treturn ItemStack.EMPTY;\n\t\t\n\t\tfor (Map.Entry<ItemStack, String> entry : upgrades.entrySet()) {\n\t\t\tString value = entry.getValue();\n\t\t\tif (value.equals(str))\n\t\t\t\treturn entry.getKey().copy();\n\t\t}\n\t\treturn ItemStack.EMPTY;\n\t}\n\t\n\tprivate static ItemStack creativeTest(TileEntityRFC tile) {\n\t\t\n\t\tboolean bool = tile.isCreative;\n\t\tif (bool)\n\t\t\treturn new ItemStack(RFCItems.upgrades, 1, 0);\n\t\t\n\t\treturn ItemStack.EMPTY;\n\t}\n}",
"public class InventoryRFC extends ItemStackHandler {\n\t\n\tfinal TileEntityRFC tile;\n\n\tpublic InventoryRFC(TileEntityRFC tile, int size) {\n\t\t\n\t\tthis.tile = tile;\n\t\tsetSize(size);\n\t}\n\t\n\tpublic void copyInv(InventoryRFC inv) {\n\t\t\n\t\tfor (int i = 0; i < inv.stacks.size(); i++) {\n\t\t\tstacks.set(i, inv.getTrueStackInSlot(i));\n\t\t}\n\t}\n\t\n\t@Override\n\tpublic ItemStack insertItem(int slot, ItemStack stack, boolean simulate) {\n\t\t\n\t\tLogRFC.debug(\"Transfer stack: \" + stack + \" / Stack in slot: \" + getStackInSlot(slot) + \" / True stack in slot: \" + getTrueStackInSlot(slot) + \" / Slot #\" + slot + \" / Simulating: \" + simulate);\n validateSlotIndex(slot);\n\t\t\n\t\tif (tile.isCabinetLocked())\n\t\t\treturn stack;\n\t\t\n if (stack.isEmpty())\n return ItemStack.EMPTY;\n\n if (!stacks.get(slot).isEmpty() && stacks.get(slot).getItem() == RFCItems.folder && stacks.get(slot).getItemDamage() == FolderType.DURA.ordinal() && DurabilityUtils.matchDurability(tile, stack, slot, simulate)) {\n \tif (!simulate) {\n \t\tVanillaPacketDispatcher.dispatchTEToNearbyPlayers(tile.getWorld(), tile.getPos());\n \t}\n \treturn ItemStack.EMPTY;\n }\n int slotIndex = StorageUtils.simpleFolderMatch(tile, stack);\n if (slotIndex != -1) {\n \tslot = slotIndex;\n \tItemStack toInsert = ItemFolder.insert(stacks.get(slot), stack, simulate);\n \tif (!simulate) {\n \t\tVanillaPacketDispatcher.dispatchTEToNearbyPlayers(tile.getWorld(), tile.getPos());\n \t}\n \treturn toInsert;\n }\n return stack;\n\t}\n\t\n\t@Override\n\tpublic ItemStack extractItem(int slot, int amount, boolean simulate) {\n\t\t\n\t\tLogRFC.debug(\"Extraction slot: \" + slot + \" / Extraction amount: \" + amount + \" / \" + simulate);\n\t\t\n\t\tif (ItemFolder.getObject(stacks.get(slot)) instanceof ItemStack) {\n\t\t\tItemStack stackFolder = this.getStackFromFolder(slot);\n\t\t\tif (stackFolder.isEmpty() || tile.isCabinetLocked() || UpgradeHelper.getUpgrade(tile, StringLibs.TAG_CRAFT) != null)\n\t\t\t\treturn ItemStack.EMPTY;\n\t\t\t\n\t\t\tif (tile.hasItemFrame() && tile.getFilter().isEmpty())\n\t\t\t\treturn ItemStack.EMPTY;\n\t\t\t\n\t\t\tif (!tile.getFilter().isEmpty()) {\n\t\t\t\tint i = StorageUtils.simpleFolderMatch(tile, tile.getFilter());\n\t\t\t\tif (i != -1 && slot == i) {\n\t\t\t\t\tstackFolder = this.getStackFromFolder(i);\n\t\t\t\t\tlong filterCount = ItemFolder.getFileSize(getTrueStackInSlot(i));\n\t\t\t\t\tif (filterCount == 0)\n\t\t\t\t\t\treturn ItemStack.EMPTY;\n\t\t\t\t\t\n\t\t\t\t\tlong filterExtract = Math.min(stackFolder.getMaxStackSize(), filterCount);\n\t\t\t\t\tamount = Math.min((int)filterExtract, amount);\n\t\t\t\t\t\n\t\t\t\t\tif (!simulate && !UpgradeHelper.isCreative(tile)) {\n\t\t\t\t\t\tItemFolder.remove(getTrueStackInSlot(i), amount);\n\t\t\t \t\tVanillaPacketDispatcher.dispatchTEToNearbyPlayers(tile.getWorld(), tile.getPos());\n\t\t\t\t\t}\n\t\t\t\t\tstackFolder.setCount(amount);\n\t\t\t\t\treturn stackFolder.copy();\n\t\t\t\t}\n\t\t\t\treturn ItemStack.EMPTY;\n\t\t\t}\n\t\t\tlong count = ItemFolder.getFileSize(getTrueStackInSlot(slot));\n\t\t\tif (count == 0)\n\t\t\t\treturn ItemStack.EMPTY;\n\t\t\t\n\t\t\tlong extract = Math.min(stackFolder.getMaxStackSize(), count);\n\t\t\tamount = Math.min((int)extract, amount);\n\t\t\t\n\t\t\tif (!simulate && !UpgradeHelper.isCreative(tile)) {\n\t\t\t\tItemFolder.remove(getTrueStackInSlot(slot), amount);\n\t \t\tVanillaPacketDispatcher.dispatchTEToNearbyPlayers(tile.getWorld(), tile.getPos());\n\t\t\t}\n\t\t\tstackFolder.setCount(amount);\n\t\t\treturn stackFolder.copy();\n\t\t}\t\n\t\treturn ItemStack.EMPTY;\n\t}\n\t\n\t@Override\n\tprotected void onContentsChanged(int slot) {\n\t\t\n\t\tsuper.onContentsChanged(slot);\n\t\tif (tile != null)\n\t\t\ttile.markDirty();\n\t}\n\t\n\tpublic ItemStack getTrueStackInSlot(int slot) {\n\t\t\n\t\tif (slot >= 0)\n\t\t\treturn stacks.get(slot);\n\t\t\n\t\treturn ItemStack.EMPTY;\n\t}\n\n\t@Override\n\tpublic ItemStack getStackInSlot(int slot) {\n\t\t\n\t\tvalidateSlotIndex(slot);\n\t\t\n\t\tif ((!stacks.get(slot).isEmpty() && !(stacks.get(slot).getItem() instanceof IFolder)) || slot == 8)\n\t\t\treturn ItemStack.EMPTY;\n\t\t\n\t\tItemStack stackFolder = getStackFromFolder(slot);\n\t\tif (!stackFolder.isEmpty()) {\n\t\t\tlong count = ItemFolder.getFileSize(getTrueStackInSlot(slot));\n\t\t\tif (count == 0)\n\t\t\t\treturn ItemStack.EMPTY;\n\t\t\t\n\t\t\tlong extract = Math.min(Integer.MAX_VALUE - 1, count);\n\t\t\tstackFolder.setCount((int)extract);\n\t\t}\n\t\treturn stackFolder;\n\t}\n\t\n\tpublic ItemStack getStackFromFolder(int slot) {\n\t\t\n\t\tItemStack folder = getTrueStackInSlot(slot);\n\t\tif (ItemFolder.getObject(folder) == null)\n\t\t\treturn ItemStack.EMPTY;\n\t\t\n\t\tif (!folder.isEmpty() && folder.getItem() instanceof IFolder) {\n\t\t\tif (ItemFolder.getObject(folder) instanceof ItemStack) {\n\t\t\t\tItemStack stack = (ItemStack)ItemFolder.getObject(folder);\n\t\t\t\tif (!stack.isEmpty()) {\n\t\t\t\t\treturn stack.copy();\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (UpgradeHelper.getUpgrade(tile, StringLibs.TAG_FLUID) != null && ItemFolder.getObject(folder) instanceof FluidStack) {\n\t\t\t\tItemStack bucket = FluidUtil.getFilledBucket((FluidStack)ItemFolder.getObject(folder));\n\t\t\t\tif (!bucket.isEmpty())\n\t\t\t\t\treturn bucket.copy();\n\t\t\t}\n\t\t}\n\t\treturn ItemStack.EMPTY;\n\t}\n\t\n\tpublic NonNullList<ItemStack> getStacks() {\n\t\t\n\t\treturn stacks;\n\t}\n\t\n\tpublic TileEntityRFC getTile() {\n\t\t\n\t\treturn tile;\n\t}\n}",
"public class ItemFolder extends Item implements IFolder {\n\t\n\tpublic static int extractSize = 0; // TODO: Figure out how to move this to CapabilityFolder\n\t\n\tpublic enum FolderType {\n\t\tNORMAL,\n\t\tENDER,\n\t\tDURA,\n\t\tMOB,\n\t\tFLUID,\n\t\tNBT;\n\t}\n\n\tpublic ItemFolder() {\n\t\t\n\t\tsetRegistryName(\"folder\");\n\t\tsetTranslationKey(RealFilingCabinet.MOD_ID + \".folder\");\n\t\tsetHasSubtypes(true);\n\t\tsetMaxStackSize(1);\n\t}\n\t\n\t@Override\n\tpublic NBTTagCompound getNBTShareTag(ItemStack stack) {\n\t\t\n\t\tif(!stack.hasCapability(CapabilityProviderFolder.FOLDER_CAP, null))\n\t\t\treturn super.getNBTShareTag(stack);\n\t\t\n\t\tNBTTagCompound tag = stack.hasTagCompound() ? stack.getTagCompound().copy() : new NBTTagCompound();\n\t\ttag.setTag(\"folderCap\", stack.getCapability(CapabilityProviderFolder.FOLDER_CAP, null).serializeNBT());\n\t\tLogRFC.debug(\"Sharing tag: \" + tag.toString());\n\t\treturn tag;\n\t}\n\t\n\t@Override\n\tpublic String getTranslationKey(ItemStack stack) {\n\t\t\n\t\treturn getTranslationKey() + \"_\" + FolderType.values()[stack.getItemDamage()].toString().toLowerCase();\n\t}\n\t\n\t@Override\n\tpublic void addInformation(ItemStack stack, World player, List<String> list, ITooltipFlag whatisthis) {\n\t\t\n\t\tif(stack.hasCapability(CapabilityProviderFolder.FOLDER_CAP, null)) // Direction doesn't really matter here.\n\t\t\tstack.getCapability(CapabilityProviderFolder.FOLDER_CAP, null).addTooltips(player, list, whatisthis);\n\t}\n\t\n\tpublic ItemStack getContainerItem(ItemStack stack) {\n\t\t\n\t\tif(!stack.hasCapability(CapabilityProviderFolder.FOLDER_CAP, null))\n\t\t\treturn ItemStack.EMPTY;\n\t\t\n\t\tCapabilityFolder cap = stack.getCapability(CapabilityProviderFolder.FOLDER_CAP, null);\n\t\tlong count = cap.getCount();\n\t\tlong extract = 0;\n\t\tif (count > 0 && cap.isItemStack())\n\t\t\textract = Math.min(cap.getItemStack().getMaxStackSize(), count);\n\t\t\n\t\tif (NBTUtils.getBoolean(stack, StringLibs.RFC_TAPED, false))\n\t\t\treturn ItemStack.EMPTY;\n\t\t\n\t\tItemStack copy = stack.copy();\n\t\tif (stack.getItemDamage() == FolderType.DURA.ordinal() && count == 0) // TODO: This works with 0 items? Might want to test this later\n\t\t\tsetRemSize(copy, 0);\n\n\t\tremove(copy, extract);\n\t\textractSize = (int)extract;\n\t\t\n\t\treturn copy;\n\t}\n\t\n\tpublic boolean hasContainerItem(ItemStack stack) {\n\t\t\n\t\treturn !getContainerItem(stack).isEmpty();\n\t}\n\t\n\tpublic static String getFolderDisplayName(ItemStack stack) {\n\t\t\n\t\tif(stack.hasCapability(CapabilityProviderFolder.FOLDER_CAP, null))\n\t\t\treturn stack.getCapability(CapabilityProviderFolder.FOLDER_CAP, null).getDisplayName();\n\t\t\n\t\treturn \"\";\n\t}\n\t\n\tpublic static int getFileMeta(ItemStack stack) {\n\t\t\n\t\tif(stack.hasCapability(CapabilityProviderFolder.FOLDER_CAP, null)) {\n\t\t\tCapabilityFolder cap = stack.getCapability(CapabilityProviderFolder.FOLDER_CAP, null);\n\t\t\tif(cap.isFluidStack()) {\n\t\t\t\treturn cap.getItemStack().getItemDamage();\n\t\t\t} else if(cap.isBlock()) {\n\t\t\t\treturn cap.getBlock().getBlock().getMetaFromState(cap.getBlock());\n\t\t\t}\n\t\t}\n\t\treturn 0;\n\t}\n\t\n\tpublic static void setFileMeta(ItemStack stack, int meta) {\n\t\t\n\t\tif(stack.hasCapability(CapabilityProviderFolder.FOLDER_CAP, null)) {\n\t\t\tCapabilityFolder cap = stack.getCapability(CapabilityProviderFolder.FOLDER_CAP, null);\n\t\t\tif(cap.isFluidStack()) {\n\t\t\t\tcap.getItemStack().setItemDamage(meta);\n\t\t\t} else if(cap.isBlock()) {\n\t\t\t\tcap.setContents(cap.getBlock().getBlock().getMetaFromState(cap.getBlock()));\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic static void setFileSize(ItemStack stack, long count) {\n\t\t\n\t\tif(stack.hasCapability(CapabilityProviderFolder.FOLDER_CAP, null))\n\t\t\tstack.getCapability(CapabilityProviderFolder.FOLDER_CAP, null).setCount(count);\n\t}\n\t\n\tpublic static long getFileSize(ItemStack stack) {\n\t\t\n\t\tif(stack.hasCapability(CapabilityProviderFolder.FOLDER_CAP, null))\n\t\t\treturn stack.getCapability(CapabilityProviderFolder.FOLDER_CAP, null).getCount();\n\t\t\n\t\treturn 0;\n\t}\n\t\n\tpublic static void remove(ItemStack stack, long count) {\n\t\t\n\t\tlong current = getFileSize(stack);\n\t\tsetFileSize(stack, Math.max(current - count, 0));\n\t}\n\t\n\t// trial new way of adding to contents of folder, while also returning the remainder in cases of reaching the storage limit\n\tpublic static ItemStack insert(ItemStack folder, ItemStack items, boolean simulate) {\n\t\t\n\t\tif (folder.hasCapability(CapabilityProviderFolder.FOLDER_CAP, null))\n\t\t\treturn folder.getCapability(CapabilityProviderFolder.FOLDER_CAP, null).insertItems(items, simulate);\n\t\t\n\t\treturn items;\n\t}\n\t\n\t/*\n\t * Maybe find a better way of adding things?\n\t */\n\t@Deprecated\n\tpublic static void add(ItemStack stack, long count) {\n\t\t\n\t\tlong current = getFileSize(stack);\n\t\tsetFileSize(stack, current + count);\n\t}\n\t\n\tpublic static void setRemSize(ItemStack stack, int count) {\n\t\t\n\t\tif(stack.hasCapability(CapabilityProviderFolder.FOLDER_CAP, null))\n\t\t\tstack.getCapability(CapabilityProviderFolder.FOLDER_CAP, null).setRemaining(count);\n\t}\n\t\n\tpublic static int getRemSize(ItemStack stack) {\n\t\t\n\t\tif(stack.hasCapability(CapabilityProviderFolder.FOLDER_CAP, null))\n\t\t\treturn stack.getCapability(CapabilityProviderFolder.FOLDER_CAP, null).getRemaining();\n\t\t\n\t\treturn 0;\n\t}\n\t\n\tpublic static void addRem(ItemStack stack, int count) {\n\t\t\n\t\tint current = getRemSize(stack);\n\t\tsetRemSize(stack, current + count);\n\t}\n\t\n\tpublic static void remRem(ItemStack stack, int count) {\n\t\t\n\t\tint current = getRemSize(stack);\n\t\tsetRemSize(stack, Math.max(current - count, 0));\n\t}\n\t\n\tpublic static NBTTagCompound getItemTag(ItemStack stack) {\n\t\t\n\t\tif(stack.hasCapability(CapabilityProviderFolder.FOLDER_CAP, null)) {\n\t\t\t\n\t\t\tCapabilityFolder cap = stack.getCapability(CapabilityProviderFolder.FOLDER_CAP, null);\n\t\t\tif(cap.isItemStack())\n\t\t\t\treturn cap.getItemStack().getTagCompound();\n\t\t}\n\t\t\n\t\treturn new NBTTagCompound();\n\t}\n\t\n\tpublic static void setItemTag(ItemStack stack, NBTTagCompound tag) {\n\t\t\n\t\tif(stack.hasCapability(CapabilityProviderFolder.FOLDER_CAP, null)) {\n\t\t\tCapabilityFolder cap = stack.getCapability(CapabilityProviderFolder.FOLDER_CAP, null);\n\t\t\t\n\t\t\tif(cap.isItemStack())\n\t\t\t\tcap.getItemStack().setTagCompound(tag);\n\t\t}\n\t}\n\n\tpublic static Object getObject(ItemStack folder) {\n\n\t\tif(folder.hasCapability(CapabilityProviderFolder.FOLDER_CAP, null))\n\t\t\treturn folder.getCapability(CapabilityProviderFolder.FOLDER_CAP, null).getContents();\n\t\t\n\t\treturn null;\n\t}\n\n\tpublic static boolean setObject(ItemStack folder, Object object) {\n\t\t\n\t\tif(folder.hasCapability(CapabilityProviderFolder.FOLDER_CAP, null) && folder.getCapability(CapabilityProviderFolder.FOLDER_CAP, null).getContents() == null)\n\t\t\treturn folder.getCapability(CapabilityProviderFolder.FOLDER_CAP, null).setContents(object);\n\t\t\n\t\treturn false;\n\t}\n\t\n//\t@Override\n//\tpublic boolean itemInteractionForEntity(ItemStack stack, EntityPlayer player, EntityLivingBase target, EnumHand hand) {\n//\t\t\n//\t\tif (target.isChild() && !(target instanceof EntityZombie))\n//\t\t\treturn false;\n//\t\t\n//\t\tif (target instanceof EntityCabinet)\n//\t\t\treturn false;\n//\t\t\n//\t\tif (target instanceof IEntityOwnable && ((IEntityOwnable)target).getOwner() != null)\n//\t\t\treturn false;\n//\t\t\n//\t\tString entityblacklist = target.getClass().getSimpleName();\n//\t\tfor (String toBlacklist : ConfigRFC.mobFolderBlacklist) {\n//\t\t\tif (toBlacklist.contains(entityblacklist))\n//\t\t\t\treturn false;\n//\t\t}\n//\t\tItemStack folder = player.getHeldItemMainhand();\n//\t\tif (!folder.isEmpty() && folder.getItem() == this && folder.getItemDamage() == FolderType.MOB.ordinal()) {\n//\t\t\tif (!ConfigRFC.mobUpgrade) return false;\n//\t\t\t\n//\t\t\tif (getObject(folder) != null) {\n//\t\t\t\tResourceLocation res = EntityList.getKey(target);\n//\t\t\t\tif (getObject(folder).equals(res.toString()))\n//\t\t\t\t{\n//\t\t\t\t\tadd(folder, 1);\n//\t\t\t\t\tMobUtils.dropMobEquips(player.world, target);\n//\t\t\t\t\ttarget.setDead();\n//\t\t\t\t}\n//\t\t\t}\n//\t\t\treturn true;\n//\t\t}\n//\t\treturn false;\n//\t}\n\t\n\t@Override\n\tpublic EnumActionResult onItemUse(EntityPlayer player, World world, BlockPos pos, EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ) {\n\t\t\n\t\tItemStack stack = player.getHeldItem(hand);\n\t\tif (getObject(stack) != null) {\n\t\t\tif (stack.getItemDamage() < 2) {\n\t\t\t\tif (((ItemStack)getObject(stack)).getItem() instanceof ItemBlock) {\t\n\t\t\t\t\tlong count = ItemFolder.getFileSize(stack);\n\t\t\t\t\tif (stack.getItemDamage() == FolderType.ENDER.ordinal() && !EnderUtils.preValidateEnderFolder(stack))\n\t\t\t\t\t\treturn EnumActionResult.FAIL;\n\t\t\t\t\t\n\t\t\t\t\tif (count > 0) {\n\t\t\t\t\t\tItemStack stackToPlace = new ItemStack(((ItemStack)getObject(stack)).getItem(), 1, ((ItemStack)getObject(stack)).getItemDamage());\n\t\t\t\t\t\tItemStack savedfolder = player.getHeldItem(hand);\n\t\t\t\t\t\t\n\t\t\t\t\t\tplayer.setHeldItem(hand, stackToPlace);\n\t\t\t\t\t\tEnumActionResult ear = stackToPlace.onItemUse(player, world, pos, hand, side, hitX, hitY, hitZ);\n\t\t\t\t\t\tplayer.setHeldItem(hand, savedfolder);\n\t\t\t\t\t\t\n\t\t\t\t\t\tif (ear == EnumActionResult.SUCCESS) {\n\t\t\t\t\t\t\tif (!player.capabilities.isCreativeMode) {\n\t\t\t\t\t\t\t\tif (stack.getItemDamage() == FolderType.ENDER.ordinal() && !world.isRemote) {\n\t\t\t\t\t\t\t\t\tEnderUtils.syncToTile(EnderUtils.getTileLoc(stack), NBTUtils.getInt(stack, StringLibs.RFC_DIM, 0), NBTUtils.getInt(stack, StringLibs.RFC_SLOTINDEX, 0), 1, true);\n\t\t\t\t\t\t\t\t\tif (player instanceof FakePlayer)\n\t\t\t\t\t\t\t\t\t\tEnderUtils.syncToFolder(EnderUtils.getTileLoc(stack), stack, NBTUtils.getInt(stack, StringLibs.RFC_SLOTINDEX, 0));\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\tremove(stack, 1);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn EnumActionResult.SUCCESS;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (stack.getItemDamage() == 3) {\n\t\t\t\tif (MobUtils.spawnEntityFromFolder(world, player, stack, pos, side))\n\t\t\t\t\treturn EnumActionResult.SUCCESS;\n\t\t\t}\n\t\t\tif (stack.getItemDamage() == 4) {\n\t\t\t\tif (!(getObject(stack) instanceof FluidStack))\n\t\t\t\t\treturn EnumActionResult.PASS;\n\t\t\t\t\n\t\t\t\tif (FluidUtils.doPlace(world, player, stack, pos, side))\n\t\t\t\t\treturn EnumActionResult.SUCCESS;\n\t\t\t}\n\t\t}\n\t\treturn EnumActionResult.PASS;\n\t}\n\t\n\t@Override\n public ActionResult<ItemStack> onItemRightClick(World world, EntityPlayer player, EnumHand hand) {\n \n\t\tItemStack stack = player.getHeldItem(hand);\n\t\tif (!stack.isEmpty() && stack.getItem() != this)\n\t\t\treturn ActionResult.newResult(EnumActionResult.PASS, stack);\n\n\t\tif (stack.getItemDamage() == FolderType.DURA.ordinal()) {\n\t\t\tNBTTagCompound tag = stack.getTagCompound();\n\t\t\ttag.setBoolean(StringLibs.RFC_IGNORENBT, !tag.getBoolean(StringLibs.RFC_IGNORENBT));\n\t\t\treturn ActionResult.newResult(EnumActionResult.SUCCESS, stack);\n\t\t}\n\t\tif (!stack.isEmpty() && stack.getItemDamage() != FolderType.FLUID.ordinal())\n\t\t\treturn ActionResult.newResult(EnumActionResult.PASS, stack);\n\t\t\n\t\tRayTraceResult rtr = rayTrace(world, player, true);\n\t\tif (rtr == null)\n\t\t\treturn ActionResult.newResult(EnumActionResult.PASS, stack);\n\t\t\n\t\tif (!MobUtils.canPlayerChangeStuffHere(world, player, stack, rtr.getBlockPos(), rtr.sideHit))\n\t\t\treturn ActionResult.newResult(EnumActionResult.PASS, stack);\n\t\t\n\t\telse {\n\t\t\tif (rtr.typeOfHit == RayTraceResult.Type.BLOCK) {\n\t\t\t\tBlockPos pos = rtr.getBlockPos();\n\t\t\t\tif (FluidUtils.doDrain(world, player, stack, pos, rtr.sideHit))\n\t\t\t\t\treturn ActionResult.newResult(EnumActionResult.SUCCESS, stack);\n\t\t\t}\n\t\t}\n\t\treturn ActionResult.newResult(EnumActionResult.PASS, stack);\n }\n\t\n\t@Override\n public boolean onEntitySwing(EntityLivingBase entityLiving, ItemStack stack) {\n \n\t\tif (entityLiving instanceof EntityPlayer && entityLiving.isSneaking()) {\n\t\t\tif (!stack.isEmpty() && stack.getItem() == this) {\n\t\t\t\tif (stack.getItemDamage() == 4) {\t\n\t\t\t\t\tNBTTagCompound tag = stack.getTagCompound();\n\t\t\t\t\ttag.setBoolean(StringLibs.RFC_PLACEMODE, !tag.getBoolean(StringLibs.RFC_PLACEMODE));\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n }\n\t\n\t@Override\n\tpublic void onUpdate(ItemStack stack, World world, Entity entity, int itemSlot, boolean isSelected) {\n\t\t\n\t\tif (!stack.hasCapability(CapabilityProviderFolder.FOLDER_CAP, null) || !stack.hasTagCompound() || !stack.getTagCompound().hasKey(\"folderCap\", 10))\n\t\t\treturn;\n\t\t\n\t\tCapabilityFolder cap = stack.getCapability(CapabilityProviderFolder.FOLDER_CAP, null);\n\t\tLogRFC.debug(\"Deserializing: \" + stack.getTagCompound().getCompoundTag(\"folderCap\").toString());\n\t\tcap.deserializeNBT(stack.getTagCompound().getCompoundTag(\"folderCap\"));\n\t\tstack.getTagCompound().removeTag(\"folderCap\");\n\t\t\n\t\tif (stack.getTagCompound().getSize() <= 0)\n\t\t\tstack.setTagCompound(null);\n\t}\n\t\n\t@Override\n\tpublic boolean shouldCauseReequipAnimation(ItemStack oldstack, ItemStack newstack, boolean slotchanged) {\n\t\t\n\t\treturn oldstack.getItem() != newstack.getItem() || (oldstack.getItem() == newstack.getItem() && oldstack.getItemDamage() != newstack.getItemDamage());\n\t}\n\t\n\t@Override\n\tpublic ItemStack isFolderEmpty(ItemStack stack) {\n\n\t\tswitch (stack.getItemDamage()) \n\t\t{\n\t\t\tcase 0: return new ItemStack(RFCItems.emptyFolder, 1, 0);\n\t\t\tcase 2: return new ItemStack(RFCItems.emptyFolder, 1, 1);\n\t\t\tcase 3: return new ItemStack(RFCItems.emptyFolder, 1, 2);\n\t\t\tcase 4: return new ItemStack(RFCItems.emptyFolder, 1, 3);\n\t\t\tcase 5: return new ItemStack(RFCItems.emptyFolder, 1, 4);\n\t\t}\n\t\treturn ItemStack.EMPTY;\n\t}\n}",
"public class SmeltingUtils {\n\t\n\tpublic static final int FUEL_TIME = 1600;\n\tpublic static final int SMELT_TIME = 100;\n\tpublic static final String TAG_SMELTLIST = \"RFC_smeltList\";\n\tpublic static final String TAG_SMELTJOB = \"RFC_smeltingJob\";\n\tpublic static final String TAG_FUELTIME = \"RFC_fuelTime\";\n\t\n\tpublic static boolean canSmelt(TileEntityRFC tile) {\n\t\t\n\t\treturn UpgradeHelper.getUpgrade(tile, StringLibs.TAG_SMELT) != null;\n\t}\n\n\tpublic static void createSmeltingJob(TileEntityRFC tile) {\n\t\t\n\t\tint toSmelt = -1;\n\t\tint smeltResult = -1;\n\t\tfor (int i = 0; i < tile.getInventory().getSlots(); i++) {\n\t\t\tif (hasSmeltingJob(tile, i)) continue;\n\t\t\tif (tile.getInventory().getTrueStackInSlot(i).getItem() == RFCItems.dyedFolder) continue; \n\t\t\tItemStack result = FurnaceRecipes.instance().getSmeltingResult(tile.getInventory().getStackInSlot(i));\n\t\t\tif (!result.isEmpty()) {\n\t\t\t\ttoSmelt = i;\n\t\t\t\tfor (int j = 0; j < tile.getInventory().getSlots(); j++) {\n\t\t\t\t\tItemStack loopStack = tile.getInventory().getStackFromFolder(j);\n\t\t\t\t\tif (!loopStack.isEmpty() && loopStack.areItemsEqual(loopStack, result) && toSmelt != j) {\n\t\t\t\t\t\tsmeltResult = j;\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (toSmelt >= 0 && smeltResult >= 0) {\n\t\t\taddSmeltingJob(tile, toSmelt, smeltResult);\n\t\t}\n\t\tif (!tile.smeltingJobs.isEmpty() && tile.fuelTime <= 0) {\n\t\t\tfor (int k = 0; k < tile.getInventory().getSlots(); k++) {\n\t\t\t\tItemStack fuel = tile.getInventory().getStackInSlot(k);\n\t\t\t\tif (!fuel.isEmpty() && fuel.getItem() == Items.COAL) {\n\t\t\t\t\tItemFolder.remove(tile.getInventory().getTrueStackInSlot(k), 1);\n\t\t\t\t\ttile.fuelTime = FUEL_TIME;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic static void writeSmeltNBT(TileEntityRFC tile, NBTTagCompound tag) {\n\n\t\tif (!canSmelt(tile)) {\n\t\t\tif (!tile.smeltingJobs.isEmpty())\n\t\t\t\ttile.smeltingJobs.clear();\n\t\t\ttile.fuelTime = 0;\n\t\t\treturn;\n\t\t}\n\t\ttag.setInteger(TAG_FUELTIME, tile.fuelTime);\n\t\tNBTTagList tagList = new NBTTagList();\n\t\tfor (int[] job : tile.smeltingJobs) {\n\t\t\tNBTTagCompound nbt = new NBTTagCompound();\n\t\t\tnbt.setIntArray(TAG_SMELTJOB, job);\n\t\t\ttagList.appendTag(nbt);\n\t\t}\n\t\ttag.setTag(TAG_SMELTLIST, tagList);\n\t}\n\t\n\tpublic static void readSmeltNBT(TileEntityRFC tile, NBTTagCompound tag) {\n\t\n//\t\tif (!canSmelt(tile)) {\n//\t\t\ttag.removeTag(TAG_SMELTJOB);\n//\t\t\treturn;\n//\t\t}\n\t\tif (tag.hasKey(TAG_SMELTLIST)) {\n//\t\t\tif (!tile.smeltingJobs.isEmpty()) tile.smeltingJobs.clear();\n\t\t\t\n\t\t\tNBTTagList tagList = tag.getTagList(TAG_SMELTLIST, 11);\n\t\t\tfor (int i = 0; i < tagList.tagCount(); i++) {\n\t\t\t\tint[] job = tagList.getIntArrayAt(i);\n\t\t\t\ttile.smeltingJobs.add(job);\n\t\t\t}\n\t\t}\n\t\ttile.fuelTime = tag.getInteger(TAG_FUELTIME);\n\t}\n\t\n\tprivate static void addSmeltingJob(TileEntityRFC tile, int toSmelt, int smeltResult) {\n\t\t\n\t\tif (tile.getWorld().isRemote) return;\n\t\t\n\t\tint[] job = new int[3];\n\t\tjob[0] = 0;\n\t\tjob[1] = toSmelt;\n\t\tjob[2] = smeltResult;\n\t\ttile.smeltingJobs.add(job);\n\t}\n\t\n\tprivate static boolean hasSmeltingJob(TileEntityRFC tile, int toSmeltSlot) {\n\t\t\n\t\tfor (int[] job : tile.smeltingJobs) {\n\t\t\tif (job[1] == toSmeltSlot)\n\t\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\t\n\tprivate static void completeSmeltingJob(TileEntityRFC tile, int[] job, int jobIndex) {\n\t\t\n\t\tif (tile.getInventory().getStackInSlot(job[1]).isEmpty()) {\n\t\t\ttile.smeltingJobs.remove(jobIndex);\n\t\t\treturn;\n\t\t}\n\t\tItemFolder.remove(tile.getInventory().getTrueStackInSlot(job[1]), 1);\n\t\tItemFolder.add(tile.getInventory().getTrueStackInSlot(job[2]), 1);\n\t\tif (tile.getInventory().getStackInSlot(job[1]).isEmpty()) {\n\t\t\ttile.smeltingJobs.remove(jobIndex);\n\t\t\treturn;\n\t\t}\n\t\tjob[0] = 0;\n\t}\n\t\n\tpublic static void incrementSmeltTime(TileEntityRFC tile) {\n\t\t\n\t\tif (tile.fuelTime > 0) tile.fuelTime--;\n\t\telse return;\n\t\t\n\t\tif (tile.getWorld().isRemote) return;\n\t\tif (!tile.smeltingJobs.isEmpty()) {\n\t\t\tfor (int i = 0; i < tile.smeltingJobs.size(); i++) {\n\t\t\t\tint[] job = tile.smeltingJobs.get(i);\n\t\t\t\tjob[0]++;\n\t\t\t\tif (job[0] >= SMELT_TIME)\n\t\t\t\t\tcompleteSmeltingJob(tile, job, i);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic static String getSmeltingPercentage(TileEntityRFC tile, int slot) {\n\t\t\n\t\tif (UpgradeHelper.getUpgrade(tile, StringLibs.TAG_SMELT) == null || tile.smeltingJobs.isEmpty()) return \"\";\n\t\tfor (int[] job : tile.smeltingJobs) {\n\t\t\tif (job[1] == slot) {\n\t\t\t\tNumberFormat percentFormatter = NumberFormat.getInstance();\n\t\t\t\tdouble calc = 0.0;\n\t\t\t\tif (job[0] > 0)\n\t\t\t\t\tcalc = (double)job[0] / (double)SMELT_TIME;\n\t\t\t\treturn \" [\" + percentFormatter.format(calc *= 100) + \"%]\";\n\t\t\t}\n\t\t}\n\t\treturn \"\";\n\t}\n\t\n\tpublic static boolean isSmelting(TileEntityRFC tile) {\n\t\t\n\t\treturn tile.fuelTime > 0;\n\t}\n}"
] | import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import mcp.mobius.waila.api.IWailaConfigHandler;
import mcp.mobius.waila.api.IWailaDataAccessor;
import mcp.mobius.waila.api.IWailaDataProvider;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fml.common.event.FMLInterModComms;
import mcp.mobius.waila.api.IWailaRegistrar;
import com.bafomdad.realfilingcabinet.blocks.BlockManaCabinet;
import com.bafomdad.realfilingcabinet.blocks.BlockRFC;
import com.bafomdad.realfilingcabinet.blocks.tiles.TileEntityRFC;
import com.bafomdad.realfilingcabinet.blocks.tiles.TileManaCabinet;
import com.bafomdad.realfilingcabinet.helpers.StringLibs;
import com.bafomdad.realfilingcabinet.helpers.UpgradeHelper;
import com.bafomdad.realfilingcabinet.inventory.InventoryRFC;
import com.bafomdad.realfilingcabinet.items.ItemFolder;
import com.bafomdad.realfilingcabinet.utils.SmeltingUtils; | package com.bafomdad.realfilingcabinet.integration;
public class WailaRFC {
public static void register() {
FMLInterModComms.sendMessage("waila", "register", "com.bafomdad.realfilingcabinet.integration.WailaRFC.load");
}
public static void load(IWailaRegistrar registrar) {
registrar.registerBodyProvider(new WailaProvider(), BlockRFC.class);
registrar.registerBodyProvider(new WailaManaProvider(), BlockManaCabinet.class);
//registrar.registerNBTProvider(new WailaProvider(), BlockRFC.class);
}
public static class WailaProvider implements IWailaDataProvider {
@Override
public ItemStack getWailaStack(IWailaDataAccessor arg0, IWailaConfigHandler arg1) {
return null;
}
@Override
public List<String> getWailaHead(ItemStack arg0, List<String> currenttip, IWailaDataAccessor arg2, IWailaConfigHandler arg3) {
return currenttip;
}
@Override
public List<String> getWailaBody(ItemStack stack, List<String> currenttip, IWailaDataAccessor accessor, IWailaConfigHandler config) {
| TileEntityRFC tileRFC = (TileEntityRFC)accessor.getTileEntity(); | 2 |
DMCApps/NavigationFragment | app/src/main/java/com/github/dmcapps/navigationfragmentexample/v7/DrawerExample/NavigationDrawerExampleActivity.java | [
"public interface Navigation {\n\n String getNavTag();\n\n void setNavBundle(Bundle bundle);\n Bundle getNavBundle();\n\n NavigationManager getNavigationManager();\n\n /**\n * Begins a Transaction for presenting the next fragment allowing for overriding of animations, bundles, etc.\n *\n * @return\n * returns an instance of {@link PresentationTransaction} for the programmer to describe the next presentation\n */\n PresentationTransaction beginPresentation();\n\n /**\n * Push a new Fragment onto the stack and presenting it to the screen\n * Uses default animation of slide in from right and slide out to left.\n *\n * @param\n * navFragment -> The Fragment to show. It must be a Fragment that implements {@link Navigation}\n */\n void presentFragment(Navigation navFragment);\n\n /**\n * Push a new Fragment onto the stack and presenting it to the screen\n * Uses default animation of slide in from right and slide out to left.\n * Sends a Bundle with the Fragment that can be retrieved using {@link Navigation#getNavBundle()}\n *\n * @param\n * navFragment -> The Fragment to show. It must be a Fragment that implements {@link Navigation}\n * @param\n * navBundle -> Bundle to add to the presenting of the Fragment.\n */\n void presentFragment(Navigation navFragment, Bundle navBundle);\n\n /**\n * Dimiss the current fragment off the top of the stack and dismiss it.\n * Uses default animation of slide in from left and slide out to right animation.\n */\n void dismissFragment();\n\n /**\n * Pop the current fragment off the top of the stack and dismiss it.\n * Uses default animation of slide in from left and slide out to right animation.\n *\n * @param\n * navBundle -> The navigation bundle to add to the fragment after the pop occurs\n */\n void dismissFragment(Bundle navBundle);\n\n /**\n * Dismiss all fragments to the given index in the stack\n */\n void dismissToIndex(int index);\n\n /**\n * Dismiss all fragments from the stack until we reach the Root Fragment (the fragment at the min stack size)\n */\n void dismissToRoot();\n\n /**\n * Remove all fragments from the stack including the Root. The add the given {@link Navigation}\n * as the new root fragment. The definition of the Root Fragment is the Fragment at the min stack size position.\n *\n * @param\n * navFragment -> The fragment that you would like as the new Root of the stack.\n */\n void replaceRootFragment(Navigation navFragment);\n\n void setTitle(String title);\n void setTitle(int resId);\n String getTitle();\n\n boolean isPortrait();\n boolean isTablet();\n}",
"public class NavigationFragment extends Fragment implements Navigation {\n\n private final String TAG = UUID.randomUUID().toString();\n private String mTitle;\n // Need to store the bundle myself as you can't change the fragment.setArguments() bundle after the fragment has been presented.\n private Bundle mNavBundle;\n\n public NavigationFragment() { }\n\n @Override\n public String getNavTag() {\n return TAG;\n }\n\n @Override\n public void setNavBundle(Bundle navBundle) {\n mNavBundle = navBundle;\n }\n\n @Override\n public Bundle getNavBundle() {\n return mNavBundle;\n }\n\n /**\n * Get the {@link NavigationManagerFragment} of the Fragment in the stack. This method will crash with\n * a RuntimeException if no Parent fragment is a {@link NavigationManagerFragment}.\n *\n * @return\n * The Parent Fragment in the stack of fragments that is the Navigation Manager of the Fragment.\n */\n @Override\n public NavigationManager getNavigationManager() {\n Fragment parent = this;\n\n // Loop until we find a parent that is a NavigationFragmentManager or there are no parents left to check.\n do {\n parent = parent.getParentFragment();\n\n NavigationManagerContainer container = ObjectUtils.as(NavigationManagerFragment.class, parent);\n if (container != null) {\n return container.getNavigationManager();\n }\n } while(parent != null);\n\n throw new RuntimeException(\"No parent NavigationManagerFragment found. In order to use the Navigation Manager Fragment you must have a parent in your Fragment Manager.\");\n }\n\n /**\n * Begins a Transaction for presenting the next fragment allowing for overriding of animations, bundles, etc.\n *\n * @return\n * returns an instance of {@link PresentationTransaction} for the programmer to describe the next presentation\n */\n @Override\n public PresentationTransaction beginPresentation() {\n return getNavigationManager().beginPresentation();\n }\n\n /**\n * Present a fragment on the Navigation Manager using the default slide in and out.\n *\n * @param\n * navFragment -> The Fragment to present.\n */\n @Override\n public void presentFragment(Navigation navFragment) {\n beginPresentation().presentFragment(navFragment);\n }\n\n /**\n * Push a new Fragment onto the stack and presenting it to the screen\n * Uses default animation of slide in from right and slide out to left.\n * Sends a Bundle with the Fragment that can be retrieved using {@link Navigation#getNavBundle()}\n *\n * @param\n * navFragment -> The Fragment to show. It must be a Fragment that implements {@link Navigation}\n * @param\n * navBundle -> Bundle to add to the presenting of the Fragment.\n */\n public void presentFragment(Navigation navFragment, Bundle navBundle) {\n beginPresentation().setNavBundle(navBundle).presentFragment(navFragment);\n }\n\n /**\n * Dimiss the current fragment off the top of the stack and dismiss it.\n * Uses default animation of slide in from left and slide out to right animation.\n */\n @Override\n public void dismissFragment() {\n getNavigationManager().dismissFragment();\n }\n\n /**\n * Pop the current fragment off the top of the stack and dismiss it.\n * Uses default animation of slide in from left and slide out to right animation.\n *\n * @param\n * navBundle -> The navigation bundle to add to the fragment after the pop occurs\n */\n @Override\n public void dismissFragment(Bundle navBundle) {\n getNavigationManager().dismissFragment(navBundle);\n }\n\n /**\n * Dismiss all fragments to the given index in the stack (With 0 being the root fragment)\n */\n @Override\n public void dismissToIndex(int index) {\n getNavigationManager().clearNavigationStackToIndex(index);\n }\n\n /**\n * Dismiss all the fragments on the Navigation Manager stack until the root fragment using the default slide in and out.\n */\n @Override\n public void dismissToRoot() {\n getNavigationManager().clearNavigationStackToRoot();\n }\n\n /**\n * Dismiss all the fragments on the Navigation Manager stack including the root fragment using the default slide in and out.\n * Present a fragment on the Navigation Manager using the default slide in and out.\n *\n * @param\n * navFragment -> The Fragment to present.\n */\n @Override\n public void replaceRootFragment(Navigation navFragment) {\n getNavigationManager().replaceRootFragment(navFragment);\n }\n\n /**\n * A method for setting the title of the action bar. (Saves you from having to call getActivity().setTitle())\n *\n * @param\n * resId -> Resource Id of the title you would like to set.\n */\n @Override\n public void setTitle(int resId) {\n setTitle(getString(resId));\n }\n\n /**\n * A method for setting the title of the action bar. (Saves you from having to call getActivity().setTitle())\n *\n * @param\n * title -> String of the title you would like to set.\n */\n @Override\n public void setTitle(String title) {\n mTitle = title;\n ActionBarManager.setTitle(getActivity(), mTitle);\n }\n\n /**\n * A method for retrieving the currently set title for the NavigationFragment\n *\n * @return\n * The current title of the NavigationFragment\n */\n @Override\n public String getTitle() {\n return mTitle;\n }\n\n @Override\n public boolean isPortrait() {\n return getNavigationManager().isPortrait();\n }\n\n @Override\n public boolean isTablet() {\n return getNavigationManager().isTablet();\n }\n}",
"public abstract class NavigationManagerFragment extends Fragment implements NavigationManagerContainer {\n // TODO: Animation making child disappear http://stackoverflow.com/a/23276145/845038\n private static final String TAG = NavigationManagerFragment.class.getSimpleName();\n\n private static final String KEY_NAVIGATION_MANAGER_CORE = \"KEY_NAVIGATION_MANAGER_CORE\";\n\n private NavigationManager mNavigationManager;\n\n // =========================================\n // Object Lifecycle\n // =========================================\n\n public NavigationManagerFragment() {}\n\n // =========================================\n // Fragment Lifecycle\n // =========================================\n\n @Override\n public void onCreate(@Nullable Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n\n if (savedInstanceState != null) {\n mNavigationManager = (NavigationManager)savedInstanceState.getSerializable(KEY_NAVIGATION_MANAGER_CORE);\n }\n\n mNavigationManager.setNavigationListener(ObjectUtils.as(NavigationManagerListener.class, getContext()));\n mNavigationManager.setContainer(this);\n }\n\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {\n return mNavigationManager.getLifecycle().onCreateView(inflater, container, savedInstanceState);\n }\n\n @Override\n public void onViewCreated(View view, Bundle savedInstanceState) {\n super.onViewCreated(view, savedInstanceState);\n mNavigationManager.getLifecycle().onViewCreated(view, mNavigationManager);\n }\n\n @Override\n public void onResume() {\n super.onResume();\n mNavigationManager.getLifecycle().onResume(mNavigationManager);\n }\n\n @Override\n public void onPause() {\n super.onPause();\n mNavigationManager.getLifecycle().onPause(mNavigationManager);\n }\n\n @Override\n public void onSaveInstanceState(Bundle outState) {\n super.onSaveInstanceState(outState);\n outState.putSerializable(KEY_NAVIGATION_MANAGER_CORE, mNavigationManager);\n }\n\n // =========================================\n // Public\n // =========================================\n\n public void setDefaultPresentAnimations(int animIn, int animOut) {\n getNavigationManager().setDefaultPresentAnimations(animIn, animOut);\n }\n\n public void setDefaultDismissAnimations(int animIn, int animOut) {\n getNavigationManager().setDefaultDismissAnimations(animIn, animOut);\n }\n\n // =========================================\n // NavigationManagerContainer\n // =========================================\n\n @Override\n public NavigationManager getNavigationManager() {\n return mNavigationManager;\n }\n\n @Override\n public Object getNavChildFragmentManager() {\n return getChildFragmentManager();\n }\n\n @Override\n public Activity getFragmentActivity() {\n return getActivity();\n }\n\n // =========================================\n // Private\n // =========================================\n\n protected void setNavigationManager(NavigationManager navigationManager) {\n mNavigationManager = navigationManager;\n }\n\n}",
"public class StackNavigationManagerFragment extends NavigationManagerFragment {\n private static final String TAG = StackNavigationManagerFragment.class.getSimpleName();\n\n private static final int SINGLE_STACK_MIN_ACTION_SIZE = 1;\n\n public static StackNavigationManagerFragment newInstance(Navigation fragment) {\n StackNavigationManagerFragment container = new StackNavigationManagerFragment();\n\n NavigationConfig config = NavigationConfig.builder()\n .setMinStackSize(SINGLE_STACK_MIN_ACTION_SIZE)\n .setPushContainerId(R.id.navigation_manager_fragment_container)\n .build();\n\n NavigationManager manager = new NavigationManager();\n manager.addInitialNavigation(fragment);\n manager.setNavigationConfig(config);\n manager.setLifecycle(new StackLifecycleManager());\n manager.setStack(new StackManager());\n manager.setState(new StateManager());\n\n container.setNavigationManager(manager);\n\n return container;\n }\n\n public StackNavigationManagerFragment() { }\n}",
"public class SampleFragment extends NavigationFragment {\n // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER\n private static final String ARG_FRAG_TEXT = \"ARG_FRAG_TEXT\";\n private static final String ARG_FRAG_COUNT = \"ARG_FRAG_COUNT\";\n\n private static final String ARG_MODEL_FROM_NAV_BUNDLE = \"ARG_MODEL_FROM_NAV_BUNDLE\";\n\n private String mFragText;\n private SampleModel model;\n\n private EditText edit1;\n private EditText edit2;\n private EditText edit3;\n\n private EditText fragIndex;\n\n private int mFragCount;\n\n /**\n * Use this factory method to create a new instance of\n * this fragment using the provided parameters.\n *\n * @param param1 Parameter 1.\n * @return A new instance of fragment SampleFragment.\n */\n public static SampleFragment newInstance(String param1, int fragCount) {\n SampleFragment fragment = new SampleFragment();\n Bundle args = new Bundle();\n args.putString(ARG_FRAG_TEXT, param1);\n args.putInt(ARG_FRAG_COUNT, fragCount);\n fragment.setArguments(args);\n return fragment;\n }\n\n public SampleFragment() {\n // Required empty public constructor\n model = new SampleModel();\n }\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n if (getArguments() != null) {\n mFragText = getArguments().getString(ARG_FRAG_TEXT);\n mFragCount = getArguments().getInt(ARG_FRAG_COUNT);\n }\n }\n\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container,\n Bundle savedInstanceState) {\n // Inflate the layout for this fragment\n View view = inflater.inflate(R.layout.fragment_sample, container, false);\n ((TextView) view.findViewById(R.id.sample_tv_text)).setText((mFragCount + 1) + \" \" + mFragText);\n\n edit1 = (EditText) view.findViewById(R.id.sample_et_text_1);\n edit1.setText(model.text1);\n edit1.addTextChangedListener(new TextWatcher() {\n @Override\n public void beforeTextChanged(CharSequence s, int start, int count, int after) {\n\n }\n\n @Override\n public void onTextChanged(CharSequence s, int start, int before, int count) {\n model.text1 = s.toString();\n }\n\n @Override\n public void afterTextChanged(Editable s) {\n\n }\n });\n\n edit2 = (EditText) view.findViewById(R.id.sample_et_text_2);\n edit2.setText(model.text2);\n edit2.addTextChangedListener(new TextWatcher() {\n @Override\n public void beforeTextChanged(CharSequence s, int start, int count, int after) {\n\n }\n\n @Override\n public void onTextChanged(CharSequence s, int start, int before, int count) {\n model.text2 = s.toString();\n }\n\n @Override\n public void afterTextChanged(Editable s) {\n\n }\n });\n\n edit3 = (EditText) view.findViewById(R.id.sample_et_text_3);\n edit3.setText(model.text3);\n edit3.addTextChangedListener(new TextWatcher() {\n @Override\n public void beforeTextChanged(CharSequence s, int start, int count, int after) {\n\n }\n\n @Override\n public void onTextChanged(CharSequence s, int start, int before, int count) {\n model.text3 = s.toString();\n }\n\n @Override\n public void afterTextChanged(Editable s) {\n\n }\n });\n\n fragIndex = (EditText)view.findViewById(R.id.frag_index_edit_text);\n\n view.findViewById(R.id.btn_pop_to_index).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n dismissToIndex(Integer.valueOf(fragIndex.getText().toString()));\n }\n });\n\n view.findViewById(R.id.sample_btn_present).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Navigation fragmentToPresent = SampleFragment.newInstance(\"Fragment added to Stack.\", (mFragCount + 1));\n presentFragment(fragmentToPresent);\n }\n });\n\n view.findViewById(R.id.sample_btn_present_override_animation).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Navigation fragmentToPresent = SampleFragment.newInstance(\"Fragment added to Stack.\", (mFragCount + 1));\n\n beginPresentation()\n .setCustomAnimations(R.anim.slide_in_from_bottom, R.anim.slide_out_to_top,\n R.anim.slide_out_to_bottom, R.anim.slide_in_from_top)\n .presentFragment(fragmentToPresent);\n }\n });\n\n view.findViewById(R.id.sample_btn_present_bundle).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Navigation fragmentToPresent = SampleFragment.newInstance(\"Fragment added to Stack.\", (mFragCount + 1));\n Bundle bundle = new Bundle();\n bundle.putSerializable(ARG_MODEL_FROM_NAV_BUNDLE, new SampleModel(model));\n\n beginPresentation().setNavBundle(bundle)\n .presentFragment(fragmentToPresent);\n }\n });\n\n view.findViewById(R.id.sample_btn_dismiss).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n dismissFragment();\n }\n });\n\n view.findViewById(R.id.sample_btn_dismiss_bundle).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Bundle bundle = new Bundle();\n bundle.putSerializable(ARG_MODEL_FROM_NAV_BUNDLE, new SampleModel(model));\n dismissFragment(bundle);\n }\n });\n\n view.findViewById(R.id.sample_btn_launch_activity).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n getActivity().startActivity(new Intent(getContext(), TestIntentLaunchingActivity.class));\n }\n });\n\n view.findViewById(R.id.sample_btn_replace_root).setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Navigation fragmentAsNewRoot = SampleFragment.newInstance(\"This is a replaced root Fragment\", 0);\n replaceRootFragment(fragmentAsNewRoot);\n }\n });\n\n return view;\n }\n\n @Override\n public void onResume() {\n super.onResume();\n\n if (getNavBundle() != null) {\n model = (SampleModel)getNavBundle().getSerializable(ARG_MODEL_FROM_NAV_BUNDLE);\n\n if (edit1 != null) {\n edit1.setText(model.text1);\n edit2.setText(model.text2);\n edit3.setText(model.text3);\n }\n }\n\n setTitle(\"Sample Fragment \" + mFragCount);\n\n // Using this to test if the memory space of the activity changes on rotation in the child\n Activity activity = getActivity();\n if (activity != null) {\n // Debug into this to check mHost is changed.\n setHasOptionsMenu(false);\n }\n }\n\n public int getFragCount() {\n return mFragCount;\n }\n\n private class SampleModel implements Serializable {\n public String text1;\n public String text2;\n public String text3;\n\n public SampleModel() {\n\n }\n\n public SampleModel(SampleModel model) {\n text1 = model.text1;\n text2 = model.text2;\n text3 = model.text3;\n }\n }\n}"
] | import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import com.github.dmcapps.navigationfragment.common.interfaces.Navigation;
import com.github.dmcapps.navigationfragment.v7.NavigationFragment;
import com.github.dmcapps.navigationfragment.v7.NavigationManagerFragment;
import com.github.dmcapps.navigationfragment.v7.StackNavigationManagerFragment;
import com.github.dmcapps.navigationfragmentexample.v7.NavigationFragments.SampleFragment;
import com.github.dmcapps.navigationfragmentexample.R; | package com.github.dmcapps.navigationfragmentexample.v7.DrawerExample;
public class NavigationDrawerExampleActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation_drawer_example);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
initialNavigationFragmentManager(SampleFragment.newInstance("Nav Camera", 0), "Camera");
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
}
else { | if(mVisibleFragment instanceof NavigationManagerFragment) { | 2 |
in-the-keyhole/khs-sherpa | src/main/java/com/khs/sherpa/SherpaContextListener.java | [
"public interface ApplicationContext extends ManagedBeanFactory {\n\n\tpublic static final String CONTEXT_PATH = \"com.khs.sherpa.SHREPA.CONTEXT\";\n\tpublic static final String SHERPA_CONTEXT = \"com.khs.sherpa.SHREPA.CONTEXT\";\n\t\n\tpublic static final String SETTINGS_JSONP = \"com.khs.sherpa.SETTGINS.JSONP\";\n\tpublic static final String SETTINGS_ADMIN_USER = \"com.khs.sherpa.SETTGINS.ADMIN_USER\";\n\tpublic static final String SETTINGS_ENDPOINT_AUTH = \"com.khs.sherpa.SETTGINS.ENDPOINT_AUTH\";\n\t\n\t\n\tpublic void setAttribute(String key, Object value);\n\t\n\tpublic Object getAttribute(String key);\n\n\tpublic ManagedBeanFactory getManagedBeanFactory();\n\t\n}",
"public class GenericApplicationContext implements ApplicationContext {\n\t\n\tpublic static final String SHERPA_APPLICATION_CONTEXT_ATTRIBUTE = GenericApplicationContext.class.getName() + \".CONTEXT\";\n\t\n\tprivate ManagedBeanFactory managedBeanFactory;\n\t\n\tprivate Map<String, Object> attributes = new LinkedHashMap<String, Object>();\n\t\n\tpublic GenericApplicationContext() {\n\t\tmanagedBeanFactory = new DefaultManagedBeanFactory();\n\t}\n\t\n\tpublic boolean containsManagedBean(Class<?> type) {\n\t\treturn managedBeanFactory.containsManagedBean(type);\n\t}\n\n\tpublic boolean containsManagedBean(String name) {\n\t\treturn managedBeanFactory.containsManagedBean(name);\n\t}\n\n\tpublic <T> T getManagedBean(Class<T> type) throws NoSuchManagedBeanExcpetion {\n\t\treturn managedBeanFactory.getManagedBean(type);\n\t}\n\n\tpublic <T> Collection<T> getManagedBeans(Class<T> type) {\n\t\treturn managedBeanFactory.getManagedBeans(type);\n\t}\n\t\n\tpublic Object getManagedBean(String name) throws NoSuchManagedBeanExcpetion {\n\t\treturn managedBeanFactory.getManagedBean(name);\n\t}\n\n\tpublic <T> T getManagedBean(String name, Class<T> type) throws NoSuchManagedBeanExcpetion {\n\t\treturn managedBeanFactory.getManagedBean(name, type);\n\t}\n\n\tpublic boolean isTypeMatch(String name, Class<?> type) throws NoSuchManagedBeanExcpetion {\n\t\treturn managedBeanFactory.isTypeMatch(name, type);\n\t}\n\n\tpublic Class<?> getType(String name) throws NoSuchManagedBeanExcpetion {\n\t\treturn managedBeanFactory.getType(name);\n\t}\n\n\tpublic void setAttribute(String key, Object value) {\n\t\tattributes.put(key, value);\n\t}\n\t\n\tpublic Object getAttribute(String key) {\n\t\treturn attributes.get(key);\n\t}\n\t\n\tpublic ManagedBeanFactory getManagedBeanFactory() {\n\t\treturn managedBeanFactory;\n\t}\n\n\tpublic static ApplicationContext getApplicationContext(ServletContext context) {\n\t\treturn (ApplicationContext) context.getAttribute(SHERPA_APPLICATION_CONTEXT_ATTRIBUTE);\n\t}\n\n\tpublic Map<String, Object> getEndpointTypes() {\n\t\treturn managedBeanFactory.getEndpointTypes();\n\t}\n\n}",
"public interface InitManageBeanFactory {\n\n\tpublic void loadManagedBeans(String path);\n\tpublic void init(SherpaSettings settings, ServletContext context);\n\t\n}",
"public interface ManagedBeanFactory {\n\n\t/**\n\t * @param type\n\t * @return \n\t */\n\tpublic boolean containsManagedBean(Class<?> type);\n\t\n\t/**\n\t * @param name\n\t * @return \n\t */\n\tpublic boolean containsManagedBean(String name);\n\t\n\t/**\n\t * @param type\n\t * @return \n\t * @throws NoSuchManagedBeanExcpetion\n\t */\n\tpublic <T> T getManagedBean(Class<T> type) throws NoSuchManagedBeanExcpetion;\n\t\n\t/**\n\t * @param type\n\t * @return\n\t */\n\tpublic <T> Collection<T> getManagedBeans(Class<T> type);\n\t\n\t/**\n\t * @param name\n\t * @return\n\t * @throws NoSuchManagedBeanExcpetion\n\t */\n\tpublic Object getManagedBean(String name) throws NoSuchManagedBeanExcpetion;\n\t\n\t/**\n\t * @param name\n\t * @param type\n\t * @return\n\t * @throws NoSuchManagedBeanExcpetion \n\t */\n\tpublic <T> T getManagedBean(String name, Class<T> type) throws NoSuchManagedBeanExcpetion;\n\t\n\t/**\n\t * @param name\n\t * @param type\n\t * @return\n\t * @throws NoSuchManagedBeanExcpetion\n\t */\n\tpublic boolean isTypeMatch(String name, Class<?> type) throws NoSuchManagedBeanExcpetion;\n\t\n\t/**\n\t * @param name\n\t * @return\n\t * @throws NoSuchManagedBeanExcpetion\n\t */\n\tpublic Class<?> getType(String name) throws NoSuchManagedBeanExcpetion;\n\t\n\t/**\n\t * @return\n\t */\n\tpublic Map<String, Object> getEndpointTypes();\n}",
"public class SherpaRuntimeException extends RuntimeException {\n\n\tprivate static final long serialVersionUID = 3997371687805128093L;\n\n\tpublic SherpaRuntimeException() {\n\t\tsuper();\n\t}\n\n\tpublic SherpaRuntimeException(String arg0, Throwable arg1) {\n\t\tsuper(arg0, arg1);\n\t}\n\n\tpublic SherpaRuntimeException(String arg0) {\n\t\tsuper(arg0);\n\t}\n\n\tpublic SherpaRuntimeException(Throwable arg0) {\n\t\tsuper(arg0);\n\t}\n\n}",
"public class CalendarParamParser implements ApplicationContextAware, ParamParser<Calendar> {\n\n\tpublic static final String DEFAULT = \"com.khs.sherpa.DEFUALT_CALENDAR_FORMAT\";\n\t\n\tprivate ApplicationContext applicationContext;\n\t\n\tpublic boolean isValid(Class<?> clazz) {\n\t\treturn clazz.isAssignableFrom(Calendar.class);\n\t}\n\n\tpublic Calendar parse(String value, Param annotation, Class<?> clazz) {\n\t\tString format = annotation.format();\n\t\tif(format == null) {\n\t\t\tformat = (String) applicationContext.getAttribute(DEFAULT);\n\t\t}\n\t\t\n\t\ttry {\n\t\t\tDateFormat fmt = new SimpleDateFormat(format);\n\t\t\tCalendar cal = Calendar.getInstance();\n\t\t\tcal.setTime(fmt.parse(value));\n\t\t\treturn cal;\n\t\t} catch (ParseException e) {\n\t\t\tthrow new RuntimeException(value+\" must be calender \");\n\t\t}\n\t}\n\n\tpublic void setApplicationContext(ApplicationContext applicationContext) {\n\t\tthis.applicationContext = applicationContext;\n\t}\n\n}",
"public class DateParamParser implements ApplicationContextAware, ParamParser<Date> {\n\n\tpublic static final String DEFAULT = \"com.khs.sherpa.DEFUALT_DATE_FORMAT\";\n\t\n\tprivate ApplicationContext applicationContext;\n\t\n\tpublic boolean isValid(Class<?> clazz) {\n\t\treturn clazz.isAssignableFrom(Date.class);\n\t}\n\n\tpublic Date parse(String value, Param annotation, Class<?> clazz) {\n\t\tString format = annotation.format();\n\t\tif(format == null || format.equals(\"\")) {\n\t\t\tformat = (String) applicationContext.getAttribute(DEFAULT);\n\t\t}\n\t\t\n\t\ttry {\n\t\t\tDateFormat fmt = new SimpleDateFormat(format);\n\t\t\treturn fmt.parse(value);\n\t\t} catch (ParseException e) {\n\t\t\tthrow new RuntimeException(value+\" must be date \");\n\t\t}\n\t}\n\n\tpublic void setApplicationContext(ApplicationContext applicationContext) {\n\t\tthis.applicationContext = applicationContext;\n\t}\n\n}",
"public class StringParamParser implements ApplicationContextAware, ParamParser<String> {\n\t\n\tpublic static final String DEFAULT = \"com.khs.sherpa.DEFUALT_STRING_FORMAT\";\n\t\n\tprivate ApplicationContext applicationContext;\n\t\n\tpublic String parse(String value, Param annotation, Class<?> clazz) {\n\t\tString format = annotation.format();\n\t\t\n\t\tif(format == null || format.equals(\"\")) {\n\t\t\tformat = (String) applicationContext.getAttribute(DEFAULT);\n\t\t}\n\t\t\n\t\treturn this.applyEncoding(value, format);\n\t}\n\n\tpublic boolean isValid(Class<?> clazz) {\n\t\treturn clazz.isAssignableFrom(String.class);\n\t}\n\n\tprivate String applyEncoding(String value,String format) {\n\t\tString result = value;\n\t\tif (format != null) {\n\t\t\tif (format.equals(Encode.XML)) {\n\t\t\t\tresult = StringEscapeUtils.escapeXml(value);\t\t\n\t\t\t} else if (format.equals(Encode.HTML)) {\n\t\t\t\tresult = StringEscapeUtils.escapeHtml4(value);\t\t\n\t\t\t} else if (format.equals(Encode.CSV)) {\n\t\t\t\tresult = StringEscapeUtils.escapeCsv(value);\n\t\t\t}\n\t\t}\n\t\t \n\t\treturn result;\n\t}\n\n\tpublic void setApplicationContext(ApplicationContext applicationContext) {\n\t\tthis.applicationContext = applicationContext;\n\t}\n}"
] | import com.khs.sherpa.context.factory.InitManageBeanFactory;
import com.khs.sherpa.context.factory.ManagedBeanFactory;
import com.khs.sherpa.exception.SherpaRuntimeException;
import com.khs.sherpa.parser.CalendarParamParser;
import com.khs.sherpa.parser.DateParamParser;
import com.khs.sherpa.parser.StringParamParser;
import java.lang.reflect.InvocationTargetException;
import java.util.HashSet;
import java.util.Set;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.reflections.Reflections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.khs.sherpa.context.ApplicationContext;
import com.khs.sherpa.context.GenericApplicationContext; | package com.khs.sherpa;
/*
* Copyright 2012 the original author or authors.
*
* 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.
*/
public class SherpaContextListener implements ServletContextListener {
private static final Logger LOGGER = LoggerFactory.getLogger("Sherpa");
public static final String SHERPA_CONFIG_LOCATION = "classpath:/sherpa.properties";
public void contextInitialized(ServletContextEvent servletContextEvent) {
servletContextEvent.getServletContext().log("Loading Sherpa Context... Start");
String configLocation = servletContextEvent.getServletContext().getInitParameter("sherpaConfigLocation");
if(configLocation == null) {
configLocation = SHERPA_CONFIG_LOCATION;
}
SherpaSettings settings = new SherpaSettings(configLocation);
ApplicationContext applicationContext = null;
// check if sherpa for spring application context is available
// if not, then use non-spring app context
Class<?> applicationContextClass = settings.applicationContext();
if(applicationContextClass != null) {
try {
applicationContext = (ApplicationContext) applicationContextClass.getDeclaredConstructor(ServletContext.class).newInstance(servletContextEvent.getServletContext());
} catch (InstantiationException e) {
e.printStackTrace();
throw new SherpaRuntimeException(e);
} catch (IllegalAccessException e) {
e.printStackTrace();
throw new SherpaRuntimeException(e);
} catch (IllegalArgumentException e) {
e.printStackTrace();
throw new SherpaRuntimeException(e);
} catch (SecurityException e) {
e.printStackTrace();
throw new SherpaRuntimeException(e);
} catch (InvocationTargetException e) {
e.printStackTrace();
throw new SherpaRuntimeException(e);
} catch (NoSuchMethodException e) {
e.printStackTrace();
throw new SherpaRuntimeException(e);
}
} else {
applicationContext = new GenericApplicationContext();
}
ManagedBeanFactory managedBeanFactory = applicationContext.getManagedBeanFactory();
applicationContext.setAttribute(ApplicationContext.CONTEXT_PATH,
servletContextEvent.getServletContext().getContextPath());
applicationContext.setAttribute(ApplicationContext.SETTINGS_JSONP, settings.jsonpSupport());
applicationContext.setAttribute(ApplicationContext.SETTINGS_ADMIN_USER, settings.sherpaAdmin());
applicationContext.setAttribute(ApplicationContext.SETTINGS_ENDPOINT_AUTH, settings.endpointAuthenication());
applicationContext.setAttribute(StringParamParser.DEFAULT, settings.encoding());
applicationContext.setAttribute(DateParamParser.DEFAULT, settings.dateFormat());
applicationContext.setAttribute(CalendarParamParser.DEFAULT, settings.dateFormat());
// Settings
applicationContext.setAttribute(SherpaSettings.SETTINGS_SERVER_URL, settings.serverUrl());
applicationContext.setAttribute(SherpaSettings.SETTINGS_SERVER_TOKEN, settings.serverToken());
| if (InitManageBeanFactory.class.isAssignableFrom(managedBeanFactory.getClass())) { | 2 |
douo/ActivityBuilder | compiler/src/main/java/info/dourok/compiler/result/ResultModel.java | [
"public class ConsumerHelper {\n public HashMap<Integer, ClassName> consumers;\n private static ConsumerHelper sInstance = new ConsumerHelper();\n\n private ConsumerHelper() {\n consumers = new HashMap<>();\n consumers.put(0, ClassName.get(Runnable.class));\n consumers.put(1, ClassName.get(\"info.dourok.esactivity.function\", \"Consumer\"));\n consumers.put(2, ClassName.get(\"info.dourok.esactivity.function\", \"BiConsumer\"));\n consumers.put(3, ClassName.get(\"info.dourok.esactivity.function\", \"TriConsumer\"));\n }\n\n public static ClassName get(int count) throws IOException {\n ClassName type = sInstance.consumers.get(count);\n if (type == null) {\n type = writeConsumer(count);\n sInstance.consumers.put(count, type);\n }\n return type;\n }\n\n private static ClassName writeConsumer(int count) throws IOException {\n String packageName = \"info.dourok.esactivity.function\";\n MethodSpec.Builder method =\n MethodSpec.methodBuilder(\"accept\").addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT);\n\n TypeSpec.Builder type =\n TypeSpec.interfaceBuilder(\"Consumer\" + count).addModifiers(Modifier.PUBLIC);\n for (int i = 0; i < count; i++) {\n type.addTypeVariable(TypeVariableName.get(\"T\" + i));\n method.addParameter(TypeVariableName.get(\"T\" + i), \"t\" + i);\n }\n type.addMethod(method.build());\n JavaFile.builder(packageName, type.build()).build().writeTo(EasyUtils.getFiler());\n return ClassName.get(packageName, \"Consumer\" + count);\n }\n}",
"public class ParameterModel {\n private String key;\n private String name;\n private String displayName;\n private TypeMirror type;\n private boolean keep;\n private TransmitType transmit;\n protected VariableElement element;\n\n public ParameterModel(BuilderParameter annotation, VariableElement element) {\n this.element = element;\n if (element.getModifiers().contains(Modifier.PRIVATE)) {\n error(\"BuilderParameter can not be private\", element);\n throw new IllegalStateException(\"BuilderParameter can not be private\");\n }\n name = element.getSimpleName().toString();\n // 将 mVar 转换为 var\n if (name.matches(\"m[A-Z].*$\")) {\n displayName =\n name.substring(1, 2).toLowerCase()\n + (name.length() > 2 ? name.substring(2, name.length()) : \"\");\n } else {\n displayName = name;\n }\n\n key =\n annotation.key().equals(BuilderParameter.USE_VARIABLE_NAME) ? getName() : annotation.key();\n keep = annotation.keep();\n type = element.asType();\n transmit = annotation.transmit();\n }\n\n /**\n * 用于 {@link Result} 注解方法\n *\n * @param element 方法的参数\n */\n public ParameterModel(VariableElement element, TransmitType transmit) {\n this.element = element;\n name = element.getSimpleName().toString();\n key = name;\n keep = false;\n type = element.asType();\n this.transmit = transmit;\n }\n\n /** 用于 {@link Result} 注解 {@link Activity} */\n public ParameterModel(AnnotationMirror annotationMirror) {\n // FIXME 优化,可提取为全局变量\n TypeElement element = getElements().getTypeElement(ResultParameter.class.getName());\n List<? extends Element> elements = element.getEnclosedElements();\n ExecutableElement name = null;\n ExecutableElement type = null;\n ExecutableElement transmit = null;\n for (Element e : elements) {\n if (\"name\".equals(e.getSimpleName().toString())) {\n name = (ExecutableElement) e;\n }\n if (\"type\".equals(e.getSimpleName().toString())) {\n type = (ExecutableElement) e;\n }\n if (\"transmit\".equals(e.getSimpleName().toString())) {\n transmit = (ExecutableElement) e;\n }\n }\n Map<? extends ExecutableElement, ? extends AnnotationValue> map =\n annotationMirror.getElementValues();\n this.name = (String) map.get(name).getValue();\n if (!SourceVersion.isName(this.name)) {\n error(\"not a valid name: \" + this.name, name);\n throw new IllegalStateException(\"not a valid name: \" + this.name);\n }\n this.key = this.name;\n this.type = (TypeMirror) map.get(type).getValue();\n AnnotationValue transmitValue = map.get(transmit);\n this.transmit =\n transmitValue == null\n ? TransmitType.AUTO\n : TransmitType.valueOf(transmitValue.getValue().toString());\n }\n\n public TypeMirror getType() {\n return type;\n }\n\n /** 如果是原生类型则返回装箱类型 */\n public TypeMirror getObjectType() {\n if (isPrimitive()) {\n return getTypes().boxedClass((PrimitiveType) getType()).asType();\n } else {\n return type;\n }\n }\n\n public VariableElement getElement() {\n return element;\n }\n\n public String getName() {\n return name;\n }\n\n /** 用于 Builder 方法名和方法参数 */\n public String getDisplayName() {\n return displayName;\n }\n\n public String getKey() {\n return key;\n }\n\n public boolean isKeep() {\n return keep;\n }\n\n public TransmitType getTransmit() {\n return transmit;\n }\n\n public boolean isPrimitive() {\n return getType() instanceof PrimitiveType;\n }\n\n public boolean isBoxed() {\n try {\n PrimitiveType primitiveType = getTypes().unboxedType(getType());\n if (primitiveType != null) {\n return true;\n }\n } catch (IllegalArgumentException e) {\n // ignore;\n }\n return false;\n }\n}",
"public enum TransmitType {\n // 如果能用 Bundle 传递则用 Bundle,不然用 REF\n AUTO,\n // 用 RefManager 直接传递引用\n REF,\n // TODO\n UNSAFE\n}",
"public static String capitalize(String s) {\n if (s.length() == 0) {\n return s;\n }\n return s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();\n}",
"public static void error(String msg) {\n S_INSTANCE.messager.printMessage(Diagnostic.Kind.ERROR, msg);\n}",
"public static Elements getElements() {\n return S_INSTANCE.elements;\n}"
] | import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeVariableName;
import info.dourok.compiler.ConsumerHelper;
import info.dourok.compiler.parameter.ParameterModel;
import info.dourok.esactivity.Result;
import info.dourok.esactivity.Transmit;
import info.dourok.esactivity.TransmitType;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.AnnotationValue;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import static info.dourok.compiler.EasyUtils.capitalize;
import static info.dourok.compiler.EasyUtils.error;
import static info.dourok.compiler.EasyUtils.getElements; | package info.dourok.compiler.result;
/**
* @author tiaolins
* @date 2017/9/4
*/
public class ResultModel {
private String name;
private List<ParameterModel> parameters;
private static final Pattern RESULT_PATTERN = Pattern.compile("result(?<name>[A-Z][\\w]*)");
/** 将 void result[Name](Parameters){} 解析为 ResultWriter */
public ResultModel(Result annotation, ExecutableElement element) {
Matcher matcher = RESULT_PATTERN.matcher(element.getSimpleName().toString());
if (matcher.find()) {
name = matcher.group("name").toLowerCase();
} else {
String msg =
String.format(
"Result annotated method must match 'result(?<name>[A-Z][\\\\w]*)',"
+ " %s is illegal result method name",
element.getSimpleName());
error(msg, element);
throw new IllegalStateException(msg);
}
List<? extends VariableElement> variableElements = element.getParameters();
parameters = new ArrayList<>(variableElements.size());
for (VariableElement variableElement : variableElements) {
Transmit t = variableElement.getAnnotation(Transmit.class);
parameters.add(
new ParameterModel(variableElement, t == null ? TransmitType.AUTO : t.value()));
}
}
public ResultModel(AnnotationMirror result) {
// FIXME 优化,可提取为全局变量
TypeElement element = getElements().getTypeElement(Result.class.getName());
List<? extends Element> elements = element.getEnclosedElements();
ExecutableElement name = null;
ExecutableElement parameters = null;
for (Element e : elements) {
if ("name".equals(e.getSimpleName().toString())) {
name = (ExecutableElement) e;
}
if ("parameters".equals(e.getSimpleName().toString())) {
parameters = (ExecutableElement) e;
}
}
// 见 com.sun.tools.javac.code.Attribute
// 常量就直接返回常量
// 类 返回 TypeMirror
// 枚举 返回 VariableElement
// 注解 返回 AnnotationMirror
//
AnnotationValue valueName = result.getElementValues().get(name);
if (valueName != null) {
this.name = (String) valueName.getValue();
} else {
error("Result annotated activity its name must specified");
throw new IllegalStateException("Result annotated activity its name must specified");
}
AnnotationValue ps = result.getElementValues().get(parameters);
// 没有参数 ps 为 null
if (ps != null) {
List list = (List) ps.getValue();
this.parameters = new ArrayList<>(list.size());
for (Object o : list) {
this.parameters.add(new ParameterModel((AnnotationMirror) o));
}
} else {
this.parameters = new ArrayList<>(0);
}
}
public List<ParameterModel> getParameters() {
return parameters;
}
public String getName() {
return name;
}
public String getCapitalizeName() { | return capitalize(getName()); | 3 |
CodeNMore/New-Beginner-Java-Game-Programming-Src | Episode 30/TileGame/src/dev/codenmore/tilegame/states/MenuState.java | [
"public class Handler {\n\t\n\tprivate Game game;\n\tprivate World world;\n\t\n\tpublic Handler(Game game){\n\t\tthis.game = game;\n\t}\n\t\n\tpublic GameCamera getGameCamera(){\n\t\treturn game.getGameCamera();\n\t}\n\t\n\tpublic KeyManager getKeyManager(){\n\t\treturn game.getKeyManager();\n\t}\n\t\n\tpublic MouseManager getMouseManager(){\n\t\treturn game.getMouseManager();\n\t}\n\t\n\tpublic int getWidth(){\n\t\treturn game.getWidth();\n\t}\n\t\n\tpublic int getHeight(){\n\t\treturn game.getHeight();\n\t}\n\n\tpublic Game getGame() {\n\t\treturn game;\n\t}\n\n\tpublic void setGame(Game game) {\n\t\tthis.game = game;\n\t}\n\n\tpublic World getWorld() {\n\t\treturn world;\n\t}\n\n\tpublic void setWorld(World world) {\n\t\tthis.world = world;\n\t}\n\n}",
"public class Assets {\n\t\n\tprivate static final int width = 32, height = 32;\n\t\n\tpublic static BufferedImage dirt, grass, stone, tree, rock;\n\tpublic static BufferedImage[] player_down, player_up, player_left, player_right;\n\tpublic static BufferedImage[] zombie_down, zombie_up, zombie_left, zombie_right;\n\n\tpublic static void init(){\n\t\tSpriteSheet sheet = new SpriteSheet(ImageLoader.loadImage(\"/textures/sheet.png\"));\n\t\t\n\t\tplayer_down = new BufferedImage[2];\n\t\tplayer_up = new BufferedImage[2];\n\t\tplayer_left = new BufferedImage[2];\n\t\tplayer_right = new BufferedImage[2];\n\t\t\n\t\tplayer_down[0] = sheet.crop(width * 4, 0, width, height);\n\t\tplayer_down[1] = sheet.crop(width * 5, 0, width, height);\n\t\tplayer_up[0] = sheet.crop(width * 6, 0, width, height);\n\t\tplayer_up[1] = sheet.crop(width * 7, 0, width, height);\n\t\tplayer_right[0] = sheet.crop(width * 4, height, width, height);\n\t\tplayer_right[1] = sheet.crop(width * 5, height, width, height);\n\t\tplayer_left[0] = sheet.crop(width * 6, height, width, height);\n\t\tplayer_left[1] = sheet.crop(width * 7, height, width, height);\n\t\t\n\t\tzombie_down = new BufferedImage[2];\n\t\tzombie_up = new BufferedImage[2];\n\t\tzombie_left = new BufferedImage[2];\n\t\tzombie_right = new BufferedImage[2];\n\t\t\n\t\tzombie_down[0] = sheet.crop(width * 4, height * 2, width, height);\n\t\tzombie_down[1] = sheet.crop(width * 5, height * 2, width, height);\n\t\tzombie_up[0] = sheet.crop(width * 6, height * 2, width, height);\n\t\tzombie_up[1] = sheet.crop(width * 7, height * 2, width, height);\n\t\tzombie_right[0] = sheet.crop(width * 4, height * 3, width, height);\n\t\tzombie_right[1] = sheet.crop(width * 5, height * 3, width, height);\n\t\tzombie_left[0] = sheet.crop(width * 6, height * 3, width, height);\n\t\tzombie_left[1] = sheet.crop(width * 7, height * 3, width, height);\n\t\t\n\t\tdirt = sheet.crop(width, 0, width, height);\n\t\tgrass = sheet.crop(width * 2, 0, width, height);\n\t\tstone = sheet.crop(width * 3, 0, width, height);\n\t\ttree = sheet.crop(0, 0, width, height * 2);\n\t\trock = sheet.crop(0, height * 2, width, height);\n\t}\n\t\n}",
"public interface ClickListener {\n\t\n\tpublic void onClick();\n\n}",
"public class UIImageButton extends UIObject {\n\n\tprivate BufferedImage[] images;\n\tprivate ClickListener clicker;\n\t\n\tpublic UIImageButton(float x, float y, int width, int height, BufferedImage[] images, ClickListener clicker) {\n\t\tsuper(x, y, width, height);\n\t\tthis.images = images;\n\t\tthis.clicker = clicker;\n\t}\n\n\t@Override\n\tpublic void tick() {}\n\n\t@Override\n\tpublic void render(Graphics g) {\n\t\tif(hovering)\n\t\t\tg.drawImage(images[1], (int) x, (int) y, width, height, null);\n\t\telse\n\t\t\tg.drawImage(images[0], (int) x, (int) y, width, height, null);\n\t}\n\n\t@Override\n\tpublic void onClick() {\n\t\tclicker.onClick();\n\t}\n\n}",
"public class UIManager {\n\n\tprivate Handler handler;\n\tprivate ArrayList<UIObject> objects;\n\t\n\tpublic UIManager(Handler handler){\n\t\tthis.handler = handler;\n\t\tobjects = new ArrayList<UIObject>();\n\t}\n\t\n\tpublic void tick(){\n\t\tfor(UIObject o : objects)\n\t\t\to.tick();\n\t}\n\t\n\tpublic void render(Graphics g){\n\t\tfor(UIObject o : objects)\n\t\t\to.render(g);\n\t}\n\t\n\tpublic void onMouseMove(MouseEvent e){\n\t\tfor(UIObject o : objects)\n\t\t\to.onMouseMove(e);\n\t}\n\t\n\tpublic void onMouseRelease(MouseEvent e){\n\t\tfor(UIObject o : objects)\n\t\t\to.onMouseRelease(e);\n\t}\n\t\n\tpublic void addObject(UIObject o){\n\t\tobjects.add(o);\n\t}\n\t\n\tpublic void removeObject(UIObject o){\n\t\tobjects.remove(o);\n\t}\n\n\tpublic Handler getHandler() {\n\t\treturn handler;\n\t}\n\n\tpublic void setHandler(Handler handler) {\n\t\tthis.handler = handler;\n\t}\n\n\tpublic ArrayList<UIObject> getObjects() {\n\t\treturn objects;\n\t}\n\n\tpublic void setObjects(ArrayList<UIObject> objects) {\n\t\tthis.objects = objects;\n\t}\n\t\n}"
] | import java.awt.Graphics;
import dev.codenmore.tilegame.Handler;
import dev.codenmore.tilegame.gfx.Assets;
import dev.codenmore.tilegame.ui.ClickListener;
import dev.codenmore.tilegame.ui.UIImageButton;
import dev.codenmore.tilegame.ui.UIManager; | package dev.codenmore.tilegame.states;
public class MenuState extends State {
private UIManager uiManager;
| public MenuState(Handler handler) { | 0 |
MontysCoconut/moco | src/test/java/de/uni/bremen/monty/moco/ast/ASTBuilderTest.java | [
"@RunWith(Parameterized.class)\npublic class CompileTestProgramsTest extends CompileFilesBaseTest {\n\n\tpublic CompileTestProgramsTest(File file, String fileName) {\n\t\tsuper(file, fileName);\n\t}\n\n\t@Parameters(name = \"Program: {1}\")\n\tpublic static Collection<Object[]> data() throws Exception {\n\t\tCollection<File> programFiles = getAllMontyFiles(\"testPrograms/\");\n\n\t\treturn buildParameterObject(programFiles);\n\t}\n\n\t@Test\n\tpublic void compileProgramTest() throws IOException, InterruptedException {\n\t\tfinal PrintStream bufferOut = System.out;\n\t\tfinal PrintStream bufferErr = System.err;\n\t\tfinal ByteArrayOutputStream outStream = setStdout();\n\t\tfinal ByteArrayOutputStream errorStream = setStdErr(file);\n\n\t\tif (inputFileExists(file)) {\n\t\t\tSystem.setProperty(\"testrun.readFromFile\", changeFileExtension(file, \".input\"));\n\t\t}\n\t\tMain.main(new String[] { \"-e\", file.getAbsolutePath() });\n\n\t\tif (outputFileExists(file)) {\n\t\t\tassertThat(getOutput(errorStream), is(isEmptyString()));\n\t\t\tassertThat(getOutput(outStream), is(expectedResultFromFile(file)));\n\t\t} else {\n\t\t\t// chop the last char to not contain /n in the string\n\t\t\tassertThat(StringUtils.chop(getOutput(errorStream)), is(expectedErrorFromFile(file)));\n\t\t\tassertThat(getOutput(outStream), is(isEmptyString()));\n\t\t}\n\t\tSystem.clearProperty(\"testrun.readFromFile\");\n\t\tSystem.setOut(bufferOut);\n\t\tSystem.setErr(bufferErr);\n\t}\n\n}",
"public class FunctionCall extends Expression implements Statement {\n\tprivate final ResolvableIdentifier identifier;\n\tprotected final List<Expression> arguments;\n\tprivate FunctionDeclaration declaration;\n\n\tpublic FunctionCall(Position position, ResolvableIdentifier identifier, List<Expression> arguments) {\n\t\tsuper(position);\n\t\tthis.identifier = identifier;\n\t\tthis.arguments = arguments;\n\t}\n\n\t/** get the identifier.\n\t *\n\t * @return the identifier */\n\tpublic ResolvableIdentifier getIdentifier() {\n\t\treturn identifier;\n\t}\n\n\t/** get the List of paramter\n\t *\n\t * @return the paramters */\n\tpublic List<Expression> getArguments() {\n\t\treturn arguments;\n\t}\n\n\t/** {@inheritDoc} */\n\t@Override\n\tpublic void visit(BaseVisitor visitor) {\n\t\tvisitor.visit(this);\n\t}\n\n\t/** {@inheritDoc} */\n\t@Override\n\tpublic void visitChildren(BaseVisitor visitor) {\n\t\tfor (Expression expression : arguments) {\n\t\t\tvisitor.visitDoubleDispatched(expression);\n\t\t}\n\t}\n\n\t/** @return the declaration */\n\tpublic FunctionDeclaration getDeclaration() {\n\t\treturn declaration;\n\t}\n\n\t/** @param declaration\n\t * the declaration to set */\n\tpublic void setDeclaration(FunctionDeclaration declaration) {\n\t\tthis.declaration = declaration;\n\t}\n}",
"public class WrappedFunctionCall extends Expression implements Statement {\n\tprivate FunctionCall functionCall;\n\tprivate MemberAccess memberAccess;\n\n\tpublic WrappedFunctionCall(Position position, FunctionCall functionCall) {\n\t\tsuper(position);\n\t\tthis.functionCall = functionCall;\n\t\tthis.memberAccess = null;\n\t}\n\n\t/** {@inheritDoc} */\n\t@Override\n\tpublic void visit(BaseVisitor visitor) {\n\t\tvisitor.visit(this);\n\t}\n\n\t/** {@inheritDoc} */\n\t@Override\n\tpublic void visitChildren(BaseVisitor visitor) {\n\t\tif (functionCall != null) {\n\t\t\tvisitor.visitDoubleDispatched(functionCall);\n\t\t}\n\t\tif (memberAccess != null) {\n\t\t\tvisitor.visitDoubleDispatched(memberAccess);\n\t\t}\n\t}\n\n\tpublic FunctionCall getFunctionCall() {\n\t\treturn functionCall;\n\t}\n\n\tpublic void setFunctionCall(FunctionCall functionCall) {\n\t\tthis.functionCall = functionCall;\n\t}\n\n\tpublic MemberAccess getMemberAccess() {\n\t\treturn memberAccess;\n\t}\n\n\tpublic void setMemberAccess(MemberAccess memberAccess) {\n\t\tthis.memberAccess = memberAccess;\n\t}\n\n\t@Override\n\tpublic TypeDeclaration getType() {\n\t\tif (functionCall != null) {\n\t\t\treturn functionCall.getType();\n\t\t}\n\t\tif (memberAccess != null) {\n\t\t\treturn memberAccess.getType();\n\t\t}\n\t\treturn null;\n\t}\n\n\t@Override\n\tpublic void setScope(Scope scope) {\n\t\tif (functionCall != null) {\n\t\t\tfunctionCall.setScope(scope);\n\t\t}\n\t}\n}",
"public class IntegerLiteral extends LiteralExpression<Integer> {\n\n\tpublic IntegerLiteral(Position position, Integer value) {\n\t\tsuper(position, value);\n\t}\n\n\t@Override\n\tpublic void visit(BaseVisitor visitor) {\n\t\tvisitor.visit(this);\n\t}\n\n}",
"public class Assignment extends BasicASTNode implements Statement {\n\n\t/** The left side. */\n\tprivate final Expression left;\n\n\t/** The right side. */\n\tprivate final Expression right;\n\n\tprivate FunctionDeclaration correspondingFunWrapper = null;\n\n\t/** Constructor.\n\t *\n\t * @param position\n\t * Position of this node\n\t * @param left\n\t * the left side\n\t * @param right\n\t * the right side */\n\tpublic Assignment(Position position, Expression left, Expression right) {\n\t\tsuper(position);\n\t\tthis.left = left;\n\t\tthis.right = right;\n\t}\n\n\t/** Get the left side.\n\t *\n\t * @return the left side */\n\tpublic Expression getLeft() {\n\t\treturn left;\n\t}\n\n\t/** Get the right side.\n\t *\n\t * @return the right side */\n\tpublic Expression getRight() {\n\t\treturn right;\n\t}\n\n\t/** {@inheritDoc} */\n\t@Override\n\tpublic void visit(BaseVisitor visitor) {\n\t\tvisitor.visit(this);\n\t}\n\n\t/** {@inheritDoc} */\n\t@Override\n\tpublic void visitChildren(BaseVisitor visitor) {\n\t\tvisitor.visitDoubleDispatched(left);\n\t\tvisitor.visitDoubleDispatched(right);\n\t}\n\n\tpublic boolean belongsToFunctionWrapper() {\n\t\treturn correspondingFunWrapper != null;\n\t}\n\n\tpublic void setCorrespondingFunctionWrapper(FunctionDeclaration fun) {\n\t\tcorrespondingFunWrapper = fun;\n\t}\n\n\tpublic FunctionDeclaration getCorrespondingFunctionWrapper() {\n\t\treturn correspondingFunWrapper;\n\t}\n}",
"public class ConditionalStatement extends BasicASTNode implements Statement {\n\n\tprivate final Expression condition;\n\tprivate final Block thenBlock;\n\tprivate final Block elseBlock;\n\n\t/** Constructor.\n\t *\n\t * @param position\n\t * Position of this node\n\t * @param condition\n\t * the condition\n\t * @param thenBlock\n\t * block if condition is true\n\t * @param elseBlock\n\t * block if condition is false */\n\tpublic ConditionalStatement(Position position, Expression condition, Block thenBlock, Block elseBlock) {\n\t\tsuper(position);\n\t\tthis.condition = condition;\n\t\tthis.thenBlock = thenBlock;\n\t\tthis.elseBlock = elseBlock;\n\t}\n\n\t/** get the condition\n\t *\n\t * @return the condition */\n\tpublic Expression getCondition() {\n\t\treturn condition;\n\t}\n\n\t/** get the then block\n\t *\n\t * @return the then block */\n\tpublic Block getThenBlock() {\n\t\treturn thenBlock;\n\t}\n\n\t/** get the else block\n\t *\n\t * @return the else block */\n\tpublic Block getElseBlock() {\n\t\treturn elseBlock;\n\t}\n\n\t/** {@inheritDoc} */\n\t@Override\n\tpublic void visit(BaseVisitor visitor) {\n\t\tvisitor.visit(this);\n\t}\n\n\t/** {@inheritDoc} */\n\t@Override\n\tpublic void visitChildren(BaseVisitor visitor) {\n\t\tvisitor.visitDoubleDispatched(condition);\n\t\tvisitor.visitDoubleDispatched(thenBlock);\n\t\tvisitor.visitDoubleDispatched(elseBlock);\n\t}\n\n}",
"public class TupleDeclarationFactory {\n\tprivate Set<Integer> tupleTypes = new HashSet<>();\n\n\tpublic void checkTupleType(int n) {\n\t\ttupleTypes.add(n);\n\t}\n\n\t/** This method checks whether the given Identifier is a tuple type. If yes, a new tuple type is introduced, given\n\t * that it was not introduced before.\n\t *\n\t * @param type */\n\tpublic void checkTupleType(ResolvableIdentifier type) {\n\t\tif (type == null) {\n\t\t\treturn;\n\t\t}\n\t\tString str = type.getSymbol();\n\t\tif (str.startsWith(\"Tuple\")) {\n\t\t\tString number = str.substring(5);\n\t\t\ttry {\n\t\t\t\tcheckTupleType(Integer.parseInt(number));\n\t\t\t} catch (Exception e) {\n\t\t\t\t// if the rest is not a number, we don't need to create a tuple type\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic ResolvableIdentifier getTupleIdentifier(List<ResolvableIdentifier> types) {\n\t\tcheckTupleType(types.size());\n\t\treturn new ResolvableIdentifier(\"Tuple\" + types.size(), types);\n\t}\n\n\t/** This method generates a new TupleType\n\t *\n\t * @param n\n\t * the size of the tuple type (TupleN)\n\t * @return a new TupleN ClassDeclaration */\n\tprotected ClassDeclaration createTupleType(int n) {\n\t\t// components of the class declaration\n\t\tClassDeclaration tupleType =\n\t\t new ClassDeclaration(new Position(), new Identifier(\"Tuple\" + n),\n\t\t new ArrayList<ResolvableIdentifier>(), new Block(new Position()), false,\n\t\t new ArrayList<AbstractGenericType>());\n\n\t\t// generate the initializer\n\t\tFunctionDeclaration initializer =\n\t\t new FunctionDeclaration(new Position(), new Identifier(\"initializer\"), new Block(new Position()),\n\t\t new ArrayList<VariableDeclaration>(), FunctionDeclaration.DeclarationType.INITIALIZER,\n\t\t (TypeDeclaration) null, false);\n\n\t\t// process the generic type parameters\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\t// add the type parameter to the class\n\t\t\tAbstractGenericType t = new AbstractGenericType(tupleType, new Position(), new Identifier(\"T\" + i));\n\t\t\ttupleType.getAbstractGenericTypes().add(t);\n\n\t\t\t// add an attribute with that type to the class\n\t\t\taddTupleAttribute(tupleType, i, t);\n\n\t\t\t// add a parameter to the initializer to initialize the attribute\n\t\t\taddTupleInitializerParameter(initializer, i, t);\n\t\t}\n\t\t// return nothing\n\t\tinitializer.getBody().addStatement(new ReturnStatement(new Position(), null));\n\t\t// add the initializer to the class declaration\n\t\ttupleType.getBlock().addDeclaration(initializer);\n\n\t\treturn tupleType;\n\t}\n\n\tprotected void addTupleAttribute(ClassDeclaration tupleType, int i, AbstractGenericType t) {\n\t\tVariableDeclaration attr =\n\t\t new VariableDeclaration(new Position(), new Identifier(\"_\" + (i + 1)), t,\n\t\t VariableDeclaration.DeclarationType.ATTRIBUTE);\n\t\ttupleType.getBlock().addDeclaration(attr);\n\t}\n\n\tprotected void addTupleInitializerParameter(FunctionDeclaration initializer, int i, AbstractGenericType t) {\n\t\t// add a parameter with that type to the initializer parameter list\n\t\tVariableDeclaration param =\n\t\t new VariableDeclaration(new Position(), new Identifier(\"p\" + (i + 1)), t,\n\t\t VariableDeclaration.DeclarationType.PARAMETER);\n\t\tinitializer.getParameters().add(param);\n\n\t\t// add an assignment to the initializer body: \"self._1 := p1\"\n\t\tinitializer.getBody().addStatement(\n\t\t new Assignment(new Position(),\n\t\t new MemberAccess(new Position(), new SelfExpression(new Position()), new VariableAccess(\n\t\t new Position(), ResolvableIdentifier.convert(new Identifier(\"_\" + (i + 1))))),\n\t\t new VariableAccess(new Position(), ResolvableIdentifier.convert(param.getIdentifier()))));\n\t}\n\n\tpublic Collection<ClassDeclaration> generateNecessaryTupleTypes() {\n\t\tCollection<ClassDeclaration> tupleClasses = new ArrayList<>(tupleTypes.size());\n\t\tfor (int n : tupleTypes) {\n\t\t\ttupleClasses.add(createTupleType(n));\n\t\t}\n\t\treturn tupleClasses;\n\t}\n\n\tpublic static boolean isTuple(ClassDeclaration type) {\n\t\tString strIdent = type.getIdentifier().getSymbol();\n\t\tif (strIdent.startsWith(\"Tuple\")) {\n\t\t\tint n;\n\t\t\ttry {\n\t\t\t\tn = Integer.parseInt(strIdent.substring(5));\n\t\t\t} catch (Exception e) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tif (type instanceof ClassDeclarationVariation) {\n\t\t\t\tif (((ClassDeclarationVariation) type).getConcreteGenericTypes().size() == n) {\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}\n}"
] | import de.uni.bremen.monty.moco.CompileTestProgramsTest;
import de.uni.bremen.monty.moco.antlr.MontyLexer;
import de.uni.bremen.monty.moco.antlr.MontyParser;
import de.uni.bremen.monty.moco.ast.declaration.*;
import de.uni.bremen.monty.moco.ast.expression.FunctionCall;
import de.uni.bremen.monty.moco.ast.expression.VariableAccess;
import de.uni.bremen.monty.moco.ast.expression.WrappedFunctionCall;
import de.uni.bremen.monty.moco.ast.expression.literal.IntegerLiteral;
import de.uni.bremen.monty.moco.ast.expression.literal.StringLiteral;
import de.uni.bremen.monty.moco.ast.statement.Assignment;
import de.uni.bremen.monty.moco.ast.statement.ConditionalStatement;
import de.uni.bremen.monty.moco.util.TupleDeclarationFactory;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.apache.commons.io.FileUtils;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertTrue; | /*
* moco, the Monty Compiler
* Copyright (c) 2013-2014, Monty's Coconut, All rights reserved.
*
* This file is part of moco, the Monty Compiler.
*
* moco 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.0 of the License, or (at your option) any later version.
*
* moco 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.
*
* Linking this program and/or its accompanying libraries statically or
* dynamically with other modules is making a combined work based on this
* program. Thus, the terms and conditions of the GNU General Public License
* cover the whole combination.
*
* As a special exception, the copyright holders of moco give
* you permission to link this programm and/or its accompanying libraries
* with independent modules to produce an executable, regardless of the
* license terms of these independent modules, and to copy and distribute the
* resulting executable under terms of your choice, provided that you also meet,
* for each linked independent module, the terms and conditions of the
* license of that module.
*
* An independent module is a module which is not
* derived from or based on this program and/or its accompanying libraries.
* If you modify this library, you may extend this exception to your version of
* the program or library, but you are not obliged to do so. If you do not wish
* to do so, delete this exception statement from your version.
*
* You should have received a copy of the GNU General Public
* License along with this library.
*/
package de.uni.bremen.monty.moco.ast;
public class ASTBuilderTest {
@Test
public void shouldConvertVariableInitialisation() throws Exception {
ModuleDeclaration ast = buildASTfrom("varDecl");
VariableDeclaration declaration = (VariableDeclaration) ast.getBlock().getDeclarations().get(0);
Assignment statement = (Assignment) ast.getBlock().getStatements().get(0);
VariableAccess left = (VariableAccess) statement.getLeft();
StringLiteral right = (StringLiteral) statement.getRight();
assertThat(declaration.getIdentifier().getSymbol(), is("s"));
assertThat(left.getIdentifier().getSymbol(), is("s"));
assertThat(right.getValue(), is("Hallo"));
}
@Test
public void shouldConvertDeclarationType() throws Exception {
ModuleDeclaration ast = buildASTfrom("declarationType");
ClassDeclaration classDecl = (ClassDeclaration) ast.getBlock().getDeclarations().get(0);
VariableDeclaration memberDecl = (VariableDeclaration) classDecl.getBlock().getDeclarations().get(0);
VariableDeclaration memberInit = (VariableDeclaration) classDecl.getBlock().getDeclarations().get(1);
FunctionDeclaration memberProc = (FunctionDeclaration) classDecl.getBlock().getDeclarations().get(2);
FunctionDeclaration memberFun = (FunctionDeclaration) classDecl.getBlock().getDeclarations().get(3);
VariableDeclaration varDecl = (VariableDeclaration) ast.getBlock().getDeclarations().get(1);
VariableDeclaration varInit = (VariableDeclaration) ast.getBlock().getDeclarations().get(2);
// 3 is the wrapper class
// 4 is the wrapper instance
FunctionDeclaration funDecl = (FunctionDeclaration) ast.getBlock().getDeclarations().get(5);
// 6 is the wrapper class
// 7 is the wrapper instance
FunctionDeclaration procDecl = (FunctionDeclaration) ast.getBlock().getDeclarations().get(8);
assertThat(varDecl.getDeclarationType(), is(VariableDeclaration.DeclarationType.VARIABLE));
assertThat(varInit.getDeclarationType(), is(VariableDeclaration.DeclarationType.VARIABLE));
assertThat(
funDecl.getParameters().get(0).getDeclarationType(),
is(VariableDeclaration.DeclarationType.PARAMETER));
assertThat(
procDecl.getParameters().get(0).getDeclarationType(),
is(VariableDeclaration.DeclarationType.PARAMETER));
assertThat(memberDecl.getDeclarationType(), is(VariableDeclaration.DeclarationType.ATTRIBUTE));
assertThat(memberInit.getDeclarationType(), is(VariableDeclaration.DeclarationType.ATTRIBUTE));
assertThat(
memberProc.getParameters().get(0).getDeclarationType(),
is(VariableDeclaration.DeclarationType.PARAMETER));
assertThat(
memberFun.getParameters().get(0).getDeclarationType(),
is(VariableDeclaration.DeclarationType.PARAMETER));
assertThat(memberProc.getDeclarationType(), is(FunctionDeclaration.DeclarationType.METHOD));
assertThat(memberFun.getDeclarationType(), is(FunctionDeclaration.DeclarationType.METHOD));
assertThat(funDecl.getDeclarationType(), is(FunctionDeclaration.DeclarationType.UNBOUND));
assertThat(procDecl.getDeclarationType(), is(FunctionDeclaration.DeclarationType.UNBOUND));
}
@Test
public void shouldConvertIf() throws Exception {
ModuleDeclaration ast = buildASTfrom("ifElse");
| ConditionalStatement condStmt = (ConditionalStatement) ast.getBlock().getStatements().get(0); | 5 |
MaLeLabTs/RegexGenerator | Random Regex Turtle/src/it/units/inginf/male/objective/performance/PerformacesObjective.java | [
"public class Configuration {\n\n private static final Logger LOG = Logger.getLogger(Configuration.class.getName()); \n \n /**\n * Initializes with default values, parameters and operators.\n */\n public Configuration() {\n this.evolutionParameters = new EvolutionParameters();\n this.evolutionParameters.setGenerations(1000);\n this.evolutionParameters.setPopulationSize(500);\n \n \n this.initialSeed = 0;\n this.jobId = 0;\n this.jobs = 4;\n this.objective = new PrecisionCharmaskLengthObjective() ;\n \n this.constants = Arrays.asList(\"\\\\d\",\n \"\\\\w\",\n \"\\\\.\",\":\",\",\",\";\",\n \"_\",\"=\",\"\\\"\",\"'\",\n \"\\\\\\\\\",\n \"/\", \n \"\\\\?\",\"\\\\!\",\n \"\\\\}\",\"\\\\{\",\"\\\\(\",\"\\\\)\",\"\\\\[\",\"\\\\]\",\"<\",\">\",\n \"@\",\"#\",\" \",\" \");\n this.ranges = new LinkedList<>();\n this.operators = new ArrayList<>(Arrays.asList(\"it.units.inginf.male.tree.operator.Group\",\n \"it.units.inginf.male.tree.operator.NonCapturingGroup\",\n \"it.units.inginf.male.tree.operator.ListMatch\",\n \"it.units.inginf.male.tree.operator.ListNotMatch\",\n \"it.units.inginf.male.tree.operator.MatchOneOrMore\",\n \"it.units.inginf.male.tree.operator.MatchZeroOrMore\",\n \"it.units.inginf.male.tree.operator.MatchZeroOrOne\",\n \"it.units.inginf.male.tree.operator.MatchMinMax\"));\n //Add context wise operators (lookaround)\n this.operators.addAll(\n Arrays.asList(\"it.units.inginf.male.tree.operator.PositiveLookbehind\",\"it.units.inginf.male.tree.operator.NegativeLookbehind\",\n \"it.units.inginf.male.tree.operator.PositiveLookahead\", \"it.units.inginf.male.tree.operator.NegativeLookahead\"));\n \n \n this.initNodeFactory(); //initNodeFactory also instantiate the NodeFactory object, this decouples the terminalset between threads\n List<Leaf> terminalSet = this.nodeFactory.getTerminalSet();\n //Add default ranges\n terminalSet.add(new RegexRange(\"A-Z\"));\n terminalSet.add(new RegexRange(\"a-z\"));\n terminalSet.add(new RegexRange(\"A-Za-z\"));\n \n this.evaluator = new CachedTreeEvaluator();\n this.evaluator.setup(Collections.EMPTY_MAP);\n \n this.outputFolderName = \".\";\n \n this.strategyParameters = new HashMap<>();\n this.strategyParameters.put(\"runStrategy\",\"it.units.inginf.male.strategy.impl.SeparateAndConquerStrategy\");\n \n this.strategyParameters.put(\"runStrategy2\",\"it.units.inginf.male.strategy.impl.DiversityElitarismStrategy\");\n \n this.strategyParameters.put(\"objective2\",\"it.units.inginf.male.objective.CharmaskMatchLengthObjective\");\n \n \n this.strategyParameters.put(\"threads\",\"2\");\n this.strategy = new CombinedMultithreadStrategy(); //MultithreadStrategy();\n \n //TerminalSet and population builder setup is performed later\n this.terminalSetBuilderParameters = new HashMap<>();\n this.terminalSetBuilderParameters.put(\"tokenThreashold\",\"80.0\");\n this.terminalSetBuilder = new TokenizedContextTerminalSetBuilder();\n \n this.populationBuilderParameters = new HashMap<>();\n this.populationBuilderParameters.put(\"tokenThreashold\",\"80.0\"); \n this.populationBuilder = new TokenizedContextPopulationBuilder();\n \n this.postprocessorParameters = new HashMap<>();\n this.postprocessor = new BasicPostprocessor();\n this.postprocessor.setup(Collections.EMPTY_MAP);\n \n this.bestSelectorParameters = new HashMap<>();\n this.bestSelector = new BasicLearningBestSelector();\n this.bestSelector.setup(Collections.EMPTY_MAP); \n } \n \n /**\n * Updates dataset and datasetCotainer stats and structures, and initializes terminalSetBuilder and populationBuilder.\n * You should invoke this method when the original Dataset/DatasetContainer is modified.\n */\n public void setup(){ \n this.datasetContainer.update();\n this.terminalSetBuilder.setup(this);\n this.populationBuilder.setup(this); \n }\n\n public Configuration(Configuration cc) {\n this.evolutionParameters = cc.getEvolutionParameters();\n this.initialSeed = cc.getInitialSeed();\n this.jobId = cc.getJobId();\n this.jobs = cc.getJobs();\n this.objective = cc.getObjective();\n this.evaluator = cc.getEvaluator();\n this.outputFolder = cc.getOutputFolder();\n this.outputFolderName = cc.getOutputFolderName();\n this.strategy = cc.getStrategy();\n this.strategyParameters = new LinkedHashMap<>(cc.getStrategyParameters()); //Permits runtime modification of Configuration objects (do not affect other configurations); Used in combined strategy\n this.configName = cc.getConfigName();\n this.populationBuilder = cc.getPopulationBuilder();\n this.terminalSetBuilderParameters = cc.getTerminalSetBuilderParameters();\n this.terminalSetBuilder = cc.getTerminalSetBuilder();\n this.populationBuilderParameters = cc.getPopulationBuilderParameters();\n this.datasetContainer = cc.getDatasetContainer();\n this.postprocessor = cc.getPostProcessor();\n this.postprocessorParameters = cc.getPostprocessorParameters();\n //nodeFactory is not dublicated \n this.bestSelector = cc.getBestSelector();\n this.bestSelectorParameters = cc.getBestSelectorParameters();\n this.constants = cc.constants;\n this.ranges = cc.ranges;\n this.operators = cc.operators;\n this.isFlagging = cc.isIsFlagging();\n this.initNodeFactory(); //initialized nodeFacory after introducing constants and operators\n }\n \n \n private EvolutionParameters evolutionParameters;\n private long initialSeed;\n private int jobs;\n private int jobId;\n private transient File outputFolder;\n private String outputFolderName;\n private transient Objective objective;\n private transient TreeEvaluator evaluator;\n private transient ExecutionStrategy strategy; \n private Map<String, String> strategyParameters; \n private String configName;\n private transient NodeFactory nodeFactory;\n private transient InitialPopulationBuilder populationBuilder;\n private Map<String, String> populationBuilderParameters;\n private Map<String, String> terminalSetBuilderParameters;\n private transient TerminalSetBuilder terminalSetBuilder;\n private DatasetContainer datasetContainer;\n private transient Postprocessor postprocessor;\n private Map<String, String> postprocessorParameters;\n private List<String> constants;\n private List<String> ranges;\n private List<String> operators;\n private transient BestSelector bestSelector;\n private Map<String, String> bestSelectorParameters;\n private boolean isFlagging = false;\n\n public NodeFactory getNodeFactory() {\n return nodeFactory;\n }\n\n public void setNodeFactory(NodeFactory nodeFactory) {\n this.nodeFactory = nodeFactory;\n }\n \n public String getConfigName() {\n return configName;\n }\n\n public void setConfigName(String configName) {\n this.configName = configName;\n }\n\n public EvolutionParameters getEvolutionParameters() {\n return evolutionParameters;\n }\n\n public void setEvolutionParameters(EvolutionParameters evolutionParameters) {\n this.evolutionParameters = evolutionParameters;\n }\n\n public long getInitialSeed() {\n return initialSeed;\n }\n\n public void setInitialSeed(long initialSeed) {\n this.initialSeed = initialSeed;\n }\n\n public Map<String, String> getPostprocessorParameters() {\n return postprocessorParameters;\n }\n\n public void setPostprocessorParameters(Map<String, String> postprocessorParameters) {\n this.postprocessorParameters = postprocessorParameters;\n }\n\n public Map<String, String> getTerminalSetBuilderParameters() {\n return terminalSetBuilderParameters;\n }\n\n public void setTerminalSetBuilderParameters(Map<String, String> terminalSetBuilderParameters) {\n this.terminalSetBuilderParameters = terminalSetBuilderParameters;\n }\n\n public TerminalSetBuilder getTerminalSetBuilder() {\n return terminalSetBuilder;\n }\n\n public void setTerminalSetBuilder(TerminalSetBuilder terminalSetBuilder) {\n this.terminalSetBuilder = terminalSetBuilder;\n }\n\n public List<String> getConstants() {\n return constants;\n }\n\n public void setConstants(List<String> constants) {\n this.constants = constants;\n }\n\n public List<String> getRanges() {\n return ranges;\n }\n\n public void setRanges(List<String> ranges) {\n this.ranges = ranges;\n }\n\n public List<String> getOperators() {\n return operators;\n }\n\n public void setOperators(List<String> operators) {\n this.operators = operators;\n }\n\n public int getJobId() {\n return jobId;\n }\n\n public void setJobId(int jobId) {\n this.jobId = jobId;\n }\n\n /**\n * Returns a clone of the current objective, the strategies should get the objective once and cache the instance.\n * There should be and instance per strategy (and one instance per job).\n * Calling the objective a lot of times is going to instantiate a lot of instances. \n * @return\n */\n public Objective getObjective() {\n return objective.cloneObjective();\n }\n\n public void setObjective(Objective objective) {\n this.objective = objective;\n }\n\n public TreeEvaluator getEvaluator() {\n return evaluator;\n }\n\n public void setEvaluator(TreeEvaluator evaluator) {\n this.evaluator = evaluator;\n }\n\n public File getOutputFolder() {\n return outputFolder;\n }\n\n public void setOutputFolder(File outputFolder) {\n this.outputFolder = outputFolder;\n }\n\n public int getJobs() {\n return jobs;\n }\n\n public void setJobs(int jobs) {\n this.jobs = jobs;\n }\n\n public ExecutionStrategy getStrategy() {\n return strategy;\n }\n\n public void setStrategy(ExecutionStrategy strategy) {\n this.strategy = strategy;\n }\n\n public Map<String, String> getStrategyParameters() {\n return strategyParameters;\n }\n\n public void setStrategyParameters(Map<String, String> strategyParameters) {\n this.strategyParameters = strategyParameters;\n }\n\n public InitialPopulationBuilder getPopulationBuilder() {\n return populationBuilder;\n }\n\n public void setPopulationBuilder(InitialPopulationBuilder populationBuilder) {\n this.populationBuilder = populationBuilder;\n }\n\n public Postprocessor getPostProcessor() {\n return postprocessor;\n }\n\n public void setPostProcessor(Postprocessor postprocessor) {\n this.postprocessor = postprocessor;\n } \n \n public BestSelector getBestSelector() {\n return bestSelector;\n }\n\n public void setBestSelector(BestSelector bestSelector) {\n this.bestSelector = bestSelector;\n this.bestSelector.setup(Collections.EMPTY_MAP);\n }\n \n public Map<String, String> getBestSelectorParameters() {\n return bestSelectorParameters;\n }\n\n public boolean isIsFlagging() {\n return isFlagging;\n }\n\n public void setIsFlagging(boolean isFlagging) {\n this.isFlagging = isFlagging;\n }\n\n public void setBestSelectorParameters(Map<String, String> bestSelectorParameters) {\n this.bestSelectorParameters = bestSelectorParameters;\n }\n\n public String getOutputFolderName() {\n return outputFolderName;\n }\n\n public void setOutputFolderName(String outputFolderName) {\n this.outputFolderName = outputFolderName;\n this.outputFolder = new File(this.outputFolderName);\n checkOutputFolder(this.outputFolder);\n }\n \n private void checkOutputFolder(File outputFolder) throws ConfigurationException {\n if (outputFolder == null) {\n throw new IllegalArgumentException(\"The output folder must be set\");\n }\n if (!outputFolder.isDirectory()) {\n if (!outputFolder.mkdirs()) {\n throw new ConfigurationException(\"Unable to create output folder \\\"\"+outputFolder+\"\\\"\");\n }\n }\n } \n \n public DatasetContainer getDatasetContainer() {\n return datasetContainer;\n }\n\n /**\n * Sets the new datasetContainer.\n * you need to call the the setup command, in order to initialize the datasetContainer and \n * in order to generate terminalSets and initial populations,\n * @param datasetContainer\n */\n public void setDatasetContainer(DatasetContainer datasetContainer) {\n this.datasetContainer = datasetContainer;\n }\n \n public Map<String, String> getPopulationBuilderParameters() {\n return populationBuilderParameters;\n } \n \n public final void initNodeFactory() {\n NodeFactory factory = new NodeFactory();\n List<Leaf> terminals = factory.getTerminalSet();\n\n for (String c : constants) { \n terminals.add(new Constant(c));\n }\n\n for (String s : ranges) {\n terminals.add(new RegexRange(s));\n }\n\n List<Node> functions = factory.getFunctionSet();\n for (String o : operators) {\n try {\n functions.add(buildOperatorInstance(o));\n } catch (ClassNotFoundException | IllegalAccessException | InstantiationException ex) {\n LOG.log(Level.SEVERE, \"Unable to create required operator: \" + o, ex);\n System.exit(1);\n }\n }\n this.nodeFactory = factory;\n }\n \n private Node buildOperatorInstance(String o) throws ClassNotFoundException, InstantiationException, IllegalAccessException {\n Class<? extends Node> operatorClass = Class.forName(o).asSubclass(Node.class);\n Node operator = operatorClass.newInstance();\n return operator;\n }\n \n /**\n * Changes the configured fitness with the java class objectiveClass\n * @param objectiveClass\n * @return\n */\n public void updateObjective(String objectiveClass) {\n try {\n Class<? extends Objective> operatorClass = Class.forName(objectiveClass).asSubclass(Objective.class);\n Objective operator = operatorClass.newInstance();\n this.objective = operator;\n } catch (ClassNotFoundException | InstantiationException | IllegalAccessException ex) {\n LOG.log(Level.SEVERE, \"Unable to create required objective: \" + objectiveClass, ex);\n System.exit(1);\n }\n //NO OP \n }\n}",
"public class BasicStats {\n\n //added transient modifier for webapp\n public long fp = 0;\n transient public long fn = 0;\n public long tp = 0;\n transient public long tn = 0;\n\n public double accuracy() {\n return ((double) (tp + tn)) / (tp + tn + fp + fn);\n }\n\n public double precision() {\n return ((double) tp) / (tp + fp);\n }\n\n public double recall() {\n return ((double) tp) / (tp + fn);\n }\n \n public double fpr(){\n return ((double) fp) / (tn + fp);\n }\n \n public double fnr(){\n return ((double) fn) / (tp + fn);\n }\n\n /**\n * To use when number of positives cases != tp+fn (eg: text extraction)\n *\n * @param positives\n * @return\n */\n public double recall(int positives) {\n return ((double) tp) / (positives);\n }\n\n public double trueNegativeRate() {\n return ((double) tn) / (tn + fn);\n }\n\n public double specificity() {\n return ((double) tn) / (tn + fp);\n }\n\n /**\n * To use when number of negative cases != tn+fp (eg: text extraction)\n *\n * @param negatives\n * @return\n */\n public double specificity(int negatives) {\n return ((double) tn) / (negatives);\n }\n\n public double fMeasure() {\n double precision = this.precision();\n double recall = this.recall();\n return 2 * (precision * recall) / (precision + recall);\n }\n\n public BasicStats add(BasicStats stats) {\n this.fp += stats.fp;\n this.fn += stats.fn;\n this.tp += stats.tp;\n this.tn += stats.tn;\n return this;\n }\n}",
"public class DataSet {\n\n public DataSet() {\n }\n\n public DataSet(String name) {\n this.name = name;\n }\n\n public DataSet(String name, String description, String regexTarget) {\n this.name = name;\n this.description = description;\n this.regexTarget = regexTarget;\n }\n \n public String name;\n public String description;\n public String regexTarget;\n public List<Example> examples = new LinkedList<>();\n \n private transient int numberMatches;\n private transient int numberUnmatches;\n private transient int numberMatchedChars;\n private transient int numberUnmatchedChars;\n private transient int numberUnAnnotatedChars;\n private transient int numberOfChars;\n \n private transient DataSet stripedDataset;\n \n private transient Map<Long, List<DataSet>> separateAndConquerLevels = new ConcurrentHashMap<>();\n //private transient DataSet datasetFocus = null;\n private final static Logger LOG = Logger.getLogger(DataSet.class.getName()); \n \n /**\n * Updates the dataset statistics, numberMatches, numberMatchesChars and so on\n */\n public void updateStats(){\n this.numberMatches = 0;\n this.numberUnmatches = 0;\n this.numberMatchedChars = 0;\n this.numberUnmatchedChars = 0;\n this.numberUnAnnotatedChars = 0;\n this.numberOfChars = 0;\n \n for (Example ex : this.examples) {\n this.numberMatches += ex.match.size();\n this.numberUnmatches += ex.unmatch.size();\n this.numberMatchedChars += ex.getNumberMatchedChars();\n this.numberUnmatchedChars += ex.getNumberUnmatchedChars();\n this.numberOfChars += ex.getNumberOfChars();\n }\n this.numberUnAnnotatedChars = this.numberOfChars - this.numberMatchedChars -this.numberUnmatchedChars;\n }\n\n public int getNumberMatches() {\n return numberMatches;\n }\n\n public int getNumberUnmatches() {\n return numberUnmatches;\n }\n\n public int getNumberMatchedChars() {\n return numberMatchedChars;\n }\n\n public int getNumberUnmatchedChars() {\n return numberUnmatchedChars;\n }\n\n public int getNumberUnannotatedChars() {\n return numberUnAnnotatedChars;\n }\n\n public int getNumberOfChars() {\n return numberOfChars;\n }\n \n public int getNumberExamples(){\n return this.examples.size();\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public String getRegexTarget() {\n return regexTarget;\n }\n\n public void setRegexTarget(String regexTarget) {\n this.regexTarget = regexTarget;\n }\n \n \n \n public String getStatsString(){\n StringBuilder stats = new StringBuilder();\n stats.append(\"DataSet \").append(this.name).append(\" stats:\\n\")\n .append(\"number examples: \").append(this.getNumberExamples())\n .append(\"\\noverall chars in dataset: \").append(this.getNumberOfChars())\n .append(\"\\nnumber matches: \").append(this.getNumberMatches())\n .append(\"\\ncharacters in matches: \").append(this.getNumberMatchedChars())\n .append(\"\\nnumber unmatches: \").append(this.getNumberUnmatches())\n .append(\"\\ncharacters in unmatches: \").append(this.getNumberUnmatchedChars())\n .append(\"\\nunannotated chars: \").append(this.getNumberUnannotatedChars());\n return stats.toString();\n }\n \n public void randomize() {\n Random random = new Random();\n for (int i = 0; i < examples.size(); i++) {\n if((((i*100)/examples.size())%5)==0){\n System.out.format(\"randomize %d%%\\n\",((i*100)/examples.size()));\n }\n Example ex1;\n Example ex2;\n int destIndex = random.nextInt(examples.size());\n ex1 = examples.get(i);\n ex2 = examples.get(destIndex);\n examples.set(i, ex2);\n examples.set(destIndex, ex1);\n }\n }\n \n public void populateUnmatchesFromMatches(){\n for (Example ex : this.examples) {\n ex.populateUnmatchesFromMatches();\n }\n \n }\n \n /**\n * Populate examples with the temporary list of matched and unmatched strings (using current match and unmatch bounds)\n */\n public void populateAnnotatedStrings(){\n for(Example example : this.examples){\n example.populateAnnotatedStrings();\n }\n }\n\n public List<Example> getExamples() {\n return this.examples;\n }\n \n /**\n * Create a dataset which is a \"view\" of the current dataset.A subset of the dataset defined by ranges.\n * @param name\n * @param ranges\n * @return\n */\n public DataSet subDataset(String name, List<Range> ranges){\n // ranges are inclusive\n DataSet subDataset = new DataSet(name);\n for(Range range : ranges){\n for(int index = range.getStartIndex(); index <= range.getEndIndex(); index++){\n subDataset.getExamples().add(this.getExamples().get(index));\n } \n }\n return subDataset;\n }\n \n /**\n * \n * @param marginSize is the how much the margin is bigger than match size. marginSize = 3 means the number of characters in margins is three times the match characters.\n * @return\n */\n public DataSet initStripedDatasetView(double marginSize){\n this.stripedDataset = new DataSet(this.name, this.description, this.regexTarget);\n for(Example example : this.examples){\n this.stripedDataset.getExamples().addAll(this.stripeExample(example, marginSize));\n } \n return this.stripedDataset;\n }\n \n \n \n /**\n * creates a list of examples created from examples by splitting example in littler pieces.\n * The pieces are created from a window surrounding the example matches. \n * When two or more windows overlaps, the windows merge together and a single multi-match example is created.\n * @param example\n * @param marginSize\n * @return\n */\n protected static List<Example> stripeExample(Example example, double marginSize){ \n List<Example> slicesExampleList = new LinkedList<>(); \n //create ranges covering the saved portions \n List<Bounds> savedBounds = new LinkedList<>();\n for(Bounds match : example.getMatch()){\n //double -> int cast works like Math.floor(); Gives the same results of the older integer version\n int charMargin = (int) Math.max(((match.size() * marginSize) / 2.0),1.0);\n Bounds grownMatch = new Bounds(match.start - charMargin, match.end + charMargin);\n grownMatch.start = (grownMatch.start >= 0) ? grownMatch.start:0;\n grownMatch.end = (grownMatch.end <= example.getNumberOfChars()) ? grownMatch.end : example.getNumberOfChars();\n savedBounds.add(grownMatch);\n }\n //compact bounds, create a compact representation of saved portions\n //This bounds represents the slices we are going to cut the example to \n savedBounds = Bounds.mergeBounds(savedBounds);\n \n //Create examples from slices\n for(Bounds slice : savedBounds){\n Example sliceExample = new Example();\n sliceExample.setString(example.getString().substring(slice.start, slice.end));\n \n //find owned matches\n for(Bounds match : example.getMatch()){\n if(match.start >= slice.end){\n break; //only the internal for\n } else {\n Bounds slicedMatch = match.windowView(slice);\n if(slicedMatch != null){\n sliceExample.getMatch().add(slicedMatch);\n }\n }\n }\n //find owned unmatches\n for(Bounds unmatch : example.getUnmatch()){\n if(unmatch.start >= slice.end){\n break; //only the internal for\n } else {\n Bounds slicedUnmatch = unmatch.windowView(slice);\n if(slicedUnmatch != null){\n sliceExample.getUnmatch().add(slicedUnmatch);\n }\n }\n }\n \n sliceExample.populateAnnotatedStrings();\n slicesExampleList.add(sliceExample);\n }\n return slicesExampleList;\n }\n \n /**\n * Returns the last initialized striped version of this DataSet. In order to change the window size you have to call initStripedDatasetView() again.\n * @return\n */\n public DataSet getStripedDataset(){\n// if(this.stripedDataset == null){\n// Logger.getLogger(this.getClass().getName()).info(\"getStripedDataset returns, null dataset cause uninitialized striped dataset.\");\n// }\n return this.stripedDataset;\n }\n \n /**\n * Returns the \"Separate and Conquer\" sub-dataset of the requested level.\n * Level 0 is the original dataset, level 1 is the dataset obtained from\n * the first reduction, level 2 is the dataset from the second reduction\n * and so on.\n * \n * @param divideEtImperaLevel\n * @param jobId\n * @return\n */\n public DataSet getSeparateAndConquerDataSet(int divideEtImperaLevel, int jobId) {\n if(divideEtImperaLevel == 0){\n return this;\n }\n return getSeparateAndConquerLevels(jobId).get(divideEtImperaLevel - 1);\n }\n \n /**\n * Divide dataset, defaults to converting match to unmatches and text extraction problem.\n * @param individualRegex\n * @param jobId\n * @return\n */\n public boolean addSeparateAndConquerLevel(String individualRegex, int jobId){\n return this.addSeparateAndConquerLevel(individualRegex, jobId, true, false);\n }\n \n /**\n * From the last generated \"Separate and conquer\" sub-dataset, creates a new sub-dataset.\n * We evaluate the individualRegex on the dataset examples, matches that are \n * correctly extracted are removed. A removed match is converted to unmatch or unannotated depending\n * on the convertToUnmatch value: True==unmatch\n * In striping mode, the base dataset and striped dataset are reduced separately.\n * There is no direct connection from --i.e the third level of the original dataset\n * and the third level of the striped dataset. The reduced dataset depends only \n * by its parent.\n * NOTE: The levels are the sub-dataset, level 0 is the original dataset, level 1 is\n * the sub-dataset reduced from the original dataset, level 2 is a sub-dataset reduced\n * from the level 1 dataset and so on.\n * @param individualRegex\n * @param jobId\n * @param convertToUnmatch when true, the eliminated matches are converted into unmatches, otherwise unannotated area.\n * @param isFlagging\n * @return true, when the dataset has been modified by reduction\n */\n public boolean addSeparateAndConquerLevel(String individualRegex, int jobId, boolean convertToUnmatch, boolean isFlagging){\n boolean modified = false;\n DataSet oldDataset = this.getLastSeparateAndConquerDataSet(jobId);\n DataSet dataset = oldDataset.reduceSeparateAndConquerDataset(individualRegex, convertToUnmatch, isFlagging);\n dataset.updateStats();\n modified = (dataset.getNumberMatches() != oldDataset.getNumberMatches());\n this.getSeparateAndConquerLevels(jobId).add(dataset);\n if(this.getStripedDataset()!=null){\n modified = this.getStripedDataset().addSeparateAndConquerLevel(individualRegex,jobId, convertToUnmatch, isFlagging) || modified; \n }\n return modified;\n }\n \n /**\n * Creates a DataSet (sub-dataset for \"Separate and conquer\") from this dataset instance.\n * We evaluate the individualRegex on the dataset examples, matches that are \n * correctly extracted are removed. A removed match is converted to unmatch or unannotated depending\n * on the convertToUnmatch value: True==unmatch\n */\n private DataSet reduceSeparateAndConquerDataset(String individualRegex, boolean convertToUnmatch, boolean isFlagging ){\n //initialize pattern matcher\n Pattern pattern = Pattern.compile(individualRegex);\n Matcher individualRegexMatcher = pattern.matcher(\"\");\n \n DataSet reducedDataset = new DataSet(this.name, \"Reduction: \"+individualRegex, this.regexTarget);\n for(Example example : this.examples){\n if(!isFlagging){\n reducedDataset.getExamples().add(this.reduceSeparateAndConquerExample(example, individualRegexMatcher, convertToUnmatch));\n } else {\n reducedDataset.getExamples().add(this.reduceSeparateAndConquerFlaggingExample(example, individualRegexMatcher));\n }\n } \n return reducedDataset;\n }\n \n private boolean isTruePositiveFlaggingExample(Example example, Matcher individualRegexMatcher){\n try {\n Matcher m = individualRegexMatcher.reset(example.getString());\n return (m.find() && !example.match.isEmpty());\n } catch (StringIndexOutOfBoundsException ex) {\n return false;\n /**\n * Workaround: riferimento BUG: 6984178\n * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6984178\n * con i quantificatori greedy restituisce una eccezzione\n * invece che restituire un \"false\".\n */\n }\n }\n \n \n private Example reduceSeparateAndConquerFlaggingExample(Example example, Matcher individualRegexMatcher){\n //Negative or unannotated are left unchanged\n if(!isTruePositiveFlaggingExample(example, individualRegexMatcher)){\n return new Example(example);\n }\n Example unannotatedExample = new Example();\n unannotatedExample.setString(example.getString());\n return unannotatedExample;\n }\n \n private Example reduceSeparateAndConquerExample(Example example, Matcher individualRegexMatcher, boolean convertToUnmatch){\n return this.manipulateSeparateAndConquerExample(example, individualRegexMatcher, convertToUnmatch);\n }\n \n //creates a reduced (\"Separate and conquer\") Example instance from an example and a given Regex Instance \n //ELIMINATED Feature: When doFocus is true, the method perform focus action instead of examples reduction (Focus action creates the complementary of the reduction in order to focus evolution).\n \n //When convertToUnmatch is true extracted matches are converted into unannotated. \n private Example manipulateSeparateAndConquerExample(Example example, Matcher individualRegexMatcher, boolean convertToUnmatch){\n Example exampleClone = new Example(example);\n List<Bounds> extractions = new LinkedList<>();\n try {\n Matcher m = individualRegexMatcher.reset(example.getString());\n while (m.find()) {\n Bounds bounds = new Bounds(m.start(0), m.end(0));\n extractions.add(bounds);\n }\n } catch (StringIndexOutOfBoundsException ex) {\n /**\n * Workaround: riferimento BUG: 6984178\n * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6984178\n * con i quantificatori greedy restituisce una eccezzione\n * invece che restituire un \"false\".\n */\n }\n \n //remove extracted matches\n for (Iterator<Bounds> it = exampleClone.getMatch().iterator(); it.hasNext();) {\n Bounds match = it.next();\n for(Bounds extraction : extractions){\n //when doFocus is true, match is remove when equals\n if(match.equals(extraction)){\n it.remove();\n if(convertToUnmatch){\n exampleClone.getUnmatch().add(match);\n }\n break;\n }\n //Optimization\n //extractions are in ascending order.. because find is going to extract in this order\n if(extraction.start > match.end){\n break;\n }\n }\n }\n \n exampleClone.mergeUnmatchesBounds();\n exampleClone.populateAnnotatedStrings();\n return exampleClone;\n }\n \n public DataSet getLastSeparateAndConquerDataSet(int jobId){\n List<DataSet> datasetsList = this.getSeparateAndConquerLevels(jobId);\n if(datasetsList.isEmpty()){\n return this;\n }\n return datasetsList.get(datasetsList.size() -1);\n }\n \n public int getNumberOfSeparateAndConquerLevels(int jobId){\n return this.getSeparateAndConquerLevels(jobId).size();\n }\n \n \n /**\n * Returns all the \"Separate and conquer\" sub-datasets lists, for all the current threads.\n * The map resolves a ThreadID to the thread sub-datasets (levels) list. \n * @return\n */\n public Map<Long, List<DataSet>> getAllSeparateAndConquerLevels(){\n return this.separateAndConquerLevels;\n }\n \n /**\n * Returns the list of the sub-datasets created by \"Separate and conquer\", for the current thread.\n * The threads (aka active Jobs) have their own sub-datasets. This works right as\n * far as there is a *:1 relation between Jobs and Threads and we clean the generated\n * levels when a new Job is stated.\n * The levels are the sub-dataset, level 0 is the original dataset, level 1 is\n * the sub-dataset reduced from the original dataset, level 2 is a sub-dataset reduced\n * from the level 1 dataset and so on.\n * @param jobId\n * @return The list of sub datasets\n */\n public List<DataSet> getSeparateAndConquerLevels(long jobId){\n if (this.separateAndConquerLevels.containsKey(jobId)){\n return this.separateAndConquerLevels.get(jobId);\n } else {\n List<DataSet> newDatasetList = new LinkedList<>();\n this.separateAndConquerLevels.put(jobId, newDatasetList);\n return newDatasetList;\n }\n }\n \n /**\n * Resets the \"Separate and conquer\" for the current thread only.\n * Deletes all the generated (reduced) sub-datasets for the current thread.\n */\n public void resetSeparateAndConquer(long jobId){\n this.getSeparateAndConquerLevels(jobId).clear();\n if(this.getStripedDataset()!=null){\n this.getStripedDataset().getSeparateAndConquerLevels(jobId).clear();\n }\n }\n \n \n /**\n * Resets the \"Separate and conquer\", delete reduced sub-datasets, for all threads.\n */\n public void resetAllSeparateAndConquer(){\n this.getAllSeparateAndConquerLevels().clear();\n }\n \n \n public void removeSeparateAndConquerLevel(int jobID){\n List<DataSet> separateAndConquerLevelsForJob = this.getSeparateAndConquerLevels(jobID);\n if(!separateAndConquerLevelsForJob.isEmpty()){\n separateAndConquerLevelsForJob.remove(separateAndConquerLevelsForJob.size()-1);\n }\n }\n\n \n \n public static class Example {\n\n public Example() {\n }\n \n public Example(Example example) {\n this.string = example.string;\n this.match= new LinkedList<>(example.match);\n this.unmatch = new LinkedList<>(example.unmatch);\n if(example.matchedStrings!=null){\n this.matchedStrings = new LinkedList<>(example.matchedStrings);\n }\n if(example.unmatchedStrings!=null){\n this.unmatchedStrings = new LinkedList<>(example.unmatchedStrings);\n }\n }\n \n public String string;\n public List<Bounds> match = new LinkedList<>();\n public List<Bounds> unmatch = new LinkedList<>();\n transient protected List<String> matchedStrings = new LinkedList<>();\n transient protected List<String> unmatchedStrings = new LinkedList<>();\n\n public void addMatchBounds(int bs, int bf) {\n Bounds boundaries = new Bounds(bs, bf);\n match.add(boundaries);\n }\n \n public void addUnmatchBounds(int bs, int bf) {\n Bounds boundaries = new Bounds(bs, bf);\n unmatch.add(boundaries);\n }\n \n public int getNumberMatchedChars(){\n return getNumberCharsInsideIntervals(match);\n }\n \n public int getNumberUnmatchedChars(){\n return getNumberCharsInsideIntervals(unmatch);\n }\n \n public int getNumberOfChars(){\n return string.length();\n }\n \n private int getNumberCharsInsideIntervals(List<Bounds> textIntervals){\n int countChars = 0;\n for(Bounds interval : textIntervals){\n countChars += (interval.end - interval.start);\n }\n return countChars;\n }\n \n public void populateAnnotatedStrings(){\n this.matchedStrings.clear();\n for(Bounds bounds : this.match){\n this.matchedStrings.add(this.string.substring(bounds.start,bounds.end));\n }\n this.unmatchedStrings.clear();\n for(Bounds bounds : this.unmatch){\n this.unmatchedStrings.add(this.string.substring(bounds.start,bounds.end));\n }\n }\n\n \n public List<String> getMatchedStrings() {\n return matchedStrings;\n }\n \n public List<String> getUnmatchedStrings() {\n return unmatchedStrings;\n }\n \n public String getString() {\n return string;\n }\n\n public List<Bounds> getMatch() {\n return match;\n }\n\n public List<Bounds> getUnmatch() {\n return unmatch;\n }\n\n public void setString(String string) {\n this.string = string;\n }\n \n \n /**\n * Creates fully annotated examples based on the provided matches (bounds)\n * All chars are going to be annotated. \n */\n public void populateUnmatchesFromMatches(){\n this.unmatch.clear();\n //generate unmatches\n int previousMatchFinalIndex = 0;\n for(DataSet.Bounds oneMatch : this.match){\n if(oneMatch.start > previousMatchFinalIndex){\n this.addUnmatchBounds(previousMatchFinalIndex, oneMatch.start);\n }\n previousMatchFinalIndex = oneMatch.end;\n }\n if(previousMatchFinalIndex < string.length()){\n /*\n the right value of the interval can be equal than the string.lenght\n because the substrings are left-inclusive and right-exclusive\n */\n this.addUnmatchBounds(previousMatchFinalIndex, string.length());\n }\n }\n\n public int getNumberMatches() {\n return this.match.size();\n }\n \n /**\n * Returns the annotated strings, matches and unmatches\n * @return a list of all annotated strings\n */\n public List<String> getAnnotatedStrings(){\n List<String> annotatedStrings = new LinkedList<>();\n for(Bounds bounds : this.getMatch()){\n annotatedStrings.add(this.getString().substring(bounds.start, bounds.end));\n }\n for(Bounds bounds : this.getUnmatch()){\n annotatedStrings.add(this.getString().substring(bounds.start, bounds.end));\n }\n return annotatedStrings;\n }\n \n /**\n * This method generates all the annotated strings; the strings are in the same order\n * they appear into the example. This method has been created in order to mantain the\n * same behavior for the getAnnotatedStrings method (different order).\n * @return\n */\n public List<String> getOrderedAnnotatedStrings(){\n List<Bounds> boundsList = new LinkedList<>(this.getMatch());\n boundsList.addAll(this.getUnmatch());\n Collections.sort(boundsList); \n List<String> annotatedStrings = new LinkedList<>();\n for(Bounds bounds : boundsList){\n annotatedStrings.add(this.getString().substring(bounds.start, bounds.end));\n }\n return annotatedStrings;\n }\n \n \n public void mergeUnmatchesBounds(){\n this.unmatch = Bounds.mergeBounds(this.unmatch);\n }\n \n }\n \n static public class Bounds implements Comparable<Bounds>{\n public Bounds(int start, int end) {\n this.start = start;\n this.end = end;\n }\n public int start;\n public int end;\n \n public int size(){\n return ( this.end - this.start );\n };\n\n @Override\n public int hashCode() {\n int hash = 3;\n hash = 97 * hash + this.start;\n hash = 97 * hash + this.end;\n return hash;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (obj == null) {\n return false;\n }\n if (getClass() != obj.getClass()) {\n return false;\n }\n final Bounds other = (Bounds) obj;\n return ((this.end == other.end)&&(this.start == other.start));\n }\n \n /**\n * Convert a list of bounds in a more compact representation; this works with overlapping intervals too.\n * Remind that bounds define ranges with start inclusive and end inclusive index.\n * @param boundsList\n * @return\n */\n static public List<Bounds> mergeBounds(List<Bounds> boundsList){\n List<Bounds> newBoundsList = new LinkedList<>();\n if(boundsList.isEmpty()){\n return newBoundsList;\n }\n Collections.sort(boundsList);\n Bounds prevBounds = new Bounds(boundsList.get(0).start, boundsList.get(0).end);\n for (int i = 1; i < boundsList.size(); i++) {\n Bounds currentBounds = boundsList.get(i);\n if(currentBounds.start <= prevBounds.end){\n //merge\n prevBounds.end = Math.max(currentBounds.end,prevBounds.end);\n } else {\n newBoundsList.add(prevBounds);\n prevBounds = new Bounds(currentBounds.start, currentBounds.end);\n }\n }\n newBoundsList.add(prevBounds);\n return newBoundsList;\n }\n \n /**\n * Creates a new Bounds object representing this interval relative a rangeBounds\n * interval. --i.e: this [4,9] ; this.windowView([2,7]) == [2,7] \n * When this Bounds object is out of the window, windowView returns null. \n * @param rangeBounds\n * @return\n */\n public Bounds windowView(Bounds rangeBounds){\n Bounds newBounds = new Bounds(this.start-rangeBounds.start, this.end-rangeBounds.start);\n if((newBounds.start >= rangeBounds.size())||(newBounds.end<=0)){\n return null; //Out of window\n }\n newBounds.start = Math.max(newBounds.start,0);\n newBounds.end = Math.min(newBounds.end,rangeBounds.size());\n return newBounds;\n }\n \n @Override\n public int compareTo(Bounds o) {\n return (this.start - o.start);\n }\n \n public boolean isSubsetOf(Bounds bounds){\n return (this.start >= bounds.start) && (this.end <= bounds.end);\n }\n \n /**\n * When this Bounds objects overlaps the bounds argument (range intersection is not empty) returns true; otherwise returns false.\n * Zero length bounds are considered overlapping when they adhere each other --i.e: [3,5] and [5,5] are considered overlapping\n * [3,3] and [3,8] are overlapping ranges.\n * @param bounds The range to compare, for intersections, with the calling instance \n * @return true when the ranges overlap\n */\n public boolean overlaps(Bounds bounds){\n return this.start == bounds.start || this.end == bounds.end || ((this.start < bounds.end) && (this.end > bounds.start));\n }\n \n \n //extracted ranges are always ordered collection. In case you have to sort the collection first.\n //AnnotatedRanges are sorted internally by the method\n /**\n * Counts the number of checkedRanges that overlaps with the zoneRanges. A Bounds object in checkedRanges who doesn't overlap\n * with zoneRanges are not counted.\n * @param ranges\n * @param zoneRanges\n * @return\n */\n static public int countRangesThatCollideZone(List<Bounds> ranges, List<Bounds> zoneRanges) {\n int overallEOAA = 0;\n Collections.sort(zoneRanges); \n \n //This approach relies on the fact that both annotatedRanges and extracted ranges are ordered\n for (Bounds extractedBounds : ranges) {\n for (Bounds expectedBounds : zoneRanges) {\n if(expectedBounds.start >= extractedBounds.end){\n break;\n } \n if(extractedBounds.overlaps(expectedBounds)){\n overallEOAA++;\n break;\n }\n }\n }\n return overallEOAA;\n }\n\n }\n \n public Example getExample(int index){\n return examples.get(index);\n }\n}",
"static public class Bounds implements Comparable<Bounds>{\n public Bounds(int start, int end) {\n this.start = start;\n this.end = end;\n }\n public int start;\n public int end;\n \n public int size(){\n return ( this.end - this.start );\n };\n\n @Override\n public int hashCode() {\n int hash = 3;\n hash = 97 * hash + this.start;\n hash = 97 * hash + this.end;\n return hash;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (obj == null) {\n return false;\n }\n if (getClass() != obj.getClass()) {\n return false;\n }\n final Bounds other = (Bounds) obj;\n return ((this.end == other.end)&&(this.start == other.start));\n }\n \n /**\n * Convert a list of bounds in a more compact representation; this works with overlapping intervals too.\n * Remind that bounds define ranges with start inclusive and end inclusive index.\n * @param boundsList\n * @return\n */\n static public List<Bounds> mergeBounds(List<Bounds> boundsList){\n List<Bounds> newBoundsList = new LinkedList<>();\n if(boundsList.isEmpty()){\n return newBoundsList;\n }\n Collections.sort(boundsList);\n Bounds prevBounds = new Bounds(boundsList.get(0).start, boundsList.get(0).end);\n for (int i = 1; i < boundsList.size(); i++) {\n Bounds currentBounds = boundsList.get(i);\n if(currentBounds.start <= prevBounds.end){\n //merge\n prevBounds.end = Math.max(currentBounds.end,prevBounds.end);\n } else {\n newBoundsList.add(prevBounds);\n prevBounds = new Bounds(currentBounds.start, currentBounds.end);\n }\n }\n newBoundsList.add(prevBounds);\n return newBoundsList;\n }\n \n /**\n * Creates a new Bounds object representing this interval relative a rangeBounds\n * interval. --i.e: this [4,9] ; this.windowView([2,7]) == [2,7] \n * When this Bounds object is out of the window, windowView returns null. \n * @param rangeBounds\n * @return\n */\n public Bounds windowView(Bounds rangeBounds){\n Bounds newBounds = new Bounds(this.start-rangeBounds.start, this.end-rangeBounds.start);\n if((newBounds.start >= rangeBounds.size())||(newBounds.end<=0)){\n return null; //Out of window\n }\n newBounds.start = Math.max(newBounds.start,0);\n newBounds.end = Math.min(newBounds.end,rangeBounds.size());\n return newBounds;\n }\n \n @Override\n public int compareTo(Bounds o) {\n return (this.start - o.start);\n }\n \n public boolean isSubsetOf(Bounds bounds){\n return (this.start >= bounds.start) && (this.end <= bounds.end);\n }\n \n /**\n * When this Bounds objects overlaps the bounds argument (range intersection is not empty) returns true; otherwise returns false.\n * Zero length bounds are considered overlapping when they adhere each other --i.e: [3,5] and [5,5] are considered overlapping\n * [3,3] and [3,8] are overlapping ranges.\n * @param bounds The range to compare, for intersections, with the calling instance \n * @return true when the ranges overlap\n */\n public boolean overlaps(Bounds bounds){\n return this.start == bounds.start || this.end == bounds.end || ((this.start < bounds.end) && (this.end > bounds.start));\n }\n \n \n //extracted ranges are always ordered collection. In case you have to sort the collection first.\n //AnnotatedRanges are sorted internally by the method\n /**\n * Counts the number of checkedRanges that overlaps with the zoneRanges. A Bounds object in checkedRanges who doesn't overlap\n * with zoneRanges are not counted.\n * @param ranges\n * @param zoneRanges\n * @return\n */\n static public int countRangesThatCollideZone(List<Bounds> ranges, List<Bounds> zoneRanges) {\n int overallEOAA = 0;\n Collections.sort(zoneRanges); \n \n //This approach relies on the fact that both annotatedRanges and extracted ranges are ordered\n for (Bounds extractedBounds : ranges) {\n for (Bounds expectedBounds : zoneRanges) {\n if(expectedBounds.start >= extractedBounds.end){\n break;\n } \n if(extractedBounds.overlaps(expectedBounds)){\n overallEOAA++;\n break;\n }\n }\n }\n return overallEOAA;\n }\n\n}",
"public static class Example {\n\n public Example() {\n }\n \n public Example(Example example) {\n this.string = example.string;\n this.match= new LinkedList<>(example.match);\n this.unmatch = new LinkedList<>(example.unmatch);\n if(example.matchedStrings!=null){\n this.matchedStrings = new LinkedList<>(example.matchedStrings);\n }\n if(example.unmatchedStrings!=null){\n this.unmatchedStrings = new LinkedList<>(example.unmatchedStrings);\n }\n }\n \n public String string;\n public List<Bounds> match = new LinkedList<>();\n public List<Bounds> unmatch = new LinkedList<>();\n transient protected List<String> matchedStrings = new LinkedList<>();\n transient protected List<String> unmatchedStrings = new LinkedList<>();\n\n public void addMatchBounds(int bs, int bf) {\n Bounds boundaries = new Bounds(bs, bf);\n match.add(boundaries);\n }\n \n public void addUnmatchBounds(int bs, int bf) {\n Bounds boundaries = new Bounds(bs, bf);\n unmatch.add(boundaries);\n }\n \n public int getNumberMatchedChars(){\n return getNumberCharsInsideIntervals(match);\n }\n \n public int getNumberUnmatchedChars(){\n return getNumberCharsInsideIntervals(unmatch);\n }\n \n public int getNumberOfChars(){\n return string.length();\n }\n \n private int getNumberCharsInsideIntervals(List<Bounds> textIntervals){\n int countChars = 0;\n for(Bounds interval : textIntervals){\n countChars += (interval.end - interval.start);\n }\n return countChars;\n }\n \n public void populateAnnotatedStrings(){\n this.matchedStrings.clear();\n for(Bounds bounds : this.match){\n this.matchedStrings.add(this.string.substring(bounds.start,bounds.end));\n }\n this.unmatchedStrings.clear();\n for(Bounds bounds : this.unmatch){\n this.unmatchedStrings.add(this.string.substring(bounds.start,bounds.end));\n }\n }\n\n \n public List<String> getMatchedStrings() {\n return matchedStrings;\n }\n \n public List<String> getUnmatchedStrings() {\n return unmatchedStrings;\n }\n \n public String getString() {\n return string;\n }\n\n public List<Bounds> getMatch() {\n return match;\n }\n\n public List<Bounds> getUnmatch() {\n return unmatch;\n }\n\n public void setString(String string) {\n this.string = string;\n }\n \n \n /**\n * Creates fully annotated examples based on the provided matches (bounds)\n * All chars are going to be annotated. \n */\n public void populateUnmatchesFromMatches(){\n this.unmatch.clear();\n //generate unmatches\n int previousMatchFinalIndex = 0;\n for(DataSet.Bounds oneMatch : this.match){\n if(oneMatch.start > previousMatchFinalIndex){\n this.addUnmatchBounds(previousMatchFinalIndex, oneMatch.start);\n }\n previousMatchFinalIndex = oneMatch.end;\n }\n if(previousMatchFinalIndex < string.length()){\n /*\n the right value of the interval can be equal than the string.lenght\n because the substrings are left-inclusive and right-exclusive\n */\n this.addUnmatchBounds(previousMatchFinalIndex, string.length());\n }\n }\n\n public int getNumberMatches() {\n return this.match.size();\n }\n \n /**\n * Returns the annotated strings, matches and unmatches\n * @return a list of all annotated strings\n */\n public List<String> getAnnotatedStrings(){\n List<String> annotatedStrings = new LinkedList<>();\n for(Bounds bounds : this.getMatch()){\n annotatedStrings.add(this.getString().substring(bounds.start, bounds.end));\n }\n for(Bounds bounds : this.getUnmatch()){\n annotatedStrings.add(this.getString().substring(bounds.start, bounds.end));\n }\n return annotatedStrings;\n }\n \n /**\n * This method generates all the annotated strings; the strings are in the same order\n * they appear into the example. This method has been created in order to mantain the\n * same behavior for the getAnnotatedStrings method (different order).\n * @return\n */\n public List<String> getOrderedAnnotatedStrings(){\n List<Bounds> boundsList = new LinkedList<>(this.getMatch());\n boundsList.addAll(this.getUnmatch());\n Collections.sort(boundsList); \n List<String> annotatedStrings = new LinkedList<>();\n for(Bounds bounds : boundsList){\n annotatedStrings.add(this.getString().substring(bounds.start, bounds.end));\n}\n return annotatedStrings;\n }\n \n \n public void mergeUnmatchesBounds(){\n this.unmatch = Bounds.mergeBounds(this.unmatch);\n }\n \n}",
"public interface Objective {\n\n public void setup(Context context);\n public double[] fitness(Node individual);\n TreeEvaluator getTreeEvaluator();\n Objective cloneObjective();\n}",
"public class FinalSolution extends Solution{\n\n public FinalSolution() {\n }\n\n public FinalSolution(Ranking individual) {\n super(individual);\n this.solutionJS = getDescriptionJavascript(individual.getTree());\n }\n \n private String getDescriptionJavascript(Node node){\n StringBuilder sb = new StringBuilder();\n node.describe(sb, new DescriptionContext(), Node.RegexFlavour.JS);\n return sb.toString();\n }\n\n /**\n * Create a FinalSolution for the Java regex (String) solution parameter.\n * Javascript version is not automatically generate, this needs initialization\n * with a Node individual.\n * @param solution\n */\n public FinalSolution(String solution) {\n super(solution);\n }\n\n public FinalSolution(String solution, double[] fitness) {\n super(solution, fitness);\n }\n\n private String solutionJS;\n private Map<String,Double> trainingPerformances = new HashMap<>();\n private Map<String,Double> validationPerformances = new HashMap<>();\n private Map<String,Double> learningPerformances = new HashMap<>();\n\n public Map<String, Double> getTrainingPerformances() {\n return trainingPerformances;\n }\n\n public void setTrainingPerformances(Map<String, Double> trainingPerformances) {\n this.trainingPerformances = trainingPerformances;\n }\n\n public Map<String, Double> getValidationPerformances() {\n return validationPerformances;\n }\n\n public void setValidationPerformances(Map<String, Double> validationPerformances) {\n this.validationPerformances = validationPerformances;\n }\n\n public Map<String, Double> getLearningPerformances() {\n return learningPerformances;\n }\n\n public void setLearningPerformances(Map<String, Double> learningPerformances) {\n this.learningPerformances = learningPerformances;\n }\n\n public String getSolutionJS() {\n return solutionJS;\n }\n \n}",
"public class Constant extends AbstractNode implements Leaf {\n\n private Node parent;\n protected String value;\n private boolean charClass;\n Set<String> allowedClasses = new HashSet<String>(Arrays.asList(\"\\\\w\", \"\\\\d\", \".\", \"\\\\b\", \"\\\\s\"));\n private boolean escaped;\n\n public Constant(String value) {\n this.value = value;\n charClass = allowedClasses.contains(value);\n escaped = value.startsWith(\"\\\\\");\n }\n\n @Override\n public int getMinChildrenCount() {\n return 0;\n }\n\n @Override\n public int getMaxChildrenCount() {\n return 0;\n }\n\n @Override\n public void describe(StringBuilder builder, DescriptionContext context, RegexFlavour flavour) {\n builder.append(value);\n }\n\n @Override\n public Leaf cloneTree() {\n Constant clone = new Constant(value);\n return clone;\n }\n\n @Override\n public Node getParent() {\n return parent;\n }\n\n @Override\n public void setParent(Node parent) {\n this.parent = parent;\n }\n\n @Override\n public List<Node> getChildrens() {\n return Collections.<Node>emptyList();\n }\n\n @Override\n public boolean isValid() {\n return true;\n }\n\n @Override\n public String toString() {\n return value;\n }\n\n @Override\n public boolean isCharacterClass() {\n return charClass;\n }\n\n @Override\n public boolean isEscaped() {\n return escaped;\n }\n\n @Override\n public int hashCode() {\n int hash = 7;\n hash = 73 * hash + Objects.hashCode(this.value);\n return hash;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (obj == null) {\n return false;\n }\n if (getClass() != obj.getClass()) {\n return false;\n }\n final Constant other = (Constant) obj;\n if (!Objects.equals(this.value, other.value)) {\n return false;\n }\n return true;\n }\n \n \n}",
"public interface Node {\n \n Node cloneTree();\n\n Node getParent();\n void setParent(Node parent);\n \n int getMinChildrenCount();\n int getMaxChildrenCount();\n List<Node> getChildrens();\n long getId();\n \n void describe(StringBuilder builder);\n void describe(StringBuilder builder, DescriptionContext context, RegexFlavour flavour);\n boolean isValid();\n\n public enum RegexFlavour {\n JAVA,\n CSHARP,\n JS\n }\n public boolean isCharacterClass();\n public boolean isEscaped();\n}"
] | import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import it.units.inginf.male.configuration.Configuration;
import it.units.inginf.male.utils.BasicStats;
import it.units.inginf.male.evaluators.TreeEvaluationException;
import it.units.inginf.male.evaluators.TreeEvaluator;
import it.units.inginf.male.inputs.Context;
import it.units.inginf.male.inputs.DataSet;
import it.units.inginf.male.inputs.DataSet.Bounds;
import it.units.inginf.male.inputs.DataSet.Example;
import it.units.inginf.male.objective.Objective;
import it.units.inginf.male.outputs.FinalSolution;
import it.units.inginf.male.tree.Constant;
import it.units.inginf.male.tree.Node;
import java.util.ArrayList; | /*
* Copyright (C) 2015 Machine Learning Lab - University of Trieste,
* Italy (http://machinelearning.inginf.units.it/)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package it.units.inginf.male.objective.performance;
/**
* This is not a fitness, but returns individual performances like in a
* mutli-objective fitness style. fitness[0] = precision fitness[1] = recall
* fitness[2] = charPrecision fitness[3] = charRecall fitness[4] = charAccuracy
* fitness[5] = match fmeasure
*
* @author MaleLabTs
*/
public class PerformacesObjective implements Objective {
private Context context;
//private DataSet dataSetView;
//private int numberCharsInMatches = 0;
@Override
public void setup(Context context) {
this.context = context;
//this.dataSetView = this.context.getCurrentDataSet();
//this.dataSetView.populateMatchesStrings();
}
@Override
public double[] fitness(Node individual) {
DataSet dataSetView = this.context.getCurrentDataSet();
TreeEvaluator evaluator = context.getConfiguration().getEvaluator();
double[] fitness = new double[12];
List<List<Bounds>> evaluate;
try {
evaluate = evaluator.evaluate(individual, context);
} catch (TreeEvaluationException ex) {
Logger.getLogger(PerformacesObjective.class.getName()).log(Level.SEVERE, null, ex);
Arrays.fill(fitness, Double.POSITIVE_INFINITY);
return fitness;
}
//match stats makes sense only for tp e fp values... we cannot use instance statistic formulas other than precision | BasicStats statsOverall = new BasicStats(); | 1 |
plusonelabs/calendar-widget | app/src/androidTest/java/org/andstatus/todoagenda/PastDueHeaderWithTasksTest.java | [
"public class QueryResultsStorage {\n\n private static final String TAG = QueryResultsStorage.class.getSimpleName();\n private static final String KEY_RESULTS_VERSION = \"resultsVersion\";\n private static final int RESULTS_VERSION = 3;\n private static final String KEY_RESULTS = \"results\";\n public static final String KEY_SETTINGS = \"settings\";\n\n private static volatile QueryResultsStorage theStorage = null;\n private static volatile int widgetIdResultsToStore = 0;\n\n private final List<QueryResult> results = new CopyOnWriteArrayList<>();\n private AtomicReference<DateTime> executedAt = new AtomicReference<>(null);\n\n public static boolean store(QueryResult result) {\n QueryResultsStorage storage = theStorage;\n if (storage != null) {\n storage.addResult(result);\n return (storage == theStorage);\n }\n return false;\n }\n\n public static void shareEventsForDebugging(Context context, int widgetId) {\n final String method = \"shareEventsForDebugging\";\n Log.i(TAG, method + \" started\");\n InstanceSettings settings = AllSettings.instanceFromId(context, widgetId);\n QueryResultsStorage storage = settings.isLiveMode() || !settings.hasResults()\n ? getNewResults(context, widgetId)\n : settings.getResultsStorage();\n String results = storage.toJsonString(context, widgetId);\n if (TextUtils.isEmpty(results)) {\n Log.i(TAG, method + \"; Nothing to share\");\n } else {\n String fileName = (settings.getWidgetInstanceName() + \"-\" + context.getText(R.string.app_name))\n .replaceAll(\"\\\\W+\", \"-\") +\n \"-shareEvents-\" + formatLogDateTime(System.currentTimeMillis()) +\n \".json\";\n Intent intent = new Intent(Intent.ACTION_SEND);\n intent.setType(\"application/json\");\n intent.putExtra(Intent.EXTRA_SUBJECT, fileName);\n intent.putExtra(Intent.EXTRA_TEXT, results);\n context.startActivity(\n Intent.createChooser(intent, context.getText(R.string.share_events_for_debugging_title)));\n Log.i(TAG, method + \"; Shared \" + results);\n }\n }\n\n public static QueryResultsStorage getNewResults(Context context, int widgetId) {\n QueryResultsStorage resultsStorage;\n try {\n setNeedToStoreResults(true, widgetId);\n RemoteViewsFactory factory = RemoteViewsFactory.factories.computeIfAbsent(widgetId,\n id -> new RemoteViewsFactory(context, id, false));\n factory.onDataSetChanged();\n resultsStorage = QueryResultsStorage.theStorage;\n } finally {\n setNeedToStoreResults(false, widgetId);\n }\n return resultsStorage;\n }\n\n public static boolean getNeedToStoreResults(int widgetId) {\n return theStorage != null && (widgetId == 0 || widgetId == widgetIdResultsToStore);\n }\n\n public static void setNeedToStoreResults(boolean needToStoreResults, int widgetId) {\n widgetIdResultsToStore = widgetId;\n if (needToStoreResults) {\n theStorage = new QueryResultsStorage();\n } else {\n theStorage = null;\n }\n }\n\n public static QueryResultsStorage getStorage() {\n return theStorage;\n }\n\n public List<QueryResult> getResults() {\n return results;\n }\n\n public void addResults(QueryResultsStorage newResults) {\n for (QueryResult result : newResults.getResults()) {\n addResult(result);\n }\n setExecutedAt(newResults.getExecutedAt());\n }\n\n public void addResult(QueryResult result) {\n executedAt.compareAndSet(null, result.getExecutedAt());\n results.add(result);\n }\n\n public List<QueryResult> getResults(EventProviderType type, int widgetId) {\n return results.stream().filter(result -> type == EventProviderType.EMPTY || result.providerType == type)\n .filter(result -> widgetId == 0 || result.getWidgetId() == widgetId)\n .collect(Collectors.toList());\n }\n\n public List<EventProviderType> getProviderTypes(int widgetId) {\n return results.stream()\n .filter(result -> widgetId == 0 || result.getWidgetId() == widgetId)\n .map(result -> result.providerType)\n .distinct()\n .collect(Collectors.toList());\n }\n\n public Optional<QueryResult> findLast(EventProviderType type) {\n for (int index = results.size() - 1; index >=0; index--) {\n QueryResult result = results.get(index);\n if (type != EventProviderType.EMPTY && result.providerType != type) continue;\n\n return Optional.of(result);\n }\n return Optional.empty();\n }\n\n public Optional<QueryResult> getResult(EventProviderType type, int index) {\n int foundIndex = -1;\n for (QueryResult result: results) {\n if (type != EventProviderType.EMPTY && result.providerType != type) continue;\n\n foundIndex++;\n if (foundIndex == index) return Optional.of(result);\n }\n return Optional.empty();\n }\n\n private String toJsonString(Context context, int widgetId) {\n try {\n return toJson(context, widgetId, true).toString(2);\n } catch (JSONException e) {\n return \"Error while formatting data \" + e;\n }\n }\n\n public JSONObject toJson(Context context, int widgetId, boolean withSettings) throws JSONException {\n JSONArray resultsArray = new JSONArray();\n for (QueryResult result : results) {\n if (result.getWidgetId() == widgetId) {\n resultsArray.put(result.toJson());\n }\n }\n WidgetData widgetData = context == null || widgetId == 0\n ? WidgetData.EMPTY\n : WidgetData.fromSettings(context, withSettings ? AllSettings.instanceFromId(context, widgetId) : null);\n\n JSONObject json = widgetData.toJson();\n json.put(KEY_RESULTS_VERSION, RESULTS_VERSION);\n json.put(KEY_RESULTS, resultsArray);\n return json;\n }\n\n public static QueryResultsStorage fromJson(int widgetId, JSONObject jsonStorage) {\n QueryResultsStorage resultsStorage = new QueryResultsStorage();\n if (jsonStorage.has(KEY_RESULTS)) {\n try {\n JSONArray jsonResults = jsonStorage.getJSONArray(KEY_RESULTS);\n for (int ind = 0; ind < jsonResults.length(); ind++) {\n resultsStorage.addResult(QueryResult.fromJson(jsonResults.getJSONObject(ind), widgetId));\n }\n } catch (Exception e) {\n Log.w(TAG, \"Error reading results\", e);\n }\n }\n return resultsStorage;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n\n QueryResultsStorage results = (QueryResultsStorage) o;\n\n if (this.results.size() != results.results.size()) {\n return false;\n }\n for (int ind = 0; ind < this.results.size(); ind++) {\n if (!this.results.get(ind).equals(results.results.get(ind))) {\n return false;\n }\n }\n return true;\n }\n\n @Override\n public int hashCode() {\n int result = 0;\n for (int ind = 0; ind < results.size(); ind++) {\n result = 31 * result + results.get(ind).hashCode();\n }\n return result;\n }\n\n @Override\n public String toString() {\n return TAG + \":\" + results;\n }\n\n public void clear() {\n results.clear();\n executedAt.set(null);\n }\n\n public void setExecutedAt(DateTime date) {\n executedAt.set(date);\n }\n\n public DateTime getExecutedAt() {\n return executedAt.get();\n }\n}",
"public class MyClock {\n public static final DateTime DATETIME_MIN = new DateTime(0, DateTimeZone.UTC).withTimeAtStartOfDay();\n public static final DateTime DATETIME_MAX = new DateTime(5000, 1, 1, 0, 0, DateTimeZone.UTC).withTimeAtStartOfDay();\n\n private volatile SnapshotMode snapshotMode = SnapshotMode.defaultValue;\n private volatile DateTime snapshotDate = null;\n private volatile DateTime snapshotDateSetAt = null;\n private volatile String lockedTimeZoneId = \"\";\n private volatile DateTimeZone zone;\n\n public MyClock() {\n zone = DateTimeZone.getDefault();\n }\n\n public void setSnapshotMode(SnapshotMode snapshotMode) {\n this.snapshotMode = snapshotMode;\n updateZone();\n }\n\n public void setSnapshotDate(DateTime snapshotDate) {\n this.snapshotDate = snapshotDate;\n snapshotDateSetAt = DateTime.now();\n updateZone();\n }\n\n public void setLockedTimeZoneId(String timeZoneId) {\n lockedTimeZoneId = DateUtil.validatedTimeZoneId(timeZoneId);\n updateZone();\n }\n\n private void updateZone() {\n if (snapshotMode == SnapshotMode.SNAPSHOT_TIME && snapshotDate != null) {\n zone = snapshotDate.getZone();\n } else if (StringUtil.nonEmpty(lockedTimeZoneId)) {\n zone = DateTimeZone.forID(lockedTimeZoneId);\n } else {\n zone = DateTimeZone.getDefault();\n }\n }\n\n public String getLockedTimeZoneId() {\n return lockedTimeZoneId;\n }\n\n public SnapshotMode getSnapshotMode() {\n return snapshotMode;\n }\n\n /**\n * Usually returns real \"now\", but may be #setNow to some other time for testing purposes\n */\n public DateTime now() {\n return now(zone);\n }\n\n public DateTime now(DateTimeZone zone) {\n DateTime snapshotDate = this.snapshotDate;\n if (getSnapshotMode() == SnapshotMode.SNAPSHOT_TIME && snapshotDate != null) {\n return PermissionsUtil.isTestMode()\n ? getTimeMachineDate(zone)\n : snapshotDate.withZone(zone);\n } else {\n return DateTime.now(zone);\n }\n }\n\n private DateTime getTimeMachineDate(DateTimeZone zone) {\n DateTime nowSetAt = null;\n DateTime now = null;\n do {\n nowSetAt = snapshotDateSetAt;\n now = snapshotDate;\n } while (nowSetAt != snapshotDateSetAt); // Ensure concurrent consistency\n\n if (now == null) {\n return DateTime.now(zone);\n } else {\n long diffL = DateTime.now().getMillis() - nowSetAt.getMillis();\n int diff = 0;\n if (diffL > 0 && diffL < Integer.MAX_VALUE) {\n diff = (int) diffL;\n }\n return new DateTime(now, zone).plusMillis(diff);\n }\n }\n\n public DateTimeZone getZone() {\n return zone;\n }\n\n public boolean isToday(@Nullable DateTime date) {\n return isDateDefined(date) && !isBeforeToday(date) && date.isBefore(now(date.getZone()).plusDays(1).withTimeAtStartOfDay());\n }\n\n public boolean isBeforeToday(@Nullable DateTime date) {\n return isDateDefined(date) && date.isBefore(now(date.getZone()).withTimeAtStartOfDay());\n }\n\n public boolean isAfterToday(@Nullable DateTime date) {\n return isDateDefined(date) && !date.isBefore(now(date.getZone()).withTimeAtStartOfDay().plusDays(1));\n }\n\n public boolean isBeforeNow(@Nullable DateTime date) {\n return isDateDefined(date) && date.isBefore(now(date.getZone()));\n }\n\n public int getNumberOfDaysTo(DateTime date) {\n return Days.daysBetween(\n now(date.getZone()).withTimeAtStartOfDay(),\n date.withTimeAtStartOfDay())\n .getDays();\n }\n\n public int getNumberOfMinutesTo(DateTime date) {\n return Minutes.minutesBetween(now(date.getZone()), date)\n .getMinutes();\n }\n\n public DateTime startOfTomorrow() {\n return startOfNextDay(now(zone));\n }\n\n public static DateTime startOfNextDay(DateTime date) {\n return date.plusDays(1).withTimeAtStartOfDay();\n }\n\n public static boolean isDateDefined(@Nullable DateTime dateTime) {\n return dateTime != null && dateTime.isAfter(DATETIME_MIN) && dateTime.isBefore(DATETIME_MAX);\n }\n}",
"public class CalendarEntry extends WidgetEntry<CalendarEntry> {\n\n private static final String ARROW = \"→\";\n private static final String SPACE = \" \";\n static final String SPACE_DASH_SPACE = \" - \";\n\n private boolean allDay;\n private CalendarEvent event;\n\n public static CalendarEntry fromEvent(InstanceSettings settings, CalendarEvent event, DateTime entryDate) {\n CalendarEntry entry = new CalendarEntry(settings, entryDate, event.getEndDate());\n entry.allDay = event.isAllDay();\n entry.event = event;\n return entry;\n }\n\n private CalendarEntry(InstanceSettings settings, DateTime entryDate, DateTime endDate) {\n super(settings, WidgetEntry.getEntryPosition(settings, entryDate, endDate), entryDate, endDate);\n }\n\n @Override\n public String getTitle() {\n String title = event.getTitle();\n if (TextUtils.isEmpty(title)) {\n title = getContext().getResources().getString(R.string.no_title);\n }\n return title;\n }\n\n public int getColor() {\n return event.getColor();\n }\n\n public boolean isAllDay() {\n return allDay;\n }\n\n @Override\n public String getLocation() {\n return event.getLocation();\n }\n\n public boolean isAlarmActive() {\n return event.isAlarmActive();\n }\n\n public boolean isRecurring() {\n return event.isRecurring();\n }\n\n public boolean isPartOfMultiDayEvent() {\n return getEvent().isPartOfMultiDayEvent();\n }\n\n public boolean isStartOfMultiDayEvent() {\n return isPartOfMultiDayEvent() && !getEvent().getStartDate().isBefore(entryDate);\n }\n\n public boolean isEndOfMultiDayEvent() {\n return isPartOfMultiDayEvent() && isLastEntryOfEvent();\n }\n\n public boolean spansOneFullDay() {\n return entryDate.plusDays(1).isEqual(event.getEndDate());\n }\n\n public CalendarEvent getEvent() {\n return event;\n }\n\n @Override\n public String getEventTimeString() {\n return hideEventTime() ? \"\" : createTimeSpanString();\n }\n\n private boolean hideEventTime() {\n return spansOneFullDay() && !(isStartOfMultiDayEvent() || isEndOfMultiDayEvent()) ||\n isAllDay();\n }\n\n private String createTimeSpanString() {\n String startStr;\n String endStr;\n String separator = SPACE_DASH_SPACE;\n if (!isDateDefined(entryDate) || (isPartOfMultiDayEvent() && DateUtil.isMidnight(entryDate)\n && !isStartOfMultiDayEvent())) {\n startStr = ARROW;\n separator = SPACE;\n } else {\n startStr = DateUtil.formatTime(this::getSettings, entryDate);\n }\n if (getSettings().getShowEndTime()) {\n if (!isDateDefined(event.getEndDate()) || (isPartOfMultiDayEvent() && !isLastEntryOfEvent())) {\n endStr = ARROW;\n separator = SPACE;\n } else {\n endStr = DateUtil.formatTime(this::getSettings, event.getEndDate());\n }\n } else {\n separator = DateUtil.EMPTY_STRING;\n endStr = DateUtil.EMPTY_STRING;\n }\n\n if (startStr.equals(endStr)) {\n return startStr;\n }\n\n return startStr + separator + endStr;\n }\n\n public Context getContext() {\n return event.getContext();\n }\n\n public InstanceSettings getSettings() {\n return event.getSettings();\n }\n\n @Override\n public OrderedEventSource getSource() {\n return event.getEventSource();\n }\n\n @Override\n public String toString() {\n return super.toString() + \" CalendarEntry [\"\n + \"allDay=\" + allDay\n + \", time=\" + getEventTimeString()\n + \", location=\" + getLocationString()\n + \", event=\" + event\n + \"]\";\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) {\n return true;\n }\n if (o == null || getClass() != o.getClass()) {\n return false;\n }\n CalendarEntry that = (CalendarEntry) o;\n return event.equals(that.event) && entryDate.equals(that.entryDate);\n }\n\n @Override\n public int hashCode() {\n int result = super.hashCode();\n result += 31 * event.hashCode();\n result += 31 * entryDate.hashCode();\n return result;\n }\n}",
"public class LastEntry extends WidgetEntry<LastEntry> {\n\n public static LastEntry forEmptyList(InstanceSettings settings) {\n LastEntry.LastEntryType entryType = PermissionsUtil.arePermissionsGranted(settings.getContext())\n ? EMPTY\n : NO_PERMISSIONS;\n return new LastEntry(settings, entryType, settings.clock().now());\n }\n\n public static void addLast(InstanceSettings settings, List<WidgetEntry> widgetEntries) {\n LastEntry entry = widgetEntries.isEmpty()\n ? LastEntry.forEmptyList(settings)\n : new LastEntry(settings, LastEntryType.LAST, widgetEntries.get(widgetEntries.size() - 1).entryDate);\n widgetEntries.add(entry);\n }\n\n public enum LastEntryType {\n NOT_LOADED(R.layout.item_not_loaded),\n NO_PERMISSIONS(R.layout.item_no_permissions),\n EMPTY(R.layout.item_empty_list),\n LAST(R.layout.item_last);\n\n final int layoutId;\n\n LastEntryType(int layoutId) {\n this.layoutId = layoutId;\n }\n }\n\n public final LastEntryType type;\n\n public LastEntry(InstanceSettings settings, LastEntryType type, DateTime date) {\n super(settings, LIST_FOOTER, date, null);\n this.type = type;\n }\n}",
"public class TaskEntry extends WidgetEntry<TaskEntry> {\n private TaskEvent event;\n\n public static TaskEntry fromEvent(InstanceSettings settings, TaskEvent event) {\n WidgetEntryPosition entryPosition = getEntryPosition(settings, event);\n TaskEntry entry = new TaskEntry(settings, entryPosition, getEntryDate(settings, entryPosition, event), event.getDueDate());\n entry.event = event;\n return entry;\n }\n\n private TaskEntry(InstanceSettings settings, WidgetEntryPosition entryPosition, DateTime entryDate, DateTime endDate) {\n super(settings, entryPosition, entryDate, endDate);\n }\n\n /** See https://github.com/plusonelabs/calendar-widget/issues/356#issuecomment-559910887 **/\n private static WidgetEntryPosition getEntryPosition(InstanceSettings settings, TaskEvent event) {\n if (!event.hasStartDate() && !event.hasDueDate()) return settings.getTaskWithoutDates().widgetEntryPosition;\n\n if (event.hasDueDate() && settings.clock().isBeforeToday(event.getDueDate())) {\n return settings.getShowPastEventsUnderOneHeader() ? PAST_AND_DUE : ENTRY_DATE;\n }\n\n DateTime mainDate = mainDate(settings, event);\n if (mainDate != null) {\n if (mainDate.isAfter(settings.getEndOfTimeRange())) return END_OF_LIST;\n }\n\n DateTime otherDate = otherDate(settings, event);\n\n if (settings.getTaskScheduling() == TaskScheduling.DATE_DUE) {\n if (!event.hasDueDate()) {\n if (settings.clock().isBeforeToday(event.getStartDate())) return START_OF_TODAY;\n if (event.getStartDate().isAfter(settings.getEndOfTimeRange())) return END_OF_LIST;\n }\n } else {\n if (!event.hasStartDate() || settings.clock().isBeforeToday(event.getStartDate())) {\n return START_OF_TODAY;\n }\n }\n return WidgetEntry.getEntryPosition(settings, mainDate, otherDate);\n }\n\n private static DateTime mainDate(InstanceSettings settings, TaskEvent event) {\n return settings.getTaskScheduling() == TaskScheduling.DATE_DUE\n ? event.getDueDate()\n : event.getStartDate();\n }\n\n private static DateTime otherDate(InstanceSettings settings, TaskEvent event) {\n return settings.getTaskScheduling() == TaskScheduling.DATE_DUE\n ? event.getStartDate()\n : event.getDueDate();\n }\n\n private static DateTime getEntryDate(InstanceSettings settings, WidgetEntryPosition entryPosition, TaskEvent event) {\n switch (entryPosition) {\n case END_OF_TODAY:\n case END_OF_LIST:\n case END_OF_LIST_HEADER:\n case LIST_FOOTER:\n case HIDDEN:\n return getEntryDateOrElse(settings, event, MyClock.DATETIME_MAX);\n default:\n return getEntryDateOrElse(settings, event, MyClock.DATETIME_MIN);\n }\n }\n\n private static DateTime getEntryDateOrElse(InstanceSettings settings, TaskEvent event, DateTime defaultDate) {\n if (settings.getTaskScheduling() == TaskScheduling.DATE_DUE) {\n return event.hasDueDate()\n ? event.getDueDate()\n : (event.hasStartDate() ? event.getStartDate() : defaultDate);\n } else {\n if (event.hasStartDate()) {\n if (settings.clock().isBeforeToday(event.getStartDate())) {\n return event.hasDueDate() ? event.getDueDate() : defaultDate;\n }\n return event.getStartDate();\n } else {\n return event.hasDueDate() ? event.getDueDate() : defaultDate;\n }\n }\n }\n\n @Override\n public OrderedEventSource getSource() {\n return event.getEventSource();\n }\n\n @Override\n public String getTitle() {\n return event.getTitle();\n }\n\n public TaskEvent getEvent() {\n return event;\n }\n\n @Override\n public String toString() {\n return super.toString() + \" TaskEntry [title='\" + event.getTitle() + \"', startDate=\" + event.getStartDate() +\n \", dueDate=\" + event.getDueDate() + \"]\";\n }\n}",
"public enum WidgetEntryPosition {\n PAST_AND_DUE_HEADER(\"PastAndDueHeader\",false, 1, 1),\n PAST_AND_DUE(\"PastAndDue\", false, 2, 2),\n DAY_HEADER(\"DayHeader\", true, 3, 1),\n START_OF_TODAY(\"StartOfToday\", false, 3, 2),\n START_OF_DAY(\"StartOfDay\", true, 3, 3),\n ENTRY_DATE(\"EntryDate\", true, 3, 4),\n END_OF_TODAY(\"EndOfToday\", false, 3, 5),\n END_OF_LIST_HEADER(\"EndOfListHeader\", false, 5, 1),\n END_OF_LIST(\"EndOfList\", false, 5, 1),\n LIST_FOOTER(\"ListFooter\", false, 6, 1),\n HIDDEN(\"Hidden\", false, 9, 9),\n UNKNOWN(\"Unknown\", false, 9, 9);\n\n public static WidgetEntryPosition defaultValue = UNKNOWN;\n\n public final String value;\n final boolean entryDateIsRequired;\n final int globalOrder;\n final int sameDayOrder;\n\n WidgetEntryPosition(String value, boolean dateIsRequired, int globalOrder, int sameDayOrder) {\n this.value = value;\n this.entryDateIsRequired = dateIsRequired;\n this.globalOrder = globalOrder;\n this.sameDayOrder = sameDayOrder;\n }\n\n public static WidgetEntryPosition fromValue(String value) {\n for (WidgetEntryPosition item : WidgetEntryPosition.values()) {\n if (item.value.equals(value)) {\n return item;\n }\n }\n return defaultValue;\n }\n}"
] | import org.andstatus.todoagenda.provider.QueryResultsStorage;
import org.andstatus.todoagenda.util.MyClock;
import org.andstatus.todoagenda.widget.CalendarEntry;
import org.andstatus.todoagenda.widget.LastEntry;
import org.andstatus.todoagenda.widget.TaskEntry;
import org.andstatus.todoagenda.widget.WidgetEntryPosition;
import org.json.JSONException;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.assertEquals; | package org.andstatus.todoagenda;
/**
* @author [email protected]
*/
public class PastDueHeaderWithTasksTest extends BaseWidgetTest {
/**
* https://github.com/plusonelabs/calendar-widget/issues/205
*/
@Test
public void testPastDueHeaderWithTasks() throws IOException, JSONException {
final String method = "testPastDueHeaderWithTasks";
QueryResultsStorage inputs = provider.loadResultsAndSettings(
org.andstatus.todoagenda.tests.R.raw.past_due_header_with_tasks);
provider.addResults(inputs);
playResults(method);
assertEquals("Past and Due header", MyClock.DATETIME_MIN, getFactory().getWidgetEntries().get(0).entryDate);
assertEquals(WidgetEntryPosition.PAST_AND_DUE_HEADER, getFactory().getWidgetEntries().get(0).entryPosition);
assertEquals("Past Calendar Entry", CalendarEntry.class, getFactory().getWidgetEntries().get(1).getClass()); | assertEquals("Due task Entry", TaskEntry.class, getFactory().getWidgetEntries().get(2).getClass()); | 4 |
algohub/judge-engine | src/test/java/org/algohub/engine/codegenerator/CppCodeGeneratorTest.java | [
"public class CppJudge implements JudgeInterface {\n /**\n * {@inheritDoc}.\n */\n public JudgeResult judge(final Function function, final Problem.TestCase[] testCases,\n final String userCode) {\n return JudgeInterface.judge(function, testCases, userCode, LanguageType.CPLUSPLUS,\n CppJudge::createFriendlyMessage);\n }\n\n private static String createFriendlyMessage(final String errorMessage) {\n if(errorMessage == null || errorMessage.isEmpty()) return null;\n\n final StringBuilder sb = new StringBuilder();\n final String[] lines = errorMessage.split(\"\\n\");\n final String CPP_SOLUTION_FILE = \"solution.\" + LanguageType.CPLUSPLUS.getFileSuffix();\n final Pattern pattern = Pattern.compile(\"^solution\\\\.cpp:(\\\\d+):\\\\d+:\");\n\n for(int i = 0; i < lines.length; i++) {\n Matcher matcher = pattern.matcher(lines[i]);\n if(matcher.find()) {\n String lineNo = matcher.group(1);\n sb.append(\"Line \" + lines[i].substring(CPP_SOLUTION_FILE.length() + 1)).append('\\n');\n sb.append(lines[i+1]).append('\\n');\n sb.append(lines[i+2]).append('\\n');\n i += 2;\n } else if(lines[i].startsWith(\"main.cpp: In function\") && lines[i+1].contains(\"was not declared in this scope\") ) {\n int pos = lines[i+1].indexOf(\"error:\");\n sb.append(lines[i+1].substring(pos)).append('\\n');\n i+= 1;\n }\n }\n return sb.toString();\n }\n}",
"public enum StatusCode {\n PENDING(0),\n RUNNING(1),\n\n COMPILE_ERROR(2),\n RUNTIME_ERROR(3),\n\n ACCEPTED(4),\n WRONG_ANSWER(5),\n\n TIME_LIMIT_EXCEEDED(6),\n MEMORY_LIMIT_EXCEEDED(7),\n OUTPUT_LIMIT_EXCEEDED(8),\n\n RESTRICTED_CALL(9),\n TOO_LONG_CODE(10);\n\n\n private final int code;\n\n StatusCode(int code) {\n this.code = code;\n }\n\n @JsonCreator\n public static StatusCode fromInt(int code) {\n for (final StatusCode v : StatusCode.values()) {\n if (code == v.code) {\n return v;\n }\n }\n\n throw new IllegalArgumentException(\"Unrecognized status code: \" + code);\n }\n\n @JsonValue\n public int toInt() {\n return this.code;\n }\n}",
"@SuppressWarnings({\"PMD.BeanMembersShouldSerialize\", \"PMD.UnusedPrivateField\", \"PMD.SingularField\",\n \"PMD.ArrayIsStoredDirectly\"}) @JsonIgnoreProperties(ignoreUnknown = true) public\nclass Function {\n\n /**\n * Function name.\n */\n private final String name;\n /**\n * Return metadata.\n */\n @JsonProperty(\"return\") private final Return return_;\n /**\n * Parameters' metadata.\n */\n private final Parameter[] parameters;\n\n /**\n * Since this class is immutable, need to provide a method for Jackson.\n */\n @JsonCreator public Function(@JsonProperty(\"name\") final String name,\n @JsonProperty(\"return\") final Return return_,\n @JsonProperty(\"parameters\") final Parameter[] parameters) {\n this.name = name;\n this.return_ = return_;\n this.parameters = parameters;\n }\n\n\n /**\n * Return type.\n */\n @JsonIgnoreProperties(ignoreUnknown = true) public static class Return {\n /**\n * Return data type.\n */\n private final TypeNode type;\n /**\n * Comment of returned value.\n */\n private final String comment;\n\n /**\n * Since this class is immutable, need to provide a method for Jackson.\n */\n @JsonCreator public Return(@JsonProperty(\"type\") final TypeNode type,\n @JsonProperty(\"comment\") final String comment) {\n this.type = type;\n this.comment = comment;\n }\n\n public TypeNode getType() {\n return type;\n }\n\n public String getComment() {\n return comment;\n }\n }\n\n\n /**\n * Function parameters' metadata.\n */\n @JsonIgnoreProperties(ignoreUnknown = true) public static class Parameter {\n /**\n * Parameter name.\n */\n private final String name;\n /**\n * Parameter type.\n */\n private final TypeNode type;\n /**\n * Parameter comment.\n */\n private final String comment;\n\n /**\n * Since this class is immutable, need to provide a method for Jackson.\n */\n @JsonCreator public Parameter(@JsonProperty(\"name\") final String name,\n @JsonProperty(\"type\") final TypeNode type, @JsonProperty(\"comment\") final String comment) {\n this.name = name;\n this.type = type;\n this.comment = comment;\n }\n\n public String getName() {\n return name;\n }\n\n public TypeNode getType() {\n return type;\n }\n\n public String getComment() {\n return comment;\n }\n }\n\n public String getName() {\n return name;\n }\n\n public Return getReturn_() {\n return return_;\n }\n\n public Parameter[] getParameters() {\n return parameters;\n }\n}",
"@SuppressWarnings({\"PMD.BeanMembersShouldSerialize\", \"PMD.UnusedPrivateField\", \"PMD.SingularField\",\n \"PMD.ArrayIsStoredDirectly\", \"PMD.CommentRequired\"})\n@JsonIgnoreProperties(ignoreUnknown = true)\npublic class Problem {\n @JsonProperty(required = true) private final Map<String, String> title;\n @JsonProperty(required = true) private final Map<String, String> description;\n @JsonProperty(required = true) private final Function function;\n @JsonProperty(value = \"test_cases\", required = true) private final TestCase[] testCases;\n private final String category;\n private final String[] tags;\n private final int difficulty;\n @JsonProperty(\"time_limit\") private final int timeLimit;\n @JsonProperty(\"memory_limit\") private final int memoryLimit;\n @JsonProperty(\"related_problems\") private final String[] relatedProblems;\n private final Map<String, String> author;\n @JsonProperty(\"test_cases_generator\") private final String testCasesGenerator;\n\n /**\n * Since some fields are immutable, need to provide a method for Jackson.\n */\n @SuppressWarnings({\"PMD.ExcessiveParameterList\", \"PMD.ShortVariable\"}) @JsonCreator\n public Problem(\n @JsonProperty(value = \"title\", required = true) final Map<String, String> title,\n @JsonProperty(value = \"description\", required = true) final Map<String, String> description,\n @JsonProperty(value = \"function\", required = true) final Function function,\n @JsonProperty(value = \"test_cases\", required = true) final TestCase[] testCases,\n @JsonProperty(\"category\") final String category,\n @JsonProperty(\"tags\") final String[] tags,\n @JsonProperty(\"difficulty\") final int difficulty,\n @JsonProperty(\"time_limit\") final int timeLimit,\n @JsonProperty(\"memory_limit\") final int memoryLimit,\n @JsonProperty(\"related_problems\") final String[] relatedProblems,\n @JsonProperty(\"author\") final Map<String, String> author,\n @JsonProperty(\"test_cases_generator\") final String testCasesGenerator) {\n this.title = title;\n this.description = description;\n this.category = category;\n this.tags = tags;\n this.difficulty = difficulty;\n this.timeLimit = timeLimit;\n this.memoryLimit = memoryLimit;\n this.relatedProblems = relatedProblems;\n this.function = function;\n this.author = author;\n this.testCases = testCases;\n this.testCasesGenerator = testCasesGenerator;\n }\n\n /**\n * Test cases.\n */\n @JsonIgnoreProperties(ignoreUnknown = true) public static class TestCase {\n @JsonProperty(required = true) private final ArrayNode input;\n @JsonProperty(required = true) private final JsonNode output;\n\n @JsonCreator public TestCase(\n @JsonProperty(value = \"input\", required = true) final ArrayNode input,\n @JsonProperty(value = \"output\", required = true) final JsonNode output) {\n this.input = input;\n this.output = output;\n }\n\n public ArrayNode getInput() {\n return input;\n }\n\n public JsonNode getOutput() {\n return output;\n }\n }\n\n public String getId() {\n return this.title.get(\"en\").replaceAll(\"\\\\s+\", \"-\").replaceAll(\"['\\\\(\\\\),]+\", \"\").toLowerCase();\n }\n\n public Map<String, String> getTitle() {\n return title;\n }\n\n public Map<String, String> getDescription() {\n return description;\n }\n\n public String getCategory() {\n return category;\n }\n\n public String[] getTags() {\n return tags;\n }\n\n public int getDifficulty() {\n return difficulty;\n }\n\n public int getTimeLimit() {\n return timeLimit;\n }\n\n public int getMemoryLimit() {\n return memoryLimit;\n }\n\n public String[] getRelatedProblems() {\n return relatedProblems;\n }\n\n public Function getFunction() {\n return function;\n }\n\n public Map<String, String> getAuthor() {\n return author;\n }\n\n public TestCase[] getTestCases() {\n return testCases;\n }\n\n public String getTestCasesGenerator() {\n return testCasesGenerator;\n }\n}",
"@SuppressWarnings(\"PMD.CommentRequired\")\npublic final class JudgeResult {\n @JsonProperty(value = \"status_code\", required = true) private StatusCode statusCode;\n @JsonProperty(\"error_message\") private String errorMessage;\n private ArrayNode input;\n private JsonNode output;\n @JsonProperty(\"expected_output\") private JsonNode expectedOutput;\n @JsonProperty(\"testcase_passed_count\") private int testcasePassedCount;\n @JsonProperty(\"testcase_total_count\") private int testcaseTotalCount;\n @JsonProperty(\"elapsed_time\") private long elapsedTime; // milliseconds\n @JsonProperty(\"consumed_memory\") private long consumedMemory; // bytes\n\n /**\n * Since some fields are immutable, need to provide a method for Jackson.\n */\n @JsonCreator public JudgeResult(@JsonProperty(value = \"status_code\", required = true) final StatusCode statusCode,\n @JsonProperty(\"error_message\") final String errorMessage,\n @JsonProperty(\"input\") final ArrayNode input, @JsonProperty(\"output\") final JsonNode output,\n @JsonProperty(\"expected_output\") final JsonNode expectedOutput,\n @JsonProperty(\"testcase_passed_count\") final int testcasePassedCount,\n @JsonProperty(\"testcase_total_count\") final int testcaseTotalCount,\n @JsonProperty(\"elapsed_time\") final long elapsedTime,\n @JsonProperty(\"consumed_memory\") final long consumedMemory) {\n this.statusCode = statusCode;\n this.errorMessage = errorMessage;\n this.input = input;\n this.output = output;\n this.expectedOutput = expectedOutput;\n this.testcasePassedCount = testcasePassedCount;\n this.testcaseTotalCount = testcaseTotalCount;\n this.elapsedTime = elapsedTime;\n this.consumedMemory = consumedMemory;\n }\n\n /**\n * Constructor.\n */\n public JudgeResult(final String compileErrorMsg) {\n this.statusCode = StatusCode.COMPILE_ERROR;\n this.errorMessage = compileErrorMsg;\n }\n\n // PENDING or RUNNING\n public JudgeResult(final StatusCode statusCode) {\n this.statusCode = statusCode;\n }\n\n public StatusCode getStatusCode() {\n return statusCode;\n }\n\n public String getErrorMessage() {\n return errorMessage;\n }\n\n public void setErrorMessage(String errorMessage) {\n this.errorMessage = errorMessage;\n }\n\n public ArrayNode getInput() {\n return input;\n }\n\n public JsonNode getOutput() {\n return output;\n }\n\n public JsonNode getExpectedOutput() {\n return expectedOutput;\n }\n\n public int getTestcasePassedCount() {\n return testcasePassedCount;\n }\n\n public int getTestcaseTotalCount() {\n return testcaseTotalCount;\n }\n\n public void setTestcaseTotalCount(int n) {\n this.testcaseTotalCount = n;\n }\n\n public long getElapsedTime() {\n return elapsedTime;\n }\n\n public long getConsumedMemory() {\n return consumedMemory;\n }\n\n public void setElapsedTime(long elapsedTime) {\n this.elapsedTime = elapsedTime;\n }\n}",
"@SuppressWarnings({\"PMD.UnusedPrivateField\", \"PMD.BeanMembersShouldSerialize\", \"PMD.SingularField\",\n \"PMD.ShortVariable\"})\n// @JsonSerialize(using = TypeNodeSerializer.class) Do NOT use it !!!\n@JsonDeserialize(using = TypeNodeDeserializer.class)\npublic class TypeNode {\n /**\n * type.\n */\n private final IntermediateType value;\n /**\n * if parent is hashmap, keyType won't be empty.\n */\n @JsonProperty(\"key_type\") private final Optional<TypeNode> keyType; // left child\n /**\n * if parent is container, this is its element type.\n */\n @JsonProperty(\"element_type\") private final Optional<TypeNode> elementType; // right child\n /**\n * point to parent contaier.\n */\n @JsonIgnore @SuppressWarnings(\"PMD.ImmutableField\") private Optional<TypeNode> parent;\n\n /**\n * Constructor.\n */\n public TypeNode(final IntermediateType value, final Optional<TypeNode> keyType,\n final Optional<TypeNode> elementType) {\n this.value = value;\n this.elementType = elementType;\n this.keyType = keyType;\n this.parent = Optional.empty();\n }\n\n /**\n * Create a TypeNode from a string.\n */\n public static TypeNode fromString(final String typeStr) {\n if (!checkAngleBrackets(typeStr)) {\n throw new IllegalArgumentException(\"Illegal type: \" + typeStr);\n }\n\n // remove all whitespaces\n final String typeString = typeStr.replaceAll(\"\\\\s+\", \"\");\n final Optional<TypeNode> result = fromStringRecursive(typeString);\n if (result.isPresent()) {\n initializeParent(result, Optional.<TypeNode>empty());\n return result.get();\n } else {\n throw new IllegalArgumentException(\"Type can not be empty!\");\n }\n }\n\n @Override\n public String toString() {\n return toString(this);\n }\n\n private static String toString(TypeNode typeNode) {\n if(!typeNode.isContainer()) {\n return typeNode.value.toString();\n }\n final StringBuilder result = new StringBuilder(typeNode.value.toString() + \"<\");\n if(typeNode.keyType.isPresent()) {\n result.append(toString(typeNode.keyType.get()));\n result.append(\", \");\n }\n if(typeNode.elementType.isPresent()) {\n result.append(toString(typeNode.elementType.get()));\n }\n return result + \">\";\n }\n\n // construct a binary tre in post-order\n // A node has three conditions, type, type<type> or type<type,type>\n private static Optional<TypeNode> fromStringRecursive(final String typeStr) {\n final int firstLeftBracket = typeStr.indexOf('<');\n\n if (firstLeftBracket == -1) { // Not a container\n if (typeStr.isEmpty()) {\n return Optional.empty();\n }\n final IntermediateType currentValue = IntermediateType.fromString(typeStr);\n final TypeNode currentNode = new TypeNode(currentValue, Optional.empty(), Optional.empty());\n return Optional.of(currentNode);\n } else { // is a container\n final IntermediateType containerType =\n IntermediateType.fromString(typeStr.substring(0, firstLeftBracket));\n final String childStr = typeStr.substring(firstLeftBracket + 1, typeStr.length() - 1);\n\n if (containerType == IntermediateType.MAP) {\n final int firstCommaOrBracket;\n if (childStr.indexOf('<') == -1 && childStr.indexOf(',') == -1) {\n throw new IllegalArgumentException(\"Illegal type: \" + childStr);\n } else if (childStr.indexOf('<') == -1) {\n firstCommaOrBracket = childStr.indexOf(',');\n } else if (childStr.indexOf(',') == -1) {\n firstCommaOrBracket = childStr.indexOf('<');\n } else {\n firstCommaOrBracket = Math.min(childStr.indexOf('<'), childStr.indexOf(','));\n }\n\n final int commaPos;\n if (childStr.charAt(firstCommaOrBracket) == ',') { // primitive, type\n commaPos = firstCommaOrBracket;\n } else {\n final int rightBracket = findRightBracket(childStr, firstCommaOrBracket);\n commaPos = rightBracket + 1;\n }\n final Optional<TypeNode> keyType = fromStringRecursive(childStr.substring(0, commaPos));\n final Optional<TypeNode> child = fromStringRecursive(childStr.substring(commaPos + 1));\n final TypeNode currentNode = new TypeNode(containerType, keyType, child);\n return Optional.of(currentNode);\n } else {\n final TypeNode currentNode =\n new TypeNode(containerType, Optional.empty(), fromStringRecursive(childStr));\n return Optional.of(currentNode);\n }\n }\n }\n\n /**\n * Check if the brackets match with each other.\n */\n public static boolean checkAngleBrackets(final String typeStr) {\n return checkAngleBrackets(typeStr, 0, 0);\n }\n\n private static boolean checkAngleBrackets(final String typeStr, final int cur, final int count) {\n if (typeStr.length() == cur) {\n return count == 0;\n } else {\n if (count >= 0) {\n final char ch = typeStr.charAt(cur);\n if (ch == '<') {\n return checkAngleBrackets(typeStr, cur + 1, count + 1);\n } else if (ch == '>') {\n return checkAngleBrackets(typeStr, cur + 1, count - 1);\n } else {\n return checkAngleBrackets(typeStr, cur + 1, count);\n }\n } else {\n return false;\n }\n }\n }\n\n /**\n * Find the right matched bracket.\n *\n * @param typeStr the string\n * @param leftBracket a left bracket in the string\n * @return the index of right matched bracket, otherwise return -1\n */\n static int findRightBracket(final String typeStr, final int leftBracket) {\n if (!checkAngleBrackets(typeStr)) {\n throw new IllegalArgumentException(\"Found unmatched brackets!\");\n }\n\n return findRightBracket(typeStr, leftBracket + 1, 1);\n }\n\n private static int findRightBracket(final String typeStr, final int cur, final int count) {\n if (count == 0) {\n return cur - 1;\n }\n\n final char ch = typeStr.charAt(cur);\n if (ch == '<') {\n return findRightBracket(typeStr, cur + 1, count + 1);\n } else if (ch == '>') {\n return findRightBracket(typeStr, cur + 1, count - 1);\n } else {\n return findRightBracket(typeStr, cur + 1, count);\n }\n }\n\n /**\n * Initialize all parent, pre-order.\n */\n private static void initializeParent(final Optional<TypeNode> node,\n final Optional<TypeNode> parent) {\n if (!node.isPresent()) {\n return;\n }\n final TypeNode realNode = node.get();\n realNode.setParent(parent);\n initializeParent(realNode.getKeyType(), node);\n initializeParent(realNode.getElementType(), node);\n }\n\n /**\n * if the elementType is not empty, which means it's a container.\n */\n @JsonIgnore public boolean isContainer() {\n return elementType.isPresent();\n }\n\n /** Singly linked list and binary tree are user-defined class. */\n @JsonIgnore public boolean isCustomizedType() {\n return value == IntermediateType.LINKED_LIST_NODE || value == IntermediateType.BINARY_TREE_NODE;\n }\n\n public boolean hasCustomizedType() {\n return hasCustomizedType(this);\n }\n \n private static boolean hasCustomizedType(final TypeNode type) {\n if (type.getValue() == IntermediateType.LINKED_LIST_NODE\n || type.getValue() == IntermediateType.BINARY_TREE_NODE) {\n return true;\n } else {\n if (type.getElementType().isPresent()) {\n return hasCustomizedType(type.getElementType().get());\n } else {\n return false;\n }\n }\n }\n\n // Generated automatically\n\n public IntermediateType getValue() {\n return value;\n }\n\n public Optional<TypeNode> getKeyType() {\n return keyType;\n }\n\n public Optional<TypeNode> getElementType() {\n return elementType;\n }\n\n public Optional<TypeNode> getParent() {\n return parent;\n }\n\n public void setParent(final Optional<TypeNode> parent) {\n this.parent = parent;\n }\n}",
"public final class ObjectMapperInstance {\n public static final ObjectMapper INSTANCE = new ObjectMapper();\n private ObjectMapperInstance() {}\n\n static {\n INSTANCE.registerModule(new Jdk8Module());\n INSTANCE.setSerializationInclusion(JsonInclude.Include.NON_NULL);\n }\n}",
"public interface DataTypes {\n TypeNode ARRAY_INT = TypeNode.fromString(\"array<int>\");\n TypeNode LIST_INT = TypeNode.fromString(\"list<int>\");\n TypeNode SET_INT = TypeNode.fromString(\"set<int>\");\n TypeNode LINKED_LIST_INT = TypeNode.fromString(\"LinkedListNode<int>\");\n\n TypeNode MAP_STRING_INT = TypeNode.fromString(\"map<string, int>\");\n TypeNode MAP_INT_DOUBLE = TypeNode.fromString(\"map<int, double>\");\n\n TypeNode BINARY_TREE_INT = TypeNode.fromString(\"BinaryTreeNode<int>\");\n\n TypeNode ARRAY_ARRAY_INT = TypeNode.fromString(\"array<array<int>>\");\n TypeNode ARRAY_LIST_INT = TypeNode.fromString(\"array<list<int>>\");\n TypeNode ARRAY_SET_INT = TypeNode.fromString(\"array<set<int>>\");\n TypeNode ARRAY_LINKED_LIST_INT = TypeNode.fromString(\"array<LinkedListNode<int>>\");\n TypeNode ARRAY_MAP_STRING_INT = TypeNode.fromString(\"array<map<string, int>>\");\n TypeNode ARRAY_MAP_INT_DOUBLE = TypeNode.fromString(\"array<map<int, double>>\");\n\n TypeNode LIST_ARRAY_INT = TypeNode.fromString(\"list<array<int>>\");\n TypeNode LIST_LIST_INT = TypeNode.fromString(\"list<list<int>>\");\n TypeNode LIST_SET_INT = TypeNode.fromString(\"list<set<int>>\");\n TypeNode LIST_LINKED_LIST_INT = TypeNode.fromString(\"list<LinkedListNode<int>>\");\n TypeNode LIST_MAP_STRING_INT = TypeNode.fromString(\"list<map<string, int>>\");\n TypeNode LIST_MAP_INT_DOUBLE = TypeNode.fromString(\"list<map<int, double>>\");\n\n TypeNode SET_ARRAY_INT = TypeNode.fromString(\"set<array<int>>\");\n TypeNode SET_LIST_INT = TypeNode.fromString(\"set<list<int>>\");\n TypeNode SET_LINKED_LIST_INT = TypeNode.fromString(\"set<LinkedListNode<int>>\");\n TypeNode SET_SET_INT = TypeNode.fromString(\"set<set<int>>\");\n TypeNode SET_MAP_STRING_INT = TypeNode.fromString(\"set<map<string, int>>\");\n TypeNode SET_MAP_INT_DOUBLE = TypeNode.fromString(\"set<map<int, double>>\");\n\n TypeNode LINKED_LIST_ARRAY_INT = TypeNode.fromString(\"LinkedListNode<array<int>>\");\n TypeNode LINKED_LIST_LIST_INT = TypeNode.fromString(\"LinkedListNode<list<int>>\");\n TypeNode LINKED_LIST_SET_INT = TypeNode.fromString(\"LinkedListNode<set<int>>\");\n TypeNode LINKED_LIST_LINKED_LIST_INT = TypeNode.fromString(\"LinkedListNode<LinkedListNode<int>>\");\n TypeNode LINKED_LIST_MAP_STRING_INT = TypeNode.fromString(\"LinkedListNode<map<string, int>>\");\n TypeNode LINKED_LIST_MAP_INT_DOUBLE = TypeNode.fromString(\"LinkedListNode<map<int, double>>\");\n\n TypeNode BINARY_TREE_ARRAY_INT = TypeNode.fromString(\"BinaryTreeNode<array<int>>\");\n TypeNode BINARY_TREE_LIST_INT = TypeNode.fromString(\"BinaryTreeNode<list<int>>\");\n TypeNode BINARY_TREE_SET_INT = TypeNode.fromString(\"BinaryTreeNode<set<int>>\");\n TypeNode BINARY_TREE_LINKED_LIST_INT = TypeNode.fromString(\"BinaryTreeNode<LinkedListNode<int>>\");\n TypeNode BINARY_TREE_MAP_STRING_INT = TypeNode.fromString(\"BinaryTreeNode<map<string, int>>\");\n TypeNode BINARY_TREE_MAP_INT_DOUBLE = TypeNode.fromString(\"BinaryTreeNode<map<int, double>>\");\n\n TypeNode MAP_STRING_LINKED_LIST_INT = TypeNode.fromString(\"map<string, LinkedListNode<int>>\");\n TypeNode ARRAY_LIST_SET_MAP_STRING_LINKED_LIST_INT = TypeNode.fromString(\n \"array<list<set<map<string, LinkedListNode<int>>>>>\");\n TypeNode BINARY_TREE_MAP_STRING_SET_LIST_DOUBLE = TypeNode.fromString(\n \"BinaryTreeNode<map<string, set<list<double>>>>\");\n\n // two functions\n Function TWO_SUM = new Function(\"twoSum\",\n new Function.Return(TypeNode.fromString(\"array<int>\"),\n \"[index1 + 1, index2 + 1] (index1 < index2)\"), new Function.Parameter[] {\n new Function.Parameter(\"numbers\", TypeNode.fromString(\"array<int>\"), \"An array of Integers\"),\n new Function.Parameter(\"target\", TypeNode.fromString(\"int\"),\n \"target = numbers[index1] + numbers[index2]\")});\n\n Function WORD_LADDER = new Function(\"ladderLength\",\n new Function.Return(TypeNode.fromString(\"int\"), \"The shortest length\"),\n new Function.Parameter[] {\n new Function.Parameter(\"begin_word\", TypeNode.fromString(\"string\"), \"the begin word\"),\n new Function.Parameter(\"end_word\", TypeNode.fromString(\"string\"), \"the end word\"),\n new Function.Parameter(\"dict\", TypeNode.fromString(\"set<string>\"), \"the dictionary\")});\n}"
] | import com.fasterxml.jackson.databind.ObjectMapper;
import org.algohub.engine.judge.CppJudge;
import org.algohub.engine.bo.StatusCode;
import org.algohub.engine.pojo.Function;
import org.algohub.engine.pojo.Problem;
import org.algohub.engine.pojo.JudgeResult;
import org.algohub.engine.type.TypeNode;
import org.algohub.engine.util.ObjectMapperInstance;
import org.junit.Test;
import java.io.IOException;
import static org.algohub.engine.codegenerator.DataTypes.*;
import static org.algohub.engine.codegenerator.DataTypes.BINARY_TREE_MAP_STRING_INT;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail; | package org.algohub.engine.codegenerator;
@SuppressWarnings({"PMD.CommentRequired"})
public class CppCodeGeneratorTest {
private static final ObjectMapper OBJECT_MAPPER = ObjectMapperInstance.INSTANCE;
private static void testSerde(final String typeStr, final String oneTestCase) { | final TypeNode type = TypeNode.fromString(typeStr); | 5 |
ppicas/android-clean-architecture-mvp | app/src/main/java/cat/ppicas/cleanarch/ui/presenter/CityDetailPresenter.java | [
"public class City {\n\n private String mId;\n private String mName;\n private String mCountry;\n private CurrentWeatherPreview mCurrentWeatherPreview;\n\n public City(String id, String name, String country) {\n mId = id;\n mName = name;\n mCountry = country;\n }\n\n public City(String id, String name, String country,\n CurrentWeatherPreview currentWeatherPreview) {\n mId = id;\n mName = name;\n mCountry = country;\n mCurrentWeatherPreview = currentWeatherPreview;\n }\n\n public String getId() {\n return mId;\n }\n\n public String getName() {\n return mName;\n }\n\n public String getCountry() {\n return mCountry;\n }\n\n public CurrentWeatherPreview getCurrentWeatherPreview() {\n return mCurrentWeatherPreview;\n }\n}",
"public interface CityRepository {\n\n City getCity(String cityId);\n\n List<City> findCity(String name);\n\n}",
"public class GetCityTask implements Task<City, IOException> {\n\n private String mId;\n\n private CityRepository mRepository;\n\n public GetCityTask(CityRepository repository, String id) {\n mId = id;\n mRepository = repository;\n }\n\n @Override\n public TaskResult<City, IOException> execute() {\n try {\n return TaskResult.newSuccessResult(mRepository.getCity(mId));\n } catch (RetrofitError e) {\n return TaskResult.newErrorResult(new IOException(e));\n }\n }\n}",
"public interface CityDetailVista extends TaskResultVista {\n\n void setTitle(int stringResId, Object... args);\n\n}",
"public abstract class DisplayErrorTaskCallback<T> implements TaskCallback<T, IOException> {\n\n private final Presenter<? extends TaskResultVista> mPresenter;\n\n /**\n * Constructs an instance of {@link DisplayErrorTaskCallback} that will use\n * the specified {@link Presenter} to display the errors. To display the errors\n * this class expects a {@link Presenter} with a parameter extending {@link\n * TaskResultVista}.\n *\n * @param presenter a {@link Presenter} with a parameter extending {@link\n * TaskResultVista}\n */\n public DisplayErrorTaskCallback(Presenter<? extends TaskResultVista> presenter) {\n mPresenter = presenter;\n }\n\n public void onError(IOException error) {\n TaskResultVista vista = mPresenter.getVista();\n if (vista != null) {\n vista.displayLoading(false);\n error.printStackTrace();\n vista.displayError(R.string.error__connection);\n }\n }\n}",
"public interface TaskExecutor {\n\n <R, E extends Exception> void execute(Task<R, E> task, TaskCallback<R, E> callback);\n\n boolean isRunning(Task<?, ?> task);\n\n}",
"public abstract class Presenter<T extends Vista> {\n\n private T mVista;\n\n /**\n * Returns the current bound {@link Vista} if any.\n *\n * @return The bound {@code Vista} or {@code null}.\n */\n @Nullable\n public T getVista() {\n return mVista;\n }\n\n /**\n * Must be called to bind the {@link Vista} and let the {@link Presenter} know that can start\n * {@code Vista} updates. Normally this method will be called from {@link Activity#onStart()}\n * or from {@link Fragment#onStart()}.\n *\n * @param vista A {@code Vista} instance to bind.\n */\n public final void start(T vista) {\n mVista = vista;\n onStart(vista);\n }\n\n /**\n * Must be called un unbind the {@link Vista} and let the {@link Presenter} know that must\n * stop updating the {@code Vista}. Normally this method will be called from\n * {@link Activity#onStop()} or from {@link Fragment#onStop()}.\n */\n public final void stop() {\n mVista = null;\n onStop();\n }\n\n /**\n * Called when the {@link Presenter} can start {@link Vista} updates.\n *\n * @param vista The bound {@code Vista}.\n */\n public abstract void onStart(T vista);\n\n /**\n * Called when the {@link Presenter} must stop {@link Vista} updates. The extending\n * {@code Presenter} can override this method to provide some custom logic.\n */\n public void onStop() {\n }\n\n /**\n * Called to ask the {@link Presenter} to save its current dynamic state, so it\n * can later be reconstructed in a new instance of its process is\n * restarted.\n *\n * @param state Bundle in which to place your saved state.\n * @see Activity#onSaveInstanceState(Bundle)\n */\n public void saveState(Bundle state) {\n }\n\n /**\n * Called to ask the {@link Presenter} to restore the previous saved state.\n *\n * @param state The data most recently supplied in {@link #saveState}.\n * @see Activity#onRestoreInstanceState(Bundle)\n */\n public void restoreState(Bundle state) {\n }\n\n /**\n * Called when this {@link Presenter} is going to be destroyed, so it has a chance to\n * release resources. The extending {@code Presenter} can override this method to provide some\n * custom logic.\n */\n public void onDestroy() {\n }\n}"
] | import android.content.res.Resources;
import android.text.format.DateFormat;
import java.util.Calendar;
import cat.ppicas.cleanarch.R;
import cat.ppicas.cleanarch.model.City;
import cat.ppicas.cleanarch.repository.CityRepository;
import cat.ppicas.cleanarch.task.GetCityTask;
import cat.ppicas.cleanarch.ui.vista.CityDetailVista;
import cat.ppicas.cleanarch.util.DisplayErrorTaskCallback;
import cat.ppicas.framework.task.TaskExecutor;
import cat.ppicas.framework.ui.Presenter; | /*
* Copyright (C) 2015 Pau Picas Sans <[email protected]>
*
* 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 cat.ppicas.cleanarch.ui.presenter;
public class CityDetailPresenter extends Presenter<CityDetailVista> {
private static final String DAY_OF_WEEK_DATE_FORMAT_PATTERN = "cccc";
private final TaskExecutor mTaskExecutor;
private final CityRepository mCityRepository;
private final Resources mResources;
private final String mCityId;
private GetCityTask mGetCityTask; | private City mCity; | 0 |
krobot-framework/krobot | src/main/java/org/krobot/command/ExceptionHandler.java | [
"public final class Krobot\n{\n public static final String VERSION = \"3.0.0 ALPHA-10\";\n\n public static final String PROPERTY_TOKEN = \"krobot.key\";\n public static final String PROPERTY_TOKEN_FILE = \"krobot.keyFile\";\n public static final String PROPERTY_DISABLE_TOKEN_SAVING = \"krobot.disableKeySaving\";\n public static final String PROPERTY_DISABLE_ASKING_TOKEN = \"krobot.disableAskingKey\";\n public static final String PROPERTY_DISABLE_START_MESSAGE = \"krobot.disableStartMessage\";\n public static final String PROPERTY_DISABLE_STATE_BAR = \"krobot.disableStateBar\";\n public static final String PROPERTY_DISABLE_CONSOLE = \"krobot.disableConsole\";\n public static final String PROPERTY_DISABLE_COLORS = \"krobot.disableColors\";\n\n public static KrobotRunner create()\n {\n return new KrobotRunner();\n }\n\n public static KrobotRuntime getRuntime()\n {\n return KrobotRuntime.get();\n }\n}",
"public class MessageContext\n{\n private JDA jda;\n private User user;\n private Message message;\n private MessageChannel channel;\n\n /**\n * The command Context\n *\n * @param jda Current JDA instance\n * @param user The user that called the command\n * @param message The command message\n * @param channel The channel where the command was called\n */\n public MessageContext(JDA jda, User user, Message message, MessageChannel channel)\n {\n this.jda = jda;\n this.user = user;\n this.message = message;\n this.channel = channel;\n }\n\n /**\n * Check for a <b>bot</b> required permission<br>\n * Throws a {@link BotNotAllowedException} if it hasn't (by default,\n * it will be caught by the ExceptionHandler to print a specific message).\n *\n * @param permission The permission to check\n *\n * @throws BotNotAllowedException If the bot hasn't the permission\n */\n public void require(Permission permission) throws BotNotAllowedException\n {\n Guild guild = getGuild();\n if (guild == null)\n {\n return;\n }\n\n if (!guild.retrieveMember(jda.getSelfUser()).complete().hasPermission(permission))\n {\n throw new BotNotAllowedException(permission);\n }\n }\n\n /**\n * Check for a <b>user</b> required permission<br>\n * Throws a {@link UserNotAllowedException} if it hasn't (by default,\n * it will be caught by the ExceptionHandler to print a specific message).\n *\n * @param permission The permission to check\n *\n * @throws UserNotAllowedException If the user hasn't the permission\n */\n public void requireCaller(Permission permission) throws UserNotAllowedException\n {\n Member member = getMember();\n if (member == null)\n {\n return;\n }\n\n if (!this.getMember().hasPermission(permission))\n {\n throw new UserNotAllowedException(permission);\n }\n }\n\n /**\n * Send a message on the context channel\n *\n * @param content The message content\n *\n * @return A Future representing the task result\n */\n public CompletableFuture<Message> send(String content)\n {\n return channel.sendMessage(content).submit();\n }\n\n /**\n * Send a formatted message on the context channel\n *\n * @param content The message content (will be formated by {@link String#format(String, Object...)}\n * @param args The args for the format\n *\n * @return A Future representing the task result\n */\n public CompletableFuture<Message> send(String content, Object... args)\n {\n return channel.sendMessage(String.format(content, args)).submit();\n }\n\n /**\n * Send an embed message on the context channel\n *\n * @param content The message content\n *\n * @return A Future representing the task result\n */\n public CompletableFuture<Message> send(MessageEmbed content)\n {\n return channel.sendMessage(content).submit();\n }\n\n /**\n * Send an embed message on the context channel\n *\n * @param content The message content (will be built)\n *\n * @return A Future representing task result\n */\n public CompletableFuture<Message> send(EmbedBuilder content)\n {\n return send(content.build());\n }\n\n public CompletableFuture<Message> info(String title, String message)\n {\n return send(Dialog.info(title, message));\n }\n\n public CompletableFuture<Message> warn(String title, String message)\n {\n return send(Dialog.warn(title, message));\n }\n\n public CompletableFuture<Message> error(String title, String message)\n {\n return send(Dialog.error(title, message));\n }\n\n public boolean hasPermission(Permission... permissions)\n {\n if (this.channel instanceof GuildChannel)\n {\n Member member = getMember();\n if (member == null) {\n try {\n MessageUtils.deleteAfter(error(\"Membre inconnu\", \"Impossible de récupérer le membre de l'auteur de la commande\").get(), 2500);\n } catch (InterruptedException | ExecutionException e) {\n e.printStackTrace();\n }\n\n return false;\n }\n\n return member.hasPermission((GuildChannel) this.channel, permissions);\n }\n\n return true;\n }\n\n public boolean botHasPermission(Permission... permissions)\n {\n if (this.channel instanceof GuildChannel)\n {\n return getBotMember().hasPermission((GuildChannel) this.channel, permissions);\n }\n\n return true;\n }\n\n /**\n * @return Return the caller user as a mention\n */\n public String mentionCaller()\n {\n return this.getUser().getAsMention();\n }\n\n /**\n * @return The current JDA instance\n */\n public JDA getJDA()\n {\n \treturn jda;\n }\n \n /**\n * @return The guild where the command was called\n */\n public Guild getGuild()\n {\n if (this.channel instanceof GuildChannel)\n {\n return ((GuildChannel) this.getChannel()).getGuild();\n }\n\n return null;\n }\n\n public Member getBotMember()\n {\n\n Guild guild = getGuild();\n if (guild == null)\n {\n return null;\n }\n\n return guild.getMember(jda.getSelfUser());\n }\n\n /**\n * @return The guild member that called the command\n */\n public Member getMember()\n {\n Guild guild = getGuild();\n if (guild == null)\n {\n return null;\n }\n\n return guild.retrieveMember(this.getUser()).complete();\n }\n\n /**\n * @return The user that called the command\n */\n public User getUser()\n {\n return user;\n }\n\n /**\n * @return The command message\n */\n public Message getMessage()\n {\n return message;\n }\n\n /**\n * @return The channel where the command was called\n */\n public MessageChannel getChannel()\n {\n return channel;\n }\n\n /**\n * @return If the context is from a private message channel\n */\n public boolean isFromPrivateMessage()\n {\n return channel instanceof PrivateChannel;\n }\n}",
"public class BotNotAllowedException extends RuntimeException\n{\n private Permission permission;\n\n /**\n * The Bot Not Allowed Exception\n *\n * @param permission The missing permission\n */\n public BotNotAllowedException(Permission permission)\n {\n super(\"The bot needs the permission '\" + permission.getName() + \"' to execute this command\");\n\n this.permission = permission;\n }\n\n public Permission getPermission()\n {\n return permission;\n }\n}",
"public class UserNotAllowedException extends RuntimeException\n{\n private Permission permission;\n\n /**\n * The User Not Allowed Exception (with a simple message)\n */\n public UserNotAllowedException()\n {\n super(\"You are not allowed to do that\");\n }\n\n /**\n * The User Not Allowed Exception\n *\n * @param s Custom message to display\n */\n public UserNotAllowedException(String s)\n {\n super(s);\n }\n\n /**\n * The User Not Allowed Exception\n *\n * @param permission The missing permission\n */\n public UserNotAllowedException(Permission permission)\n {\n super(\"You needs the permission '\" + permission.getName() + \"' to execute this command\");\n\n this.permission = permission;\n }\n\n public Permission getPermission()\n {\n return permission;\n }\n}",
"public class ColoredLogger\n{\n private Logger logger;\n\n // TODO: fatal\n\n public ColoredLogger(Logger logger)\n {\n this.logger = logger;\n }\n\n public static ColoredLogger getLogger(String name)\n {\n return new ColoredLogger(LogManager.getLogger(name));\n }\n\n public void info(Object text, Object... format)\n {\n logger.info(String.valueOf(text), format);\n }\n\n public void info(Color color, Object text, Object... format)\n {\n logger.info(ansi().fg(color).a(text).reset().toString(), format);\n }\n\n public void infoBold(Object text, Object... format)\n {\n logger.info(ansi().bold().a(text).reset().toString(), format);\n }\n\n public void infoBold(Color color, Object text, Object... format)\n {\n logger.info(ansi().bold().fg(color).a(text).reset().toString(), format);\n }\n\n public void infoAuto(String text, Object... format)\n {\n logger.info(ansi().render(text).reset().toString(), format);\n }\n\n public void warn(Object text, Object... format)\n {\n logger.warn(String.valueOf(text), format);\n }\n\n public void warn(Color color, Object text, Object... format)\n {\n logger.warn(ansi().fg(color).a(text).reset().toString(), format);\n }\n\n public void warnBold(Object text, Object... format)\n {\n logger.warn(ansi().bold().a(text).reset().toString(), format);\n }\n\n public void warnBold(Color color, Object text, Object... format)\n {\n logger.warn(ansi().bold().fg(color).a(text).reset().toString(), format);\n }\n\n public void warnAuto(String text, Object... format)\n {\n logger.warn(ansi().render(text).reset().toString(), format);\n }\n\n public void error(Object text, Object... format)\n {\n logger.error(String.valueOf(text), format);\n }\n\n public void error(Color color, Object text, Object... format)\n {\n logger.error(ansi().fg(color).a(text).reset().toString(), format);\n }\n\n public void errorBold(Object text, Object... format)\n {\n logger.error(ansi().bold().a(text).reset().toString(), format);\n }\n\n public void errorBold(Color color, Object text, Object... format)\n {\n logger.error(ansi().bold().fg(color).a(text).reset().toString(), format);\n }\n\n public void errorBold(Color color, Object text, Throwable t)\n {\n logger.error(ansi().bold().fg(color).a(text).reset().toString(), t);\n }\n\n public void errorAuto(String text, Object... format)\n {\n logger.error(ansi().render(text).reset().toString(), format);\n }\n\n public void errorAuto(String text, Throwable t)\n {\n logger.error(ansi().render(text).reset().toString(), t);\n }\n\n public void errorAuto(Color color, String text, Object... format)\n {\n logger.error(ansi().fg(color).render(text).reset().toString(), format);\n }\n\n public void errorAuto(Color color, String text, Throwable t)\n {\n logger.error(ansi().fg(color).render(text).reset().toString(), t);\n }\n}",
"public final class Dialog\n{\n /**\n * Icon used in info dialogs\n */\n public static final String INFO_ICON = \"http://litarvan.github.com/krobot_icons/info_v2.png\";\n\n /**\n * Icon used in warn dialogs\n */\n public static final String WARN_ICON = \"http://litarvan.github.com/krobot_icons/warn.png\";\n\n /**\n * Icon used in error dialogs\n */\n public static final String ERROR_ICON = \"http://litarvan.github.com/krobot_icons/error.png\";\n\n /**\n * The color used for the info dialogs\n */\n public static final Color INFO_COLOR = Color.decode(\"0x0094FF\");\n\n /**\n * The color used for the warn dialogs\n */\n public static final Color WARN_COLOR = Color.decode(\"0xFFBD00\");\n\n /**\n * The color used for the errors dialogs\n */\n public static final Color ERROR_COLOR = Color.decode(\"0xED1B2E\");\n\n /**\n * Displays an info dialog\n *\n * @param title The title of the dialog\n * @param description The description of the dialog\n *\n * @return The created dialog\n */\n public static MessageEmbed info(String title, String description)\n {\n return dialog(INFO_COLOR, title, description, INFO_ICON);\n }\n\n /**\n * Display a warning dialog\n *\n * @param title The title of the dialog\n * @param description The description of the dialog\n *\n * @return The created dialog\n */\n public static MessageEmbed warn(String title, String description)\n {\n return dialog(WARN_COLOR, title, description, WARN_ICON);\n }\n\n /**\n * Displays an error dialog\n *\n * @param title The title of the dialog\n * @param description The description of the dialog\n *\n * @return The created dialog\n */\n public static MessageEmbed error(String title, String description)\n {\n return dialog(ERROR_COLOR, title, description, ERROR_ICON);\n }\n\n /**\n * Displays a dialog\n *\n * @param color The color of the bar on the dialog' left side\n * @param title The title of the dialog\n * @param description The description of the dialog\n *\n * @return The created dialog\n */\n public static MessageEmbed dialog(Color color, String title, String description)\n {\n return dialog(color, title, description, null);\n }\n\n /**\n * Displays a dialog\n *\n * @param color The color of the bar on the dialog left side\n * @param title The title of the dialog\n * @param description The description of the dialog\n * @param icon The URL of the dialog icon\n *\n * @return The created dialog\n */\n public static MessageEmbed dialog(Color color, String title, String description, String icon)\n {\n EmbedBuilder builder = new EmbedBuilder();\n\n builder.setColor(color);\n\n builder.setTitle(title, null);\n builder.setDescription(description);\n\n if (icon != null)\n {\n builder.setThumbnail(icon);\n }\n\n return builder.build();\n }\n}",
"public final class Markdown\n{\n public static final String BOLD_MODIFIER = \"**\";\n public static final String ITALIC_MODIFIER = \"_\";\n public static final String UNDERLINE_MODIFIER = \"__\";\n public static final String CODE_MODIFIER = \"```\";\n public static final String STRIKEOUT_MODIFIER = \"~~\";\n public static final String SMALL_CODE_MODIFIER = \"`\";\n\n public static String bold(String string)\n {\n return markdown(string, BOLD_MODIFIER);\n }\n\n public static String italic(String string)\n {\n return markdown(string, ITALIC_MODIFIER);\n }\n\n public static String underline(String string)\n {\n return markdown(string, UNDERLINE_MODIFIER);\n }\n\n public static String strikeout(String string)\n {\n return markdown(string, STRIKEOUT_MODIFIER);\n }\n\n public static String smallCode(String string)\n {\n return markdown(string, SMALL_CODE_MODIFIER);\n }\n\n public static String code(String string)\n {\n return code(string, \"\");\n }\n\n public static String code(String string, String lang)\n {\n return CODE_MODIFIER + lang + \"\\n\" + string + \"\\n\" + CODE_MODIFIER;\n }\n\n public static String markdown(String string, String modifier)\n {\n return modifier + string + modifier;\n }\n}",
"public final class MessageUtils\n{\n /**\n * Number of maximum character in a Discord message\n */\n public static final int MAX_MESSAGE_CHARS = 1999;\n\n private static ScheduledExecutorService deletePool = Executors.newSingleThreadScheduledExecutor();\n\n /**\n * Split a message in messages of at most {@link #MAX_MESSAGE_CHARS} characters\n *\n * @param message The message to split\n *\n * @return The splitted message\n */\n public static String[] splitMessage(@NotNull String message)\n {\n return splitMessage(message, MAX_MESSAGE_CHARS);\n }\n\n /**\n * Split a message in messages of at most a given amount of characters\n *\n * @param message The message to split\n * @param limit The messages max characters\n *\n * @return The splitted message\n */\n public static String[] splitMessage(@NotNull String message, int limit)\n {\n ArrayList<String> messages = new ArrayList<>();\n\n while (message.length() > limit)\n {\n messages.add(message.substring(0, limit));\n message = message.substring(limit, message.length());\n }\n\n messages.add(message);\n\n return messages.toArray(new String[messages.size()]);\n }\n\n /**\n * Split a message in messages of at most {@link #MAX_MESSAGE_CHARS} characters,\n * without breaking the message lines.\n *\n * @param message The message to split\n *\n * @return The splitted message\n */\n public static String[] splitMessageKeepLines(@NotNull String message)\n {\n return splitMessageKeepLines(message, MAX_MESSAGE_CHARS);\n }\n\n /**\n * Split a message in messages of at most a given amount of characters,\n * without breaking the message lines.\n *\n * @param message The message to split\n * @param limit The messages max characters\n *\n * @return The splitted message\n */\n public static String[] splitMessageKeepLines(@NotNull String message, int limit)\n {\n ArrayList<String> messages = new ArrayList<>();\n String[] lines = message.split(\"\\n\");\n StringBuilder current = new StringBuilder();\n\n for (String line : lines)\n {\n if (current.length() + line.length() > limit)\n {\n messages.add(current.toString());\n current = new StringBuilder();\n }\n\n current.append(line).append(\"\\n\");\n }\n\n messages.add(current.toString());\n\n return messages.toArray(new String[messages.size()]);\n }\n\n public static String[] splitWithQuotes(String string, boolean keepQuotes)\n {\n List<String> result = new ArrayList<>();\n String[] split = string.split(\" \");\n\n for (int i = 0; i < split.length; i++)\n {\n StringBuilder current = new StringBuilder(split[i]);\n\n if (current.toString().startsWith(\"\\\"\"))\n {\n i++;\n\n while (i < split.length && !current.toString().endsWith(\"\\\"\"))\n {\n current.append(\" \").append(split[i]);\n i++;\n }\n\n i--;\n }\n\n String done = current.toString();\n\n if (!done.endsWith(\"\\\"\"))\n {\n result.addAll(Arrays.asList(done.split(\" \")));\n }\n else\n {\n result.add(keepQuotes ? done : done.replace(\"\\\"\", \"\"));\n }\n }\n\n return result.toArray(new String[result.size()]);\n }\n\n /**\n * Get the most similar message of a list to a base<br><br>\n *\n * <b>Example:</b><br><br>\n *\n * base = hello<br>\n * messages = [haul, hella, yay]<br><br>\n *\n * It returns <b>hella</b>\n *\n * @param base The base message\n * @param messages The messages where to get the most similar\n *\n * @return The most similar message to the base\n */\n public static String getMostSimilar(String base, String[] messages)\n {\n ArrayList<Integer> matches = new ArrayList<>();\n\n for (String message : messages)\n {\n matches.add(StringUtils.getLevenshteinDistance(base, message));\n }\n\n int candidateIndex = 0;\n int candidate = Integer.MAX_VALUE;\n\n for (int i = 0; i < matches.size(); i++)\n {\n int entry = matches.get(i);\n\n if (entry < candidate)\n {\n candidate = entry;\n candidateIndex = i;\n }\n }\n\n if (candidate > 10)\n {\n return null;\n }\n\n return messages[matches.get(candidateIndex)];\n }\n\n /**\n * Delete a message after a certain amount of time\n *\n * @param message The message to delete\n * @param duration How much time (in milliseconds) to wait before deletion\n */\n public static void deleteAfter(Message message, int duration)\n {\n deletePool.schedule(() -> message.delete().queue(), duration, TimeUnit.MILLISECONDS);\n }\n\n public static Message search(TextChannel channel, String query, int max)\n {\n List<Message> messages = channel.getHistory().retrievePast(100).complete();\n messages.remove(0);\n\n Message result = null;\n int searched = 0;\n\n while (result == null && searched < max)\n {\n messages = channel.getHistory().retrievePast(100).complete();\n\n for (Message message : messages)\n {\n if (message.getContentDisplay().toLowerCase().contains(query.toLowerCase().trim()))\n {\n result = message;\n break;\n }\n }\n\n searched += messages.size();\n }\n\n return result;\n }\n}"
] | import org.krobot.permission.BotNotAllowedException;
import org.krobot.permission.UserNotAllowedException;
import org.krobot.util.ColoredLogger;
import org.krobot.util.Dialog;
import org.krobot.util.Markdown;
import org.krobot.util.MessageUtils;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import javax.inject.Singleton;
import net.dv8tion.jda.api.entities.PrivateChannel;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.krobot.Krobot;
import org.krobot.MessageContext; | /*
* Copyright 2017 The Krobot Contributors
*
* This file is part of Krobot.
*
* Krobot 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.
*
* Krobot 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 Krobot. If not, see <http://www.gnu.org/licenses/>.
*/
package org.krobot.command;
@Singleton
public class ExceptionHandler
{
private static final ColoredLogger log = ColoredLogger.getLogger("ExceptionHandler");
private Map<Class<? extends Throwable>, IExceptionHandler> handlers = new HashMap<>();
public void handle(MessageContext context, KrobotCommand command, String[] args, Throwable t)
{
Optional<IExceptionHandler> handler = handlers.entrySet().stream().filter(e -> e.getKey().isInstance(t)).map(Entry::getValue).findFirst();
if (handler.isPresent())
{
if (command.getErrorMP())
handler.get().handle(new MessageContext(context.getJDA(), context.getUser(), context.getMessage(), context.getUser().openPrivateChannel().complete()), t);
else
handler.get().handle(context, t);
return;
}
log.errorAuto("@|red Unhandled |@ @|red,bold '" + t.getClass().getName() + "'|@ @|red while executing command '|@@|red,bold " + command.getLabel() + "|@@|red '|@", t);
String report = makeCrashReport(t, command, args, context);
try
{ | MessageUtils.deleteAfter(context.send(Dialog.error("Command crashed !", "A crash report has been sent to you " + context.getUser().getAsMention() + " . Please send it to the developer as soon as possible !")).get(), 5000); | 5 |
egetman/ibm-bpm-rest-client | src/main/ru/bpmink/bpm/api/impl/simple/ExposedClientImpl.java | [
"public interface ExposedClient {\n\n /**\n * Retrieve items of all types that are exposed to an end user.\n *\n * @return {@link ru.bpmink.bpm.model.common.RestRootEntity} instance, that contains information about\n * all exposed to an end user entities: {@link ru.bpmink.bpm.model.other.exposed.ExposedItems}.\n */\n RestRootEntity<ExposedItems> listItems();\n\n /**\n * Retrieve items of a specific type that are exposed to an end user.\n * If itemType is null, then all service subtypes will be included in the result set.\n *\n * @param itemType is a filter of items (see {@link ru.bpmink.bpm.model.other.exposed.ItemType})\n * @return {@link ru.bpmink.bpm.model.common.RestRootEntity} instance, that contains information about\n * all exposed to an end user entities of specified {@literal itemType}:\n * {@link ru.bpmink.bpm.model.other.exposed.ExposedItems}. If parameter {@literal itemType} is null,\n * return will be similar to call {@link #listItems()}.\n */\n RestRootEntity<ExposedItems> listItems(@Nullable ItemType itemType);\n\n /**\n * Retrieve item by the specified name.\n * If itemName is null, then {@link IllegalArgumentException} should be thrown.\n * <p>Note: default wle rest api don't allows to extract only one, specified item.\n * So sorting and filtering are performed on client side. That's why, if api call was unsuccessful, there are\n * possibility of throwing {@link ru.bpmink.bpm.model.common.RestException}.</p>\n *\n * @param itemName is a full name of item {@link ru.bpmink.bpm.model.other.exposed.Item#getName()}\n * @return {@link ru.bpmink.bpm.model.other.exposed.Item} instance with given {@literal itemName}.\n * If item with given {@literal itemName} not found, it implementation-dependent to return {@literal null} or\n * {@literal NULL_OBJECT}.\n * @throws IllegalArgumentException if itemName is null.\n * @throws ru.bpmink.bpm.model.common.RestException if the api call was unsuccessful.\n */\n @SuppressWarnings(\"SameParameterValue\")\n Item getItemByName(@Nonnull String itemName);\n\n /**\n * Retrieve item by the specified name and type.\n * If itemName or itemType is null, then {@link IllegalArgumentException} should be thrown.\n * <p>Note: default wle rest api don't allows to extract only one, specified item.\n * So sorting and filtering are performed on client side. That's why, if api call was unsuccessful, there are\n * possibility of throwing {@link ru.bpmink.bpm.model.common.RestException}.</p>\n *\n * @param itemName is a full name of item {@link ru.bpmink.bpm.model.other.exposed.Item#getName()}\n * @param itemType is a filter of items {@link ru.bpmink.bpm.model.other.exposed.ItemType}\n * @return {@link ru.bpmink.bpm.model.other.exposed.Item} instance with given {@literal itemName}\n * and {@literal itemType}.\n * If item with given {@literal itemName} and {@literal itemType} not found, it implementation-dependent\n * to return {@literal null} or {@literal NULL_OBJECT}.\n * @throws IllegalArgumentException if itemName or itemType are null\n * @throws ru.bpmink.bpm.model.common.RestException if the api call was unsuccessful.\n */\n Item getItemByName(@Nonnull ItemType itemType, @Nonnull String itemName);\n\n}",
"@SuppressWarnings(\"unused\")\npublic class RestRootEntity<T extends Describable> extends RestEntity {\n\n //The status of the API call.\n @SerializedName(\"status\")\n private String status;\n\n //Success API call data.\n @SerializedName(\"data\")\n private T payload;\n\n //Unsuccessful API call information.\n @SerializedName(\"Data\")\n private RestException exception;\n\n /**\n * @return true if the API call was unsuccessful, and\n * {@link ru.bpmink.bpm.model.common.RestRootEntity} contains exception information.\n */\n @SuppressWarnings(\"WeakerAccess\")\n public boolean isExceptional() {\n return exception != null;\n }\n\n /**\n * @return Success API call data.\n * @throws ru.bpmink.bpm.model.common.RestException if the API call was unsuccessful,\n * and {@link ru.bpmink.bpm.model.common.RestRootEntity} contain\n * any exception details.\n */\n public T getPayload() {\n if (isExceptional()) {\n //noinspection ConstantConditions\n throw exception;\n }\n return payload;\n }\n\n /**\n * @return The status of the API call.\n */\n public String getStatus() {\n return status;\n }\n\n public void setStatus(String status) {\n this.status = status;\n }\n\n @Override\n @SuppressWarnings(\"StringBufferReplaceableByString\")\n public String toString() {\n StringBuilder builder = new StringBuilder();\n builder.append(this.getClass().getName());\n builder.append(COLON).append(SPACE);\n builder.append(\"Status\").append(COLON).append(SPACE);\n builder.append(status).append(SEMICOLON).append(SPACE);\n builder.append(\"IsExceptional\").append(COLON).append(SPACE);\n builder.append((isExceptional() ? PASSES : FAILS));\n return builder.toString();\n }\n}",
"public class ExposedItems extends RestEntity {\n\n\tprivate static final List<Item> EMPTY_LIST = Lists.newArrayList();\n\t\n\tpublic ExposedItems() {}\n\t\n\t@SerializedName(\"exposedItemsList\")\n\tprivate List<Item> exposedItems = Lists.newArrayList();\n\t\n\t//To avoid null checks after de-serialization.\n\tpublic List<Item> getExposedItems() {\n\t\treturn MoreObjects.firstNonNull(exposedItems, EMPTY_LIST);\n\t}\n\t\n}",
"public class Item extends RestEntity {\n\n public Item() {}\n\n //The exposed ID of the item.\n @SerializedName(\"ID\")\n private String id;\n\n //The type associated with the exposed item: 'process', 'service', 'scoreboard', or 'report'.\n @SerializedName(\"type\")\n private ItemType itemType;\n\n //The subtype associated with the exposed item of type 'service': 'not_exposed', 'administration_service',\n //'startable_service', 'dashboard', or 'url'.\n @SerializedName(\"subtype\")\n private SubType sybType;\n\n //The exposed URL of the item; use this to view or run the item.\n @SerializedName(\"runURL\")\n private String runUrl;\n\n //The item's ID; this will be based on the type of the item.\n @SerializedName(\"itemID\")\n private String itemId;\n\n //The item's reference; this will be based on the type of the item.\n @SerializedName(\"itemReference\")\n private String itemReference;\n\n //The ID of the process application associated with this item.\n @SerializedName(\"processAppID\")\n private String processAppId;\n\n //The title of the process application associated with this item.\n @SerializedName(\"processAppName\")\n private String processAppName;\n\n //The acronym of the process application associated with this item.\n @SerializedName(\"processAppAcronym\")\n private String processAppAcronym;\n\n //The ID of the snapshot associated with this item.\n @SerializedName(\"snapshotID\")\n private String snapshotId;\n\n //The title of the snapshot associated with this item.\n @SerializedName(\"snapshotName\")\n private String snapshotName;\n\n //The time, when snapshot is created\n @SerializedName(\"snapshotCreatedOn\")\n private Date snapshotCreatedOn;\n\n //The display name of the item; this will be the name of the Process, Service, Scoreboard or Report.\n @SerializedName(\"display\")\n private String name;\n\n //The ID of the branch (track) associated with this item.\n @SerializedName(\"branchID\")\n private String branchId;\n\n //The branch (track) name associated with this item.\n @SerializedName(\"branchName\")\n private String branchName;\n\n //If startable via a REST api, a relative URL that can start the item.\n @SerializedName(\"startURL\")\n private String startUrl;\n\n @SerializedName(\"isDefault\")\n private Boolean isDefault;\n\n @SerializedName(\"tip\")\n private Boolean tip;\n\n /**\n * @return The exposed ID of the item.\n */\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n /**\n * @return The type associated with the exposed item: 'process', 'service', 'scoreboard', or 'report'.\n */\n public ItemType getItemType() {\n return itemType;\n }\n\n public void setItemType(ItemType itemType) {\n this.itemType = itemType;\n }\n\n /**\n * @return The subtype associated with the exposed item of type 'service': 'not_exposed', 'administration_service',\n * 'startable_service', 'dashboard', or 'url'.\n */\n public SubType getSybType() {\n return sybType;\n }\n\n public void setSybType(SubType sybType) {\n this.sybType = sybType;\n }\n\n /**\n * @return The exposed URL of the item; use this to view or run the item.\n */\n public String getRunUrl() {\n return runUrl;\n }\n\n public void setRunUrl(String runUrl) {\n this.runUrl = runUrl;\n }\n\n /**\n * @return The item's ID; this will be based on the type of the item.\n */\n public String getItemId() {\n return itemId;\n }\n\n public void setItemId(String itemId) {\n this.itemId = itemId;\n }\n\n /**\n * @return The item's reference; this will be based on the type of the item.\n */\n public String getItemReference() {\n return itemReference;\n }\n\n public void setItemReference(String itemReference) {\n this.itemReference = itemReference;\n }\n\n /**\n * @return The ID of the process application associated with this item.\n */\n public String getProcessAppId() {\n return processAppId;\n }\n\n public void setProcessAppId(String processAppId) {\n this.processAppId = processAppId;\n }\n\n /**\n * @return The acronym of the process application associated with this item.\n */\n public String getProcessAppAcronym() {\n return processAppAcronym;\n }\n\n public void setProcessAppAcronym(String processAppAcronym) {\n this.processAppAcronym = processAppAcronym;\n }\n\n /**\n * @return The ID of the snapshot associated with this item.\n */\n public String getSnapshotId() {\n return snapshotId;\n }\n\n public void setSnapshotId(String snapshotId) {\n this.snapshotId = snapshotId;\n }\n\n\n /**\n * @return The title of the snapshot associated with this item.\n */\n public String getSnapshotName() {\n return snapshotName;\n }\n\n public void setSnapshotName(String snapshotName) {\n this.snapshotName = snapshotName;\n }\n\n /**\n * @return The time, when snapshot is created.\n */\n public Date getSnapshotCreatedOn() {\n if (snapshotCreatedOn != null) {\n return new Date(snapshotCreatedOn.getTime());\n }\n return null;\n }\n\n /**\n * @param snapshotCreatedOn the snapshotCreatedOn to set.\n */\n public void setSnapshotCreatedOn(Date snapshotCreatedOn) {\n if (snapshotCreatedOn != null) {\n this.snapshotCreatedOn = new Date(snapshotCreatedOn.getTime());\n }\n }\n\n /**\n * @return The display name of the item; this will be the name of the Process, Service, Scoreboard or Report.\n */\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n /**\n * @return The title of the process application associated with this item.\n */\n public String getProcessAppName() {\n return processAppName;\n }\n\n public void setProcessAppName(String processAppName) {\n this.processAppName = processAppName;\n }\n\n /**\n * @return The ID of the branch (track) associated with this item.\n */\n public String getBranchId() {\n return branchId;\n }\n\n public void setBranchId(String branchId) {\n this.branchId = branchId;\n }\n\n /**\n * @return The branch (track) name associated with this item.\n */\n public String getBranchName() {\n return branchName;\n }\n\n public void setBranchName(String branchName) {\n this.branchName = branchName;\n }\n\n /**\n * @return If startable via a REST api, a relative URL that can start the item.\n */\n public String getStartUrl() {\n return startUrl;\n }\n\n public void setStartUrl(String startUrl) {\n this.startUrl = startUrl;\n }\n\n /**\n * @return The isDefault attribute.\n */\n public Boolean isDefault() {\n return isDefault;\n }\n\n public void setIsDefault(Boolean isDefault) {\n this.isDefault = isDefault;\n }\n\n /**\n * @return The tip attribute.\n */\n public Boolean isTip() {\n return tip;\n }\n\n public void setTip(Boolean tip) {\n this.tip = tip;\n }\n\n} ",
"public enum ItemType {\n\t\n\t@SerializedName(\"process\")\n\tPROCESS, \n\t@SerializedName(\"service\")\n\tSERVICE, \n\t@SerializedName(\"scoreboard\")\n\tSCOREBOARD, \n\t@SerializedName(\"report\")\n\tREPORT\n\t\n}",
"public class SafeUriBuilder extends URIBuilder {\n\n private static final String DATE_TIME_FORMAT = \"yyyy-MM-dd'T'HH:mm:ss'Z'\";\n\n /**\n * Constructs an empty instance.\n */\n @SuppressWarnings(\"unused\")\n public SafeUriBuilder() {\n super();\n }\n\n /**\n * Creates SafeUriBuilder instance from given URI.\n * @param source is a URI to build from.\n */\n public SafeUriBuilder(URI source) {\n fromUri(source);\n }\n\n /**\n * Constructs the SafeUriBuilder from given URI.\n * @param source is a URI to build from.\n * @return this instance of SafeUriBuilder.\n */\n private SafeUriBuilder fromUri(URI source) {\n setScheme(source.getScheme());\n setHost(source.getHost());\n setPort(source.getPort());\n setPath(source.getPath());\n return this;\n }\n\n /**\n * Builds new path of SafeUriBuilder, which contain's old path with new one appended.\n * @param path new segment to add.\n * @return this instance of SafeUriBuilder.\n */\n public SafeUriBuilder addPath(String path) {\n setPath(getPath() + normalizePath(path));\n return this;\n }\n\n /**\n * Replaces '/' from the path end and add '/' to beginning, if them don't present.\n * @param path given new segment of path.\n * @return normalized path.\n */\n private String normalizePath(String path) {\n //Avoid NPE\n path = MoreObjects.firstNonNull(path, EMPTY_STRING);\n if (path.endsWith(SLASH)) {\n path = path.substring(0, path.length() - 1);\n }\n if (!path.startsWith(SLASH)) {\n path = SLASH + path;\n }\n return path;\n }\n\n @Override\n public URI build() {\n try {\n return super.build();\n } catch (URISyntaxException e) {\n throw new RuntimeException(\"Can't build Uri for: \" + getScheme() + getHost() + getPort() + getPath(), e);\n }\n }\n\n @Override\n public SafeUriBuilder addParameter(String param, String value) {\n super.addParameter(param, value);\n return this;\n }\n\n public SafeUriBuilder addParameter(String param, Object value) {\n return this.addParameter(param, String.valueOf(value));\n }\n\n @SuppressWarnings(\"WeakerAccess\")\n public SafeUriBuilder addParameter(String param, Date value, Format format) {\n return this.addParameter(param, format.format(value));\n }\n\n public SafeUriBuilder addParameter(String param, Date value) {\n return this.addParameter(param, value, new SimpleDateFormat(DATE_TIME_FORMAT));\n }\n}"
] | import com.google.gson.reflect.TypeToken;
import org.apache.http.client.HttpClient;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.Args;
import ru.bpmink.bpm.api.client.ExposedClient;
import ru.bpmink.bpm.model.common.RestRootEntity;
import ru.bpmink.bpm.model.other.exposed.ExposedItems;
import ru.bpmink.bpm.model.other.exposed.Item;
import ru.bpmink.bpm.model.other.exposed.ItemType;
import ru.bpmink.util.SafeUriBuilder;
import javax.annotation.Nonnull;
import javax.annotation.concurrent.Immutable;
import java.net.URI;
import java.util.List; | package ru.bpmink.bpm.api.impl.simple;
@Immutable
final class ExposedClientImpl extends BaseClient implements ExposedClient {
private static final Item EMPTY_ITEM = new Item();
private final URI rootUri;
private final HttpClient httpClient;
private final HttpContext httpContext;
ExposedClientImpl(URI rootUri, HttpClient httpClient, HttpContext httpContext) {
this.httpClient = httpClient;
this.rootUri = rootUri;
this.httpContext = httpContext;
}
ExposedClientImpl(URI rootUri, HttpClient httpClient) {
this(rootUri, httpClient, null);
}
/**
* {@inheritDoc}
*/
@Override
public RestRootEntity<ExposedItems> listItems() {
return listItems(rootUri);
}
/**
* {@inheritDoc}
*/
@Override | public RestRootEntity<ExposedItems> listItems(ItemType itemType) { | 4 |
multi-os-engine/moe-plugin-gradle | src/main/java/org/moe/gradle/tasks/XcodeBuild.java | [
"public class MoeExtension extends AbstractMoeExtension {\n\n private static final Logger LOG = Logging.getLogger(MoeExtension.class);\n\n @NotNull\n public final PackagingOptions packaging;\n\n @NotNull\n public final ResourceOptions resources;\n\n @NotNull\n public final XcodeOptions xcode;\n\n @NotNull\n public final SigningOptions signing;\n\n @NotNull\n public final UIActionsAndOutletsOptions actionsAndOutlets;\n\n @NotNull\n public final IpaExportOptions ipaExport;\n\n @NotNull\n public final RemoteBuildOptions remoteBuildOptions;\n\n @NotNull\n private MoePlatform platform = MoePlatform.IOS;\n\n @NotNull\n public final ProGuardOptions proguard;\n\n public MoeExtension(@NotNull MoePlugin plugin, @NotNull Instantiator instantiator) {\n super(plugin, instantiator);\n this.packaging = instantiator.newInstance(PackagingOptions.class);\n this.resources = instantiator.newInstance(ResourceOptions.class);\n this.xcode = instantiator.newInstance(XcodeOptions.class);\n this.signing = instantiator.newInstance(SigningOptions.class);\n this.actionsAndOutlets = instantiator.newInstance(UIActionsAndOutletsOptions.class);\n this.ipaExport = instantiator.newInstance(IpaExportOptions.class);\n this.remoteBuildOptions = instantiator.newInstance(RemoteBuildOptions.class);\n this.proguard = instantiator.newInstance(ProGuardOptions.class);\n }\n\n void setup() {}\n\n @IgnoreUnused\n public void packaging(Action<PackagingOptions> action) {\n Require.nonNull(action).execute(packaging);\n }\n\n @IgnoreUnused\n public void resources(Action<ResourceOptions> action) {\n Require.nonNull(action).execute(resources);\n }\n\n @IgnoreUnused\n public void xcode(Action<XcodeOptions> action) {\n Require.nonNull(action).execute(xcode);\n }\n\n @IgnoreUnused\n public void signing(Action<SigningOptions> action) {\n Require.nonNull(action).execute(signing);\n }\n\n @IgnoreUnused\n public void actionsAndOutlets(Action<UIActionsAndOutletsOptions> action) {\n Require.nonNull(action).execute(actionsAndOutlets);\n }\n\n @IgnoreUnused\n public void ipaExport(Action<IpaExportOptions> action) {\n Require.nonNull(action).execute(ipaExport);\n }\n\n @IgnoreUnused\n public void remoteBuild(Action<RemoteBuildOptions> action) {\n Require.nonNull(action).execute(remoteBuildOptions);\n }\n\n @IgnoreUnused\n public void proguard(Action<ProGuardOptions> action) {\n Require.nonNull(action).execute(proguard);\n }\n\n @NotNull\n @IgnoreUnused\n public String getPlatform() {\n return Require.nonNull(platform).displayName;\n }\n\n @NotNull\n public MoePlatform getPlatformType() {\n return Require.nonNull(platform);\n }\n\n @IgnoreUnused\n public void setPlatform(@NotNull String platform) {\n this.platform = MoePlatform.getForDisplayName(platform);\n }\n\n @NotNull\n @IgnoreUnused\n @Deprecated\n public String getProguardLevel() {\n LOG.warn(\"The 'getProguardLevel' is deprecated, please use 'proguard.level' instead!\");\n return proguard.getLevel();\n }\n\n @IgnoreUnused\n @Deprecated\n public void setProguardLevel(@NotNull String proguardLevel) {\n LOG.warn(\"The 'setProguardLevel' is deprecated, please use 'proguard.level' instead!\");\n proguard.setLevel(proguardLevel);\n }\n\n @Nullable\n public File getPlatformJar() {\n return plugin.getSDK().getPlatformJar(platform);\n }\n\n @Nullable\n public File getPlatformDex() {\n return plugin.getSDK().getPlatformDex(platform);\n }\n}",
"public class MoePlatform {\n @NotNull\n public final String displayName;\n\n @NotNull\n public final String platformName;\n\n @NotNull\n public final List<Arch> archs;\n\n @Nullable\n public final MoePlatform simulatorPlatform;\n\n private MoePlatform(@NotNull String displayName, @NotNull String platformName, @NotNull Arch[] archs,\n @Nullable MoePlatform simulatorPlatform) {\n this.displayName = Require.nonNull(displayName);\n this.platformName = Require.nonNull(platformName);\n this.archs = Collections.unmodifiableList(Arrays.asList(Require.sizeGT(archs, 0)));\n this.simulatorPlatform = simulatorPlatform;\n }\n\n /* NOTE: Unsupported but may be in the future\n public static final MoePlatform MACOS =\n new MoePlatform(\"macOS\", \"macosx\", new Arch[]{Arch.X86_64}, null);\n */\n\n private static final MoePlatform IOS_SIMULATOR =\n new MoePlatform(\"iOS Simulator\", \"iphonesimulator\", new Arch[]{Arch.X86_64, Arch.ARM64}, null);\n public static final MoePlatform IOS =\n new MoePlatform(\"iOS\", \"iphoneos\", new Arch[]{Arch.ARMV7, Arch.ARM64}, IOS_SIMULATOR);\n\n /* NOTE: Unsupported but may be in the future\n private static final MoePlatform TVOS_SIMULATOR =\n new MoePlatform(\"tvOS Simulator\", \"appletvsimulator\", new Arch[]{Arch.X86_64}, null);\n public static final MoePlatform TVOS =\n new MoePlatform(\"tvOS\", \"appletvos\", new Arch[]{Arch.ARM64}, TVOS_SIMULATOR);\n\n private static final MoePlatform WATCHOS_SIMULATOR =\n new MoePlatform(\"watchOS Simulator\", \"watchsimulator\", new Arch[]{Arch.I386}, null);\n public static final MoePlatform WATCHOS =\n new MoePlatform(\"watchOS\", \"watchos\", new Arch[]{Arch.ARMV7K}, WATCHOS_SIMULATOR);\n */\n\n private static final MoePlatform[] ROOT_PLATFORMS = new MoePlatform[]{\n /* NOTE: Unsupported but may be in the future\n MACOS,\n */\n IOS,\n /* NOTE: Unsupported but may be in the future\n TVOS,\n WATCHOS,\n */\n };\n\n public static final MoePlatform[] ALL_PLATFORMS = new MoePlatform[]{\n /* NOTE: Unsupported but may be in the future\n MACOS,\n */\n IOS,\n IOS_SIMULATOR,\n /* NOTE: Unsupported but may be in the future\n TVOS,\n TVOS_SIMULATOR,\n WATCHOS,\n WATCHOS_SIMULATOR,\n */\n };\n\n @NotNull\n public static MoePlatform getForDisplayName(@NotNull final String name) {\n Require.nonNull(name);\n\n for (MoePlatform platform : ROOT_PLATFORMS) {\n if (platform.displayName.equalsIgnoreCase(name)) {\n return platform;\n }\n if (platform.simulatorPlatform != null && platform.simulatorPlatform.displayName.equalsIgnoreCase(name)) {\n return platform.simulatorPlatform;\n }\n }\n throw new GradleException(\"Unknown platform '\" + name + \"', supported platforms are: \" +\n Arrays.stream(ROOT_PLATFORMS).map(x -> x.displayName).collect(Collectors.toList()));\n }\n\n @NotNull\n public static MoePlatform getForPlatformName(@NotNull final String name) {\n Require.nonNull(name);\n\n for (MoePlatform platform : ROOT_PLATFORMS) {\n if (platform.platformName.equalsIgnoreCase(name)) {\n return platform;\n }\n if (platform.simulatorPlatform != null && platform.simulatorPlatform.platformName.equalsIgnoreCase(name)) {\n return platform.simulatorPlatform;\n }\n }\n throw new GradleException(\"Unknown SDK name '\" + name + \"', supported platforms are: \" +\n Arrays.stream(ROOT_PLATFORMS).map(x -> x.platformName).collect(Collectors.toList()));\n }\n\n public boolean mainPlatformsHasSimulatorPair() {\n return /* this == MACOS ? false : */ true;\n }\n\n @Override\n public String toString() {\n return platformName;\n }\n\n public static List<MoePlatform> getSupportedTargetVariants(Arch archVariant) {\n List<MoePlatform> supported = new ArrayList<MoePlatform>();\n for (MoePlatform currentTarget : ALL_PLATFORMS) {\n for (Arch currentArch : currentTarget.archs) {\n if (archVariant == currentArch) {\n supported.add(currentTarget);\n }\n }\n }\n return supported;\n }\n}",
"public class MoePlugin extends AbstractMoePlugin {\n\n private static final Logger LOG = Logging.getLogger(MoePlugin.class);\n\n private static final String MOE_ARCHS_PROPERTY = \"moe.archs\";\n\n @NotNull\n private MoeExtension extension;\n\n @NotNull\n @Override\n public MoeExtension getExtension() {\n return Require.nonNull(extension, \"The plugin's 'extension' property was null\");\n }\n\n @Nullable\n private Server remoteServer;\n\n @Nullable\n public Server getRemoteServer() {\n return remoteServer;\n }\n\n @Nullable\n private Set<Arch> archs = null;\n\n @Nullable\n public Set<Arch> getArchs() {\n return archs;\n }\n\n @Inject\n public MoePlugin(Instantiator instantiator, ToolingModelBuilderRegistry registry) {\n super(instantiator, registry, false);\n }\n\n @Override\n public void apply(Project project) {\n super.apply(project);\n\n // Setup explicit archs\n String archsProp = PropertiesUtil.tryGetProperty(project, MOE_ARCHS_PROPERTY);\n if (archsProp != null) {\n archsProp = archsProp.trim();\n archs = Arrays.stream(archsProp.split(\",\"))\n .map(String::trim)\n .filter(it -> !it.isEmpty())\n .map(Arch::getForName)\n .collect(Collectors.toSet());\n\n if (archs.isEmpty()) {\n archs = null;\n }\n }\n\n // Setup remote build\n remoteServer = Server.setup(this);\n if (remoteServer != null) {\n remoteServer.connect();\n }\n\n // Create plugin extension\n extension = project.getExtensions().create(MOE, MoeExtension.class, this, instantiator);\n extension.setup();\n\n // Add common MOE dependencies\n installCommonDependencies();\n\n // Install rules\n addRule(ProGuard.class, \"Creates a ProGuarded jar.\",\n asList(SOURCE_SET, MODE), MoePlugin.this);\n addRule(ClassValidate.class, \"Validate classes.\",\n asList(SOURCE_SET, MODE), MoePlugin.this);\n addRule(Dex.class, \"Creates a Dexed jar.\",\n asList(SOURCE_SET, MODE), MoePlugin.this);\n addRule(Dex2Oat.class, \"Creates art and oat files.\",\n asList(SOURCE_SET, MODE, ARCH_FAMILY), MoePlugin.this);\n ResourcePackager.addRule(this);\n addRule(TestClassesProvider.class, \"Creates the classlist.txt file.\",\n asList(SOURCE_SET, MODE), MoePlugin.this);\n addRule(StartupProvider.class, \"Creates the preregister.txt file.\",\n asList(SOURCE_SET, MODE), MoePlugin.this);\n addRule(XcodeProvider.class, \"Collects the required dependencies.\",\n asList(SOURCE_SET, MODE, ARCH, PLATFORM), MoePlugin.this);\n addRule(XcodeInternal.class, \"Creates all files for Xcode.\",\n emptyList(), MoePlugin.this);\n addRule(XcodeBuild.class, \"Creates .app files.\",\n asList(SOURCE_SET, MODE, PLATFORM), MoePlugin.this);\n addRule(IpaBuild.class, \"Creates .ipa files.\",\n emptyList(), MoePlugin.this);\n addRule(GenerateUIObjCInterfaces.class, \"Creates a source file for Interface Builder\",\n singletonList(MODE), MoePlugin.this);\n addRule(NatJGen.class, \"Generate binding\",\n emptyList(), MoePlugin.this);\n addRule(UpdateXcodeSettings.class, \"Updates Xcode project settings\",\n emptyList(), MoePlugin.this);\n\n project.getTasks().create(\"moeSDKProperties\", task -> {\n task.setGroup(MOE);\n task.setDescription(\"Prints some properties of the MOE SDK.\");\n task.getActions().add(t -> {\n final File platformJar = extension.getPlatformJar();\n LOG.quiet(\"\\n\" +\n \"moe.sdk.home=\" + getSDK().getRoot() + \"\\n\" +\n \"moe.sdk.coreJar=\" + getSDK().getCoreJar() + \"\\n\" +\n \"moe.sdk.platformJar=\" + (platformJar == null ? \"\" : platformJar) + \"\\n\" +\n \"moe.sdk.junitJar=\" + getSDK().getiOSJUnitJar() + \"\\n\" +\n \"\\n\");\n });\n });\n project.getTasks().create(\"moeXcodeProperties\", task -> {\n task.setGroup(MOE);\n task.setDescription(\"Prints some properties of the MOE Xcode project.\");\n task.getActions().add(t -> {\n final StringBuilder b = new StringBuilder(\"\\n\");\n Optional.ofNullable(extension.xcode.getProject()).ifPresent(\n o -> b.append(\"moe.xcode.project=\").append(project.file(o).getAbsolutePath()).append(\"\\n\"));\n Optional.ofNullable(extension.xcode.getWorkspace()).ifPresent(\n o -> b.append(\"moe.xcode.workspace=\").append(project.file(o).getAbsolutePath()).append(\"\\n\"));\n Optional.ofNullable(extension.xcode.getMainTarget()).ifPresent(\n o -> b.append(\"moe.xcode.mainTarget=\").append(o).append(\"\\n\"));\n Optional.ofNullable(extension.xcode.getTestTarget()).ifPresent(\n o -> b.append(\"moe.xcode.testTarget=\").append(o).append(\"\\n\"));\n Optional.ofNullable(extension.xcode.getMainScheme()).ifPresent(\n o -> b.append(\"moe.xcode.mainScheme=\").append(o).append(\"\\n\"));\n Optional.ofNullable(extension.xcode.getTestScheme()).ifPresent(\n o -> b.append(\"moe.xcode.testScheme=\").append(o).append(\"\\n\"));\n b.append(\"\\n\");\n LOG.quiet(b.toString());\n });\n });\n\n Launchers.addTasks(this);\n }\n\n @SuppressWarnings(\"unchecked\")\n public static String getTaskName(@NotNull Class<?> taskClass, @NotNull Object... params) {\n Require.nonNull(taskClass);\n Require.nonNull(params);\n\n final String TASK_CLASS_NAME = taskClass.getSimpleName();\n final String ELEMENTS_DESC = Arrays.stream(params).map(TaskParams::getNameForValue).collect(Collectors.joining());\n\n return MOE + ELEMENTS_DESC + TASK_CLASS_NAME;\n }\n\n @SuppressWarnings(\"unchecked\")\n public <T extends AbstractBaseTask> T getTaskBy(@NotNull Class<T> taskClass, @NotNull Object... params) {\n return (T) getProject().getTasks().getByName(getTaskName(taskClass, params));\n }\n\n @SuppressWarnings(\"unchecked\")\n public <T extends Task> T getTaskByName(@NotNull String name) {\n Require.nonNull(name);\n\n return (T) getProject().getTasks().getByName(name);\n }\n\n public void requireMacHostOrRemoteServerConfig(@NotNull Task task) {\n Require.nonNull(task);\n if (!Os.isFamily(Os.FAMILY_MAC) && getRemoteServer() == null) {\n throw new GradleException(\"The '\" + task.getName() + \"' task requires a macOS host or a remote build configuration.\");\n }\n }\n\n @Override\n protected void checkRemoteServer(AbstractBaseTask task) {\n if (getRemoteServer() != null && task.getRemoteExecutionStatusSet()) {\n task.dependsOn(getRemoteServer().getMoeRemoteServerSetupTask());\n }\n }\n}",
"public class Server {\n\n private static final Logger LOG = Logging.getLogger(Server.class);\n\n private static final String MOE_REMOTEBUILD_DISABLE = \"moe.remotebuild.disable\";\n private static final String SDK_ROOT_MARK = \"REMOTE_MOE_SDK_ROOT___1234567890\";\n\n @NotNull\n final Session session;\n\n @NotNull\n private final MoePlugin plugin;\n\n @NotNull\n private final ServerSettings settings;\n\n @Nullable\n private String userHome;\n\n @NotNull\n public String getUserHome() {\n return Require.nonNull(userHome);\n }\n\n @Nullable\n private String userName;\n\n @NotNull\n public String getUserName() {\n return Require.nonNull(userName);\n }\n\n @Nullable\n private URI buildDir;\n\n @NotNull\n public URI getBuildDir() {\n return Require.nonNull(buildDir);\n }\n\n @Nullable\n private URI sdkDir;\n\n @NotNull\n public URI getSdkDir() {\n return Require.nonNull(sdkDir);\n }\n\n @Nullable\n private Task moeRemoteServerSetupTask;\n\n @NotNull\n public Task getMoeRemoteServerSetupTask() {\n return Require.nonNull(moeRemoteServerSetupTask);\n }\n\n private final ExecutorService executor = Executors.newFixedThreadPool(1);\n\n private Server(@NotNull JSch jsch, @NotNull Session session, @NotNull MoePlugin plugin, @NotNull ServerSettings settings) {\n Require.nonNull(jsch);\n this.session = Require.nonNull(session);\n this.plugin = Require.nonNull(plugin);\n this.settings = Require.nonNull(settings);\n\n this.userName = session.getUserName();\n\n final Project project = plugin.getProject();\n project.getGradle().buildFinished(new ConfigurationClosure<BuildResult>(project) {\n @Override\n public void doCall(BuildResult object) {\n if (!session.isConnected()) {\n return;\n }\n try {\n lockRemoteKeychain();\n } catch (Throwable e) {\n LOG.error(\"Failed to lock remote keychain\", e);\n }\n try {\n if (buildDir != null) {\n final ServerCommandRunner runner = new ServerCommandRunner(Server.this, \"cleanup\", \"\" +\n \"rm -rf '\" + getBuildDir() + \"'\");\n runner.setQuiet(true);\n runner.run();\n }\n } catch (Throwable e) {\n LOG.error(\"Failed to cleanup on remote server\", e);\n }\n disconnect();\n }\n });\n }\n\n @Nullable\n public static Server setup(@NotNull MoePlugin plugin) {\n Require.nonNull(plugin);\n\n ServerSettings settings = new ServerSettings(plugin);\n\n final Project project = plugin.getProject();\n project.getTasks().create(\"moeConfigRemote\", task -> {\n task.setGroup(MOE);\n task.setDescription(\"Starts an interactive remote server connection configurator and tester\");\n task.getActions().add(t -> {\n settings.interactiveConfig();\n });\n });\n project.getTasks().create(\"moeTestRemote\", task -> {\n task.setGroup(MOE);\n task.setDescription(\"Tests the connection to the remote server\");\n task.getActions().add(t -> {\n if (!settings.testConnection()) {\n throw new GradleException(\"Remote connection test failed\");\n }\n });\n });\n\n if (project.hasProperty(MOE_REMOTEBUILD_DISABLE)) {\n return null;\n }\n\n if (!settings.isConfigured()) {\n return null;\n }\n\n // Create session\n try {\n final JSch jsch = settings.getJSch();\n final Session session = settings.getJSchSession(jsch);\n return new Server(jsch, session, plugin, settings);\n } catch (JSchException e) {\n throw new GradleException(e.getMessage(), e);\n }\n }\n\n public void connect() {\n Require.nonNull(plugin);\n moeRemoteServerSetupTask = plugin.getProject().getTasks().create(\"moeRemoteServerSetup\", task -> {\n task.setGroup(MOE);\n task.setDescription(\"Sets up the SDK on the remote server\");\n task.getActions().add(t -> {\n\n if (session.isConnected()) {\n return;\n }\n try {\n session.connect();\n } catch (JSchException e) {\n throw new GradleException(e.getMessage(), e);\n }\n\n setupUserHome();\n setupBuildDir();\n prepareServerMOE();\n });\n });\n }\n\n private void prepareServerMOE() {\n final MoeSDK sdk = plugin.getSDK();\n\n final File gradlewZip = sdk.getGradlewZip();\n final FileList list = new FileList(gradlewZip.getParentFile(), getBuildDir());\n final String remoteGradlewZip = list.add(gradlewZip);\n upload(\"prepare - gradlew\", list);\n\n final String output = exec(\"install MOE SDK\", \"\" +\n \"cd \" + getBuildDir().getPath() + \" && \" +\n\n \"unzip \" + remoteGradlewZip + \" && \" +\n\n \"cd gradlew && \" +\n\n \"echo 'distributionBase=GRADLE_USER_HOME' >> gradle/wrapper/gradle-wrapper.properties && \" +\n \"echo 'distributionPath=wrapper/dists' >> gradle/wrapper/gradle-wrapper.properties && \" +\n \"echo 'zipStoreBase=GRADLE_USER_HOME' >> gradle/wrapper/gradle-wrapper.properties && \" +\n \"echo 'zipStorePath=wrapper/dists' >> gradle/wrapper/gradle-wrapper.properties && \" +\n \"echo 'distributionUrl=https\\\\://services.gradle.org/distributions/gradle-\" + plugin.getRequiredGradleVersion() + \"-bin.zip' >> gradle/wrapper/gradle-wrapper.properties && \" +\n\n \"echo 'buildscript {' >> build.gradle && \" +\n \"echo ' repositories {' >> build.gradle && \" +\n \"echo ' \" + settings.getGradleRepositories() + \"' >> build.gradle && \" +\n \"echo ' }' >> build.gradle && \" +\n \"echo ' dependencies {' >> build.gradle && \" +\n \"echo ' classpath group: \\\"org.multi-os-engine\\\", name: \\\"moe-gradle\\\", version: \\\"\" + sdk.pluginVersion + \"\\\"' >> build.gradle && \" +\n \"echo ' }' >> build.gradle && \" +\n \"echo '}' >> build.gradle && \" +\n \"echo '' >> build.gradle && \" +\n \"echo 'apply plugin: \\\"moe-sdk\\\"' >> build.gradle && \" +\n \"echo 'task printSDKRoot << { print \\\"\" + SDK_ROOT_MARK + \":${moe.sdk.root}\\\" }' >> build.gradle && \" +\n\n \"./gradlew printSDKRoot -s && \" +\n \"cd .. && rm -rf gradlew && rm -f gradlew.zip\"\n );\n final int start = output.indexOf(SDK_ROOT_MARK);\n Require.NE(start, -1, \"SDK_ROOT_MARK not found\");\n final int start2 = start + SDK_ROOT_MARK.length() + 1;\n try {\n sdkDir = new URI(\"file://\" + output.substring(start2, output.indexOf('\\n', start2)));\n } catch (URISyntaxException e) {\n throw new GradleException(e.getMessage(), e);\n }\n\n exec(\"check MOE SDK path\", \"[ -d '\" + sdkDir.getPath() + \"' ]\");\n }\n\n private void setupUserHome() {\n final ChannelExec channel;\n try {\n channel = (ChannelExec) session.openChannel(\"exec\");\n } catch (JSchException e) {\n throw new GradleException(e.getMessage(), e);\n }\n\n channel.setCommand(\"echo $HOME\");\n\n final ByteArrayOutputStream baos = new ByteArrayOutputStream();\n channel.setOutputStream(baos);\n\n try {\n channel.connect();\n } catch (JSchException e) {\n throw new GradleException(e.getMessage(), e);\n }\n\n while (!channel.isClosed()) {\n try {\n Thread.sleep(100);\n } catch (InterruptedException e) {\n throw new GradleException(e.getMessage(), e);\n }\n }\n\n channel.disconnect();\n if (channel.getExitStatus() != 0) {\n throw new GradleException(\"Failed to initialize connection with server\");\n }\n userHome = baos.toString().trim();\n LOG.quiet(\"MOE Remote Build - REMOTE_HOME=\" + getUserHome());\n }\n\n private void setupBuildDir() {\n final ChannelExec channel;\n try {\n channel = (ChannelExec) session.openChannel(\"exec\");\n } catch (JSchException e) {\n throw new GradleException(e.getMessage(), e);\n }\n\n channel.setCommand(\"mktemp -d\");\n\n final ByteArrayOutputStream baos = new ByteArrayOutputStream();\n channel.setOutputStream(baos);\n\n try {\n channel.connect();\n } catch (JSchException e) {\n throw new GradleException(e.getMessage(), e);\n }\n\n while (!channel.isClosed()) {\n try {\n Thread.sleep(100);\n } catch (InterruptedException e) {\n throw new GradleException(e.getMessage(), e);\n }\n }\n\n channel.disconnect();\n if (channel.getExitStatus() != 0) {\n throw new GradleException(\"Failed to initialize connection with server\");\n }\n try {\n buildDir = new URI(\"file://\" + baos.toString().trim());\n } catch (URISyntaxException e) {\n throw new GradleException(e.getMessage(), e);\n }\n LOG.quiet(\"MOE Remote Build - REMOTE_BUILD_DIR=\" + buildDir.getPath());\n }\n\n private void disconnect() {\n if (!session.isConnected()) {\n return;\n }\n session.disconnect();\n userHome = null;\n }\n\n private void assertConnected() {\n if (!session.isConnected()) {\n throw new GradleException(\"MOE Remote Build session in not connected\");\n }\n }\n\n public void upload(@NotNull String name, @NotNull FileList list) {\n assertConnected();\n new ServerFileUploader(this, name, list).run();\n }\n\n public void downloadFile(@NotNull String name, @NotNull String remoteFile, @NotNull File localOutputDir) {\n assertConnected();\n new ServerFileDownloader(this, name, remoteFile, localOutputDir, false).run();\n }\n\n public void downloadDirectory(@NotNull String name, @NotNull String remoteFile, @NotNull File localOutputDir) {\n assertConnected();\n new ServerFileDownloader(this, name, remoteFile, localOutputDir, true).run();\n }\n\n public String exec(@NotNull String name, @NotNull String command) {\n assertConnected();\n final ServerCommandRunner runner = new ServerCommandRunner(this, name, command);\n runner.run();\n return runner.getOutput();\n }\n\n public String getRemotePath(Path relative) {\n assertConnected();\n\n try {\n return getRemotePath(getBuildDir(), relative);\n } catch (IOException e) {\n throw new GradleException(e.getMessage(), e);\n }\n }\n\n public String getSDKRemotePath(@NotNull File file) throws IOException {\n Require.nonNull(file);\n\n final Path filePath = file.toPath().toAbsolutePath();\n final Path sdk = plugin.getSDK().getRoot().toPath().toAbsolutePath();\n\n if (!filePath.getRoot().equals(sdk.getRoot())) {\n throw new IOException(\"non-sdk file\");\n }\n\n final Path relative = sdk.relativize(filePath);\n return getRemotePath(getSdkDir(), relative);\n }\n\n public static String getRemotePath(@NotNull URI root, @NotNull Path relative) throws IOException {\n Require.nonNull(root);\n Require.nonNull(relative);\n\n if (relative.toString().contains(\"..\")) {\n throw new IOException(\"Relative path points to extenral directory: \" + relative);\n }\n\n ArrayList<String> comps = new ArrayList<>();\n for (Path path : relative) {\n comps.add(path.getFileName().toString());\n }\n\n try {\n return new URI(root.getPath() + \"/\" + comps.stream().collect(Collectors.joining(\"/\"))).getPath();\n } catch (URISyntaxException e) {\n throw new GradleException(e.getMessage(), e);\n }\n }\n\n public boolean checkFileMD5(String remotePath, @NotNull File localFile) {\n // Get local file md5\n final Future<String> localMD5Future = executor.submit(() -> {\n try {\n return DigestUtils.md5Hex(new FileInputStream(localFile));\n } catch (IOException ignore) {\n return null;\n }\n });\n\n // Get remote file md5\n assertConnected();\n final ServerCommandRunner runner = new ServerCommandRunner(this, \"check file md5\", \"\" +\n \"[ -f '\" + remotePath + \"' ] && md5 -q '\" + remotePath + \"'\");\n runner.setQuiet(true);\n try {\n runner.run();\n } catch (GradleException ignore) {\n return false;\n }\n final String remoteMD5 = runner.getOutput().trim();\n\n // Check equality\n final String localMD5;\n try {\n localMD5 = localMD5Future.get();\n } catch (InterruptedException | ExecutionException e) {\n throw new GradleException(e.getMessage(), e);\n }\n if (localMD5 == null) {\n return false;\n }\n return remoteMD5.compareToIgnoreCase(localMD5) == 0;\n }\n\n public void unlockRemoteKeychain() {\n assertConnected();\n\n final String kc_name = settings.getKeychainName();\n final String kc_pass = settings.getKeychainPass();\n final int kc_lock_to = settings.getKeychainLockTimeout();\n\n final ServerCommandRunner runner = new ServerCommandRunner(this, \"unlock keychain\", \"\" +\n \"security unlock-keychain -p '\" + kc_pass + \"' \" + kc_name + \" && \" +\n \"security set-keychain-settings -t \" + kc_lock_to + \" -l \" + kc_name);\n runner.setQuiet(true);\n runner.run();\n }\n\n private void lockRemoteKeychain() {\n assertConnected();\n\n final String kc_name = settings.getKeychainName();\n\n final ServerCommandRunner runner = new ServerCommandRunner(this, \"lock keychain\", \"\" +\n \"security lock-keychain \" + kc_name);\n runner.setQuiet(true);\n runner.run();\n }\n}",
"public class ServerChannelException extends RuntimeException {\n\n private final String output;\n\n public ServerChannelException(String message, String output) {\n super(message);\n this.output = output;\n }\n\n public ServerChannelException(String message, String output, Throwable cause) {\n super(message, cause);\n this.output = output;\n }\n\n public String getOutput() {\n return output;\n }\n}",
"public class FileList implements EntryParent {\n\n @NotNull\n private final Path localRoot;\n\n @NotNull\n private final URI target;\n\n @NotNull\n private final List<Entry> entries = new ArrayList<>();\n\n public FileList(@NotNull File localRoot, @NotNull URI target) {\n this.localRoot = Require.nonNull(localRoot.getAbsoluteFile().toPath());\n this.target = Require.nonNull(target);\n }\n\n public Path getLocalRoot() {\n return localRoot;\n }\n\n public URI getTarget() {\n return target;\n }\n\n public void walk(@NotNull Walker walker) {\n Require.nonNull(walker);\n\n try {\n for (Entry entry : entries) {\n entry.walk(walker);\n }\n } catch (IOException ex) {\n throw new GradleException(ex.getMessage(), ex);\n }\n }\n\n @Override\n public boolean isLast(Entry entry) {\n Require.TRUE(entries.contains(entry), \"unexpected state\");\n Require.sizeGT(entries, 0);\n return entries.indexOf(entry) == entries.size() - 1;\n }\n\n public String add(@NotNull File file) {\n return add(file, null);\n }\n\n public String add(@NotNull File file, @Nullable Set<File> excludes) {\n Require.nonNull(file);\n Require.TRUE(file.isAbsolute(), \"Internal error: file must be an absolute path\");\n\n final Set<Path> excls;\n if (excludes != null) {\n excls = excludes.stream()\n .map(x -> x.getAbsoluteFile().toPath())\n .collect(Collectors.toSet());\n } else {\n excls = Collections.emptySet();\n }\n\n // We only support files and directories\n if (!file.isFile() && !file.isDirectory()) {\n throw new GradleException(\"unknown file type \" + file.getAbsolutePath());\n }\n\n final File absoluteFile = file.getAbsoluteFile();\n if (file.isFile()) {\n addFile(absoluteFile);\n return resolveRemotePath(absoluteFile);\n\n } else if (file.isDirectory()) {\n final Path root = absoluteFile.toPath();\n try {\n Files.walkFileTree(root, new FileVisitor<Path>() {\n @Override\n public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {\n if (excls.contains(dir)) {\n return SKIP_SUBTREE;\n }\n\n final Path relativize = localRoot.relativize(dir);\n\n if (relativize.getNameCount() == 1 && relativize.getName(0).toString().length() == 0) {\n return CONTINUE;\n }\n\n getDirectory(relativize);\n return CONTINUE;\n }\n\n @Override\n public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {\n if (excls.contains(file)) {\n return CONTINUE;\n }\n addFile(file.toFile());\n return CONTINUE;\n }\n\n @Override\n public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {\n return TERMINATE;\n }\n\n @Override\n public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {\n return CONTINUE;\n }\n });\n } catch (IOException e) {\n throw new GradleException(e.getMessage(), e);\n }\n return resolveRemotePath(absoluteFile);\n\n } else {\n throw new IllegalStateException();\n }\n }\n\n private String resolveRemotePath(File absoluteFile) {\n final Path relative = localRoot.relativize(absoluteFile.toPath());\n try {\n return Server.getRemotePath(target, relative);\n } catch (IOException e) {\n throw new GradleException(e.getMessage(), e);\n }\n }\n\n private void addFile(@NotNull File absoluteFile) {\n // Get relative path\n final Path relativePath = localRoot.relativize(absoluteFile.toPath());\n\n Require.GT(relativePath.getNameCount(), 0, \"unexpected state - relativePath.namecount <= 0\");\n\n // Get entryParent and entries container\n List<Entry> entries = this.entries;\n EntryParent entryParent = this;\n if (relativePath.getNameCount() > 1) {\n final DirectoryEntry directory = getDirectory(relativePath.getParent());\n assert directory != null;\n entries = directory.entries;\n entryParent = directory;\n }\n\n // Add the file\n insertFileEntry(relativePath.getFileName().toString(), absoluteFile, entryParent, entries);\n }\n\n private static void insertFileEntry(@NotNull String name, @NotNull File localFile,\n @NotNull EntryParent parent, @NotNull List<Entry> entries) {\n Require.GT(name.length(), 0, \"unexpected state - rpath.filename.length <= 0\");\n final Entry entry = getEntry(entries, name);\n if (entry != null) {\n Require.TRUE(entry instanceof FileEntry, \"unexpected state - entry.class !~ FileEntry\");\n Require.TRUE(((FileEntry) entry).getLocalFile().equals(localFile), \"unexpected state - entry.localFile != localFile\");\n\n } else {\n entries.add(new FileEntry(name, parent, localFile));\n }\n }\n\n @Nullable\n private static Entry getEntry(@NotNull List<Entry> entries, @NotNull String name) {\n Require.nonNull(name);\n Require.nonNull(entries);\n\n return entries.stream().filter(entry -> entry.name.equals(name)).findFirst().orElse(null);\n }\n\n @Override\n public DirectoryEntry getEntry() {\n throw new IllegalStateException();\n }\n\n @Override\n public EntryParent getEntryParent() {\n return null;\n }\n\n private DirectoryEntry getDirectory(Path path) {\n return getDirectory(path, entries, this, 0);\n }\n\n private static DirectoryEntry getDirectory(Path path, List<Entry> entries, EntryParent entryParent, int idx) {\n final Path name = path.getName(idx);\n DirectoryEntry entry = (DirectoryEntry) getEntry(entries, name.getFileName().toString());\n if (entry == null) {\n entry = new DirectoryEntry(name.toString(), entryParent);\n entries.add(entry);\n }\n if (idx + 1 < path.getNameCount()) {\n return getDirectory(path, entry.entries, entry, idx + 1);\n }\n return entry;\n }\n}",
"public class Arch {\n @NotNull\n public final String name;\n\n @NotNull\n public final String family;\n\n private Arch(@NotNull String name, @NotNull String family) {\n this.name = Require.nonNull(name);\n this.family = Require.nonNull(family);\n }\n\n public static final String ARCH_ARMV7 = \"armv7\";\n public static final String ARCH_ARMV7S = \"armv7s\";\n public static final String ARCH_ARMV7K = \"armv7k\";\n public static final String ARCH_ARM64 = \"arm64\";\n public static final String ARCH_I386 = \"i386\";\n public static final String ARCH_X86_64 = \"x86_64\";\n\n public static final String FAMILY_ARM = \"arm\";\n public static final String FAMILY_ARM64 = \"arm64\";\n public static final String FAMILY_X86 = \"x86\";\n public static final String FAMILY_X86_64 = \"x86_64\";\n public static final String[] ALL_FAMILIES = new String[]{FAMILY_ARM, FAMILY_ARM64, FAMILY_X86, FAMILY_X86_64};\n\n public static final Arch ARMV7 = new Arch(ARCH_ARMV7, FAMILY_ARM);\n public static final Arch ARMV7S = new Arch(ARCH_ARMV7S, FAMILY_ARM);\n public static final Arch ARMV7K = new Arch(ARCH_ARMV7K, FAMILY_ARM);\n public static final Arch ARM64 = new Arch(ARCH_ARM64, FAMILY_ARM64);\n public static final Arch I386 = new Arch(ARCH_I386, FAMILY_X86);\n public static final Arch X86_64 = new Arch(ARCH_X86_64, FAMILY_X86_64);\n public static final Arch[] ALL_ARCHS = new Arch[]{ARMV7, ARMV7S, ARMV7K, ARM64, I386, X86_64};\n\n @NotNull\n public static Arch getForName(@NotNull String name) {\n Require.nonNull(name);\n\n for (Arch arch : ALL_ARCHS) {\n if (arch.name.equalsIgnoreCase(name)) {\n return arch;\n }\n }\n throw new GradleException(\"Unknown architecture '\" + name + \"', supported: \" +\n Arrays.stream(ALL_ARCHS).map(x -> x.name).collect(Collectors.toList()));\n }\n\n @NotNull\n public static String validateArchFamily(@NotNull String name) {\n Require.nonNull(name);\n\n for (String family : ALL_FAMILIES) {\n if (family.equalsIgnoreCase(name)) {\n return family;\n }\n }\n throw new GradleException(\"Unknown architecture family '\" + name + \"', supported: \" +\n Arrays.stream(ALL_ARCHS).map(x -> x.name).collect(Collectors.toList()));\n }\n\n @Override\n public String toString() {\n return name;\n }\n}",
"public class Mode {\n @NotNull\n public final String name;\n\n private Mode(@NotNull String name) {\n this.name = name;\n }\n\n public static final Mode DEBUG = new Mode(\"debug\");\n public static final Mode RELEASE = new Mode(\"release\");\n\n public static Mode getForName(@NotNull String name) {\n Require.nonNull(name);\n\n if (\"debug\".equalsIgnoreCase(name)) {\n return DEBUG;\n }\n if (\"release\".equalsIgnoreCase(name)) {\n return RELEASE;\n }\n throw new GradleException(\"Unknown configuration '\" + name + \"'\");\n }\n\n public static boolean validateName(@Nullable String name) {\n return \"debug\".equalsIgnoreCase(name) || \"release\".equalsIgnoreCase(name);\n }\n\n public String getXcodeCompatibleName() {\n if (this == DEBUG) {\n return \"Debug\";\n }\n if (this == RELEASE) {\n return \"Release\";\n }\n throw new GradleException(\"Unknown configuration '\" + name + \"'\");\n }\n}",
"public class Require {\n private Require() {\n\n }\n\n public static <T> T nonNull(T obj) {\n if (obj == null)\n throw new GradleException();\n return obj;\n }\n\n public static <T> T nullObject(T obj) {\n if (obj != null)\n throw new GradleException();\n return obj;\n }\n\n public static <T> T nonNull(T obj, String message) {\n if (message == null) {\n return nonNull(obj);\n }\n if (obj == null)\n throw new GradleException(message);\n return obj;\n }\n\n public static <T> T nullObject(T obj, String message) {\n if (message == null) {\n return nullObject(obj);\n }\n if (obj != null)\n throw new GradleException(message);\n return obj;\n }\n\n public static <T> T[] sizeEQ(T[] arrays, int other) {\n return EQ(arrays, nonNull(arrays).length, other, null);\n }\n\n public static <T> T[] sizeNE(T[] arrays, int other) {\n return NE(arrays, nonNull(arrays).length, other, null);\n }\n\n public static <T> T[] sizeLT(T[] arrays, int other) {\n return LT(arrays, nonNull(arrays).length, other, null);\n }\n\n public static <T> T[] sizeLE(T[] arrays, int other) {\n return LE(arrays, nonNull(arrays).length, other, null);\n }\n\n public static <T> T[] sizeGT(T[] arrays, int other) {\n return GT(arrays, nonNull(arrays).length, other, null);\n }\n\n public static <T> T[] sizeGE(T[] arrays, int other) {\n return GE(arrays, nonNull(arrays).length, other, null);\n }\n\n public static <T> T[] sizeEQ(T[] arrays, int other, String message) {\n return EQ(arrays, nonNull(arrays).length, other, message);\n }\n\n public static <T> T[] sizeNE(T[] arrays, int other, String message) {\n return NE(arrays, nonNull(arrays).length, other, message);\n }\n\n public static <T> T[] sizeLT(T[] arrays, int other, String message) {\n return LT(arrays, nonNull(arrays).length, other, message);\n }\n\n public static <T> T[] sizeLE(T[] arrays, int other, String message) {\n return LE(arrays, nonNull(arrays).length, other, message);\n }\n\n public static <T> T[] sizeGT(T[] arrays, int other, String message) {\n return GT(arrays, nonNull(arrays).length, other, message);\n }\n\n public static <T> T[] sizeGE(T[] arrays, int other, String message) {\n return GE(arrays, nonNull(arrays).length, other, message);\n }\n\n public static <T extends Collection> T sizeEQ(T coll, int other) {\n return EQ(coll, nonNull(coll).size(), other, null);\n }\n\n public static <T extends Collection> T sizeNE(T coll, int other) {\n return NE(coll, nonNull(coll).size(), other, null);\n }\n\n public static <T extends Collection> T sizeLT(T coll, int other) {\n return LT(coll, nonNull(coll).size(), other, null);\n }\n\n public static <T extends Collection> T sizeLE(T coll, int other) {\n return LE(coll, nonNull(coll).size(), other, null);\n }\n\n public static <T extends Collection> T sizeGT(T coll, int other) {\n return GT(coll, nonNull(coll).size(), other, null);\n }\n\n public static <T extends Collection> T sizeGE(T coll, int other) {\n return GE(coll, nonNull(coll).size(), other, null);\n }\n\n public static <T extends Collection> T sizeEQ(T coll, int other, String message) {\n return EQ(coll, nonNull(coll).size(), other, message);\n }\n\n public static <T extends Collection> T sizeNE(T coll, int other, String message) {\n return NE(coll, nonNull(coll).size(), other, message);\n }\n\n public static <T extends Collection> T sizeLT(T coll, int other, String message) {\n return LT(coll, nonNull(coll).size(), other, message);\n }\n\n public static <T extends Collection> T sizeLE(T coll, int other, String message) {\n return LE(coll, nonNull(coll).size(), other, message);\n }\n\n public static <T extends Collection> T sizeGT(T coll, int other, String message) {\n return GT(coll, nonNull(coll).size(), other, message);\n }\n\n public static <T extends Collection> T sizeGE(T coll, int other, String message) {\n return GE(coll, nonNull(coll).size(), other, message);\n }\n\n public static void EQ(int actual, int value, String message) {\n check(actual == value, null, message);\n }\n\n public static void NE(int actual, int value, String message) {\n check(actual != value, null, message);\n }\n\n public static void LT(int actual, int value, String message) {\n check(actual < value, null, message);\n }\n\n public static void LE(int actual, int value, String message) {\n check(actual <= value, null, message);\n }\n\n public static void GT(int actual, int value, String message) {\n check(actual > value, null, message);\n }\n\n public static void GE(int actual, int value, String message) {\n check(actual >= value, null, message);\n }\n\n public static <T> T EQ(T object, int actual, int value, String message) {\n return check(actual == value, object, message);\n }\n\n public static <T> T NE(T object, int actual, int value, String message) {\n return check(actual != value, object, message);\n }\n\n public static <T> T LT(T object, int actual, int value, String message) {\n return check(actual < value, object, message);\n }\n\n public static <T> T LE(T object, int actual, int value, String message) {\n return check(actual <= value, object, message);\n }\n\n public static <T> T GT(T object, int actual, int value, String message) {\n return check(actual > value, object, message);\n }\n\n public static <T> T GE(T object, int actual, int value, String message) {\n return check(actual >= value, object, message);\n }\n\n public static void TRUE(boolean actual, String message) {\n check(actual, null, message);\n }\n\n public static void FALSE(boolean actual, String message) {\n check(!actual, null, message);\n }\n\n public static <T> T check(boolean succeed, T object, String message) {\n if (succeed) {\n return object;\n }\n throw new GradleException(message);\n }\n}"
] | import com.dd.plist.NSDictionary;
import com.dd.plist.NSNumber;
import com.dd.plist.NSObject;
import com.dd.plist.PropertyListParser;
import org.gradle.api.GradleException;
import org.gradle.api.logging.LogLevel;
import org.gradle.api.logging.Logger;
import org.gradle.api.logging.Logging;
import org.gradle.api.tasks.Input;
import org.gradle.api.tasks.InputDirectory;
import org.gradle.api.tasks.Internal;
import org.gradle.api.tasks.Optional;
import org.gradle.api.tasks.OutputFile;
import org.gradle.api.tasks.SourceSet;
import org.gradle.api.tasks.compile.JavaCompile;
import org.moe.common.developer.ProvisioningProfile;
import org.moe.document.pbxproj.PBXNativeTarget;
import org.moe.document.pbxproj.PBXObject;
import org.moe.document.pbxproj.PBXObjectRef;
import org.moe.document.pbxproj.ProjectFile;
import org.moe.document.pbxproj.XCBuildConfiguration;
import org.moe.document.pbxproj.XCConfigurationList;
import org.moe.document.pbxproj.nextstep.Array;
import org.moe.document.pbxproj.nextstep.NextStep;
import org.moe.document.pbxproj.nextstep.Value;
import org.moe.gradle.MoeExtension;
import org.moe.gradle.MoePlatform;
import org.moe.gradle.MoePlugin;
import org.moe.gradle.anns.IgnoreUnused;
import org.moe.gradle.anns.NotNull;
import org.moe.gradle.anns.Nullable;
import org.moe.gradle.remote.Server;
import org.moe.gradle.remote.ServerChannelException;
import org.moe.gradle.remote.file.FileList;
import org.moe.gradle.utils.Arch;
import org.moe.gradle.utils.Mode;
import org.moe.gradle.utils.Require;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors; | return Require.nonNull(xcodeBuildSettings);
}
@Nullable
@Internal
public Map<String, String> getNullableXcodeBuildSettings() {
if (xcodeBuildSettings == null && getState().getSkipped()) {
this.xcodeBuildSettings = getCachedXcodeBuildSettings();
}
return xcodeBuildSettings;
}
@NotNull
@Internal
public Map<String, String> getCachedXcodeBuildSettings() {
Properties xcodeBuildSettingsP = new Properties();
try {
xcodeBuildSettingsP.load(new FileInputStream(getXcodeBuildSettingsFile()));
} catch (IOException e) {
throw new GradleException(e.getMessage(), e);
}
Map<String, String> xcodeBuildSettings = new HashMap<>();
xcodeBuildSettingsP.forEach((k, v) -> xcodeBuildSettings.put((String)k, (String)v));
return xcodeBuildSettings;
}
@Override
protected void run() {
getMoePlugin().requireMacHostOrRemoteServerConfig(this);
if (getXcodeWorkspaceFile() != null && getScheme() == null) {
String set = SourceSet.MAIN_SOURCE_SET_NAME.equals(sourceSet.getName()) ? "main" : "test";
throw new GradleException("Using Xcode workspaces requires schemes! Please set the "
+ "moe.xcode." + set + "Scheme property");
}
String scheme = getScheme();
if (scheme != null) {
generateSchemeIfNeeded(scheme);
}
final Server remoteServer = getMoePlugin().getRemoteServer();
final MoeExtension ext = getMoePlugin().getExtension();
if (remoteServer != null) {
remoteServer.unlockRemoteKeychain();
// Upload project
File projectDir = getProject().getParent() != null ? getProject().getParent().getProjectDir() : getProject().getProjectDir();
final FileList list = new FileList(projectDir, remoteServer.getBuildDir());
// Collect files we don't want to upload
final Set<File> excludes = new HashSet<>();
// Exclude some special paths
excludes.add(new File(getProject().getProjectDir(), "moe.remotebuild.properties"));
excludes.add(new File(getProject().getBuildDir(), "tmp"));
excludes.add(new File(getProject().getRootDir(), ".gradle"));
excludes.add(new File(getProject().getRootDir(), ".idea"));
// Exclude files from dependencies
for (XcodeProvider xcodeProvider : getXcodeProviderTaskDeps()) {
excludes.add(xcodeProvider.getLogFile());
excludes.add(resolvePathInBuildDir(xcodeProvider.getOutRoot()));
final Dex2Oat dex2OatTask = xcodeProvider.getDex2OatTaskDep();
excludes.add(dex2OatTask.getLogFile());
final Dex dexTask = dex2OatTask.getDexTaskDep();
excludes.add(dexTask.getDestJar());
excludes.add(dexTask.getLogFile());
final ClassValidate classValidateTask = dexTask.getClassValidateTaskDep();
excludes.add(classValidateTask.getOutputDir());
excludes.add(classValidateTask.getLogFile());
final ProGuard proGuardTask = classValidateTask.getProGuardTaskDep();
excludes.add(proGuardTask.getOutJar());
excludes.add(proGuardTask.getComposedCfgFile());
excludes.add(proGuardTask.getLogFile());
final JavaCompile classesTask = proGuardTask.getJavaCompileTaskDep();
if (classesTask != null) {
excludes.add(classesTask.getDestinationDir());
}
final StartupProvider startupProviderTask = xcodeProvider.getStartupProviderTaskDep();
excludes.add(startupProviderTask.getLogFile());
}
// Exclude files from "self"
excludes.add(getLogFile());
excludes.add(new File(getXcodeBuildRoot()));
excludes.add(getLocalSDKLink().toFile());
// TODO: exclude IPA
list.add(getProject().getProjectDir(), excludes);
remoteServer.upload("project files", list);
List<File> resources = ext.remoteBuildOptions.getResources();
if (resources != null && !resources.isEmpty()) {
uploadResources(remoteServer, projectDir, resources);
}
linkSDK();
final Path configurationBuildDirRel;
try {
configurationBuildDirRel = getInnerProjectRelativePath(getConfigurationBuildDir());
} catch (IOException e) {
throw new GradleException("Unsupported configuration", e);
}
try {
remoteServer.exec("xcodebuild", "xcrun --find xcodebuild && " +
"xcrun xcodebuild " + calculateArgs().stream().collect(Collectors.joining(" ")));
} catch (GradleException e) { | if (e.getCause() instanceof ServerChannelException) { | 4 |
fhissen/CrococryptFile | CrococryptFile WebDecrypt/src/org/crococryptfile/datafile/experimental/DumpReaderStreamonly.java | [
"public class DumpHeader {\r\n\tpublic static final int DUMPHEADER_VERSION = 1;\r\n\t\r\n\tprivate int ATTRIBUTE_VERSION = DUMPHEADER_VERSION;\r\n\tpublic long ATTRIBUTE_DUMPLEN;\r\n\tpublic long ATTRIBUTE_DUMPCOUNT;\r\n\t\r\n\tprivate Suite suite;\r\n\tprivate CipherMain ciph;\r\n\t\r\n\tpublic DumpHeader(Suite suite){\r\n\t\tthis.suite = suite;\r\n\t\tciph = suite.getCipher();\r\n\t}\r\n\t\r\n\tpublic void createOut(OutputStream out) throws IOException{\r\n\t\tbyte[] tmp;\r\n\t\t\r\n\t\ttmp = ByteUtils.fill(ATTRIBUTE_VERSION, CryptoCodes.STANDARD_BLOCKSIZE);\r\n\t\ttmp = Xor.xor(suite.getAlteredIV(2), tmp);\r\n\t\tout.write(ciph.doEnc_ECB(tmp));\r\n\t\t\r\n\t\ttmp = ByteUtils.fill(ATTRIBUTE_DUMPLEN, CryptoCodes.STANDARD_BLOCKSIZE);\r\n\t\ttmp = Xor.xor(suite.getAlteredIV(4), tmp);\r\n\t\tout.write(ciph.doEnc_ECB(tmp));\r\n\t\t\r\n\t\ttmp = ByteUtils.fill(ATTRIBUTE_DUMPCOUNT, CryptoCodes.STANDARD_BLOCKSIZE);\r\n\t\ttmp = Xor.xor(suite.getAlteredIV(6), tmp);\r\n\t\tout.write(ciph.doEnc_ECB(tmp));\r\n\t}\r\n\t\r\n\tpublic void readFrom(InputStream is) {\r\n\t\tbyte[] tmp;\r\n\t\tStreamMachine sm = new StreamMachine(is);\r\n\t\t\r\n\t\ttmp = sm.read(CryptoCodes.STANDARD_BLOCKSIZE);\r\n\t\tATTRIBUTE_VERSION = ByteUtils.bytesToObject(Xor.xor(ciph.doDec_ECB(tmp), suite.getAlteredIV(2)), ATTRIBUTE_VERSION);\r\n\r\n\t\ttmp = sm.read(CryptoCodes.STANDARD_BLOCKSIZE);\r\n\t\tATTRIBUTE_DUMPLEN = ByteUtils.bytesToObject(Xor.xor(ciph.doDec_ECB(tmp), suite.getAlteredIV(4)), ATTRIBUTE_DUMPLEN);\r\n\r\n\t\ttmp = sm.read(CryptoCodes.STANDARD_BLOCKSIZE);\r\n\t\tATTRIBUTE_DUMPCOUNT = ByteUtils.bytesToObject(Xor.xor(ciph.doDec_ECB(tmp), suite.getAlteredIV(6)), ATTRIBUTE_DUMPCOUNT);\r\n\t}\r\n\t\r\n\t\r\n\tpublic long getLen(){\r\n\t\treturn ATTRIBUTE_DUMPLEN;\r\n\t}\r\n\r\n\tpublic long getCount(){\r\n\t\treturn ATTRIBUTE_DUMPCOUNT;\r\n\t}\r\n\t\r\n\tpublic boolean isValid(){\r\n\t\treturn ATTRIBUTE_VERSION == DUMPHEADER_VERSION;\r\n\t}\r\n\t\r\n\tprivate final int len = 3 * CryptoCodes.STANDARD_BLOCKSIZE;\r\n\tpublic int headerLength(){\r\n\t\treturn len;\r\n\t}\r\n}\r",
"public class IndexEntry {\r\n\tpublic int ATTRIBUTE_NAMELEN;\r\n\tpublic byte[] ATTRIBUTE_NAME;\r\n\tpublic byte[] ATTRIBUTE_IV;\r\n\tpublic long ATTRIBUTE_MODIFIED;\r\n\tpublic long ATTRIBUTE_CREATED;\r\n\tpublic long ATTRIBUTE_SIZE;\r\n\tpublic long ATTRIBUTE_OFFSET;\r\n\tpublic long ATTRIBUTE_FSATTRIBUTES;\r\n\tpublic long ATTRIBUTE_OTHER;\r\n\t\r\n\tpublic void write(OutputStream os) throws IOException{\r\n\t\tif(ATTRIBUTE_NAME == null) throw new IOException(\"file name failure, no null filename allowed\");\r\n\t\tif(ATTRIBUTE_IV == null || ATTRIBUTE_IV.length != CryptoCodes.STANDARD_IVSIZE) throw new IOException(\"IV has wrong size!\");\r\n\t\t\r\n\t\tStreamMachine.write(os,\r\n\t\t\t\tATTRIBUTE_NAMELEN,\r\n\t\t\t\tATTRIBUTE_NAME,\r\n\t\t\t\tATTRIBUTE_IV,\r\n\t\t\t\tATTRIBUTE_MODIFIED,\r\n\t\t\t\tATTRIBUTE_CREATED,\r\n\t\t\t\tATTRIBUTE_SIZE,\r\n\t\t\t\tATTRIBUTE_OFFSET,\r\n\t\t\t\tATTRIBUTE_FSATTRIBUTES,\r\n\t\t\t\tATTRIBUTE_OTHER\r\n\t\t\t\t);\r\n\t}\r\n\t\r\n\tpublic static final IndexEntry readFrom(InputStream is) throws IOException{\r\n\t\tIndexEntry entry = new IndexEntry();\r\n\t\t\r\n\t\tbyte[] buffer_head = new byte[4]; \r\n\t\tStreamResult se = StreamMachine.read(is, buffer_head);\r\n\t\tif(se == StreamResult.EndOfStream) return null;\r\n\t\telse if(se == StreamResult.ReadException) throw new IOException();\r\n\t\t\r\n\t\ttry {\r\n\t\t\tentry.ATTRIBUTE_NAMELEN = ByteUtils.bytesToInt(buffer_head);\r\n\t\t\tentry.ATTRIBUTE_NAME = StreamMachine.read(is, entry.ATTRIBUTE_NAMELEN);\r\n\t\t\tentry.ATTRIBUTE_IV = StreamMachine.read(is, CryptoCodes.STANDARD_IVSIZE);\r\n\t\t\tentry.ATTRIBUTE_MODIFIED = StreamMachine.readO(is, entry.ATTRIBUTE_MODIFIED);\r\n\t\t\tentry.ATTRIBUTE_CREATED = StreamMachine.readO(is, entry.ATTRIBUTE_CREATED);\r\n\t\t\tentry.ATTRIBUTE_SIZE = StreamMachine.readO(is, entry.ATTRIBUTE_SIZE);\r\n\t\t\tentry.ATTRIBUTE_OFFSET = StreamMachine.readO(is, entry.ATTRIBUTE_OFFSET);\r\n\t\t\tentry.ATTRIBUTE_FSATTRIBUTES = StreamMachine.readO(is, entry.ATTRIBUTE_FSATTRIBUTES);\r\n\t\t\tentry.ATTRIBUTE_OTHER = StreamMachine.readO(is, entry.ATTRIBUTE_OTHER);\r\n\t\t} catch (Exception e) {\r\n\t\t\te.printStackTrace();\r\n\t\t\tthrow new IOException();\r\n\t\t}\r\n\t\t\r\n\t\treturn entry;\r\n\t}\r\n}\r",
"public abstract class Suite {\r\n\tprivate SuiteMODE mode;\r\n\tprivate StatusUpdate status;\r\n\tprivate boolean initialized = false;\r\n\t\r\n\tprotected Suite(){}\r\n\t\r\n\tpublic final void init(SuiteMODE mode, HashMap<SuitePARAM, Object> params, StatusUpdate status) throws IllegalArgumentException{\r\n\t\tif(mode == null) throw new IllegalArgumentException(\"no mode specified\");\r\n\t\t\r\n\t\tthis.status = status;\r\n\t\t_init(mode, params);\r\n\t\t\r\n\t\tthis.mode = mode;\r\n\t\tinitialized = true;\r\n\t}\r\n\t\r\n\tpublic SuiteMODE getMode(){\r\n\t\treturn mode;\r\n\t}\r\n\t\r\n\tpublic final void writeTo(OutputStream out) throws IllegalStateException{\r\n\t\tif(!initialized) throw new IllegalStateException(\"not initialized\");\r\n\t\tif(getMode() != SuiteMODE.ENCRYPT) throw new IllegalStateException(\"wrong mode\");\r\n\t\t\r\n\t\t_writeTo(out);\r\n\t}\r\n\t\r\n\tpublic final void readFrom(InputStream is) throws IllegalStateException{\r\n\t\tif(!initialized) throw new IllegalStateException(\"not initialized\");\r\n\t\tif(getMode() != SuiteMODE.DECRYPT) throw new IllegalStateException(\"wrong mode\");\r\n\t\t\r\n\t\t_readFrom(is);\r\n\t}\r\n\r\n\tabstract protected void _init(SuiteMODE mode, HashMap<SuitePARAM, Object> params) throws IllegalArgumentException;\r\n\tabstract protected void _writeTo(OutputStream out) throws IllegalStateException;\r\n\tabstract protected void _readFrom(InputStream is) throws IllegalStateException;\r\n\tabstract public CipherMain getCipher();\r\n\tabstract public byte[] getAttributeIV();\r\n\tabstract public int headerLength();\r\n\tabstract public void deinit();\r\n\t\r\n\tpublic final byte[] getAlteredIV(int add){\r\n\t\tadd = add % CryptoCodes.STANDARD_IVSIZE;\r\n\t\tbyte[] buf = Arrays.copyOf(getAttributeIV(), CryptoCodes.STANDARD_IVSIZE);\r\n\t\tbuf[add]++;\r\n\t\treturn buf;\r\n\t}\r\n\t\r\n\tprivate int len = -1;\r\n\tpublic final int suiteLength(){\r\n\t\tif(len < 0){\r\n\t\t\tlen = headerLength();\r\n\t\t\tif(!(this instanceof PBECloaked_AES2F_Main)) len += SUITES.MAGICNUMBER_LENGTH;\r\n\t\t}\r\n\t\treturn len;\r\n\t}\r\n\t\r\n\tpublic final StatusUpdate getStatus(){\r\n\t\treturn status;\r\n\t}\r\n\t\r\n\t\r\n\tpublic static final Suite getInstance(SUITES suite){\r\n\t\ttry {\r\n\t\t\treturn (Suite)(SUITES.classFromSuites(suite).newInstance());\r\n\t\t} catch (Exception e) {\r\n\t\t\tSystem.err.println(\"getInstance: \" + e.getLocalizedMessage());\r\n\t\t\treturn null;\t\r\n\t\t}\r\n\t}\r\n\r\n\tpublic static final Suite getInitializedInstance(SUITES suite, SuiteMODE mode, HashMap<SuitePARAM, Object> params, StatusUpdate status){\r\n\t\ttry {\r\n\t\t\tSuite instance = (Suite)(SUITES.classFromSuites(suite).newInstance());\r\n\t\t\tinstance.init(mode, params, status);\r\n\t\t\treturn instance;\r\n\t\t} catch (Exception e) {\r\n\t\t\te.printStackTrace();\r\n\t\t\tSystem.err.println(\"getInitializedInstance: \" + e.getLocalizedMessage());\r\n\t\t\treturn null;\t\r\n\t\t}\r\n\t}\r\n\t\r\n\t\r\n\tpublic static final void getInitializedInstanceAsync(final SUITES suite, final SuiteMODE mode,\r\n\t\t\tfinal HashMap<SuitePARAM, Object> params, final StatusUpdate status, final SuiteReceiver rec){\r\n\t\tif(rec == null){\r\n\t\t\tSystem.err.println(\"SuiteReceiver == null\");\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tif(suite == null){\r\n\t\t\tSystem.err.println(\"Requested SUITES == null\");\r\n\t\t\trec.receiveInitializedInstance(null);\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\r\n\t\tnew Thread(new Runnable() {\r\n\t\t\t@Override\r\n\t\t\tpublic void run() {\r\n\t\t\t\ttry {\r\n\t\t\t\t\tSuite instance = (Suite)(SUITES.classFromSuites(suite).newInstance());\r\n\t\t\t\t\tinstance.init(mode, params, status);\r\n\t\t\t\t\trec.receiveInitializedInstance(instance);\r\n\t\t\t\t} catch (Exception e) {\r\n\t\t\t\t\te.printStackTrace();\r\n\t\t\t\t\tSystem.err.println(\"getInitializedInstanceAsync: \" + e.getLocalizedMessage());\r\n\t\t\t\t\trec.receiveInitializedInstance(null);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}).start();\r\n\t}\r\n\t\r\n\t\r\n\tpublic static final Suite getInitializedInstance(SUITES suite, SuiteMODE mode, SuitePARAM aparam, Object avalue){\r\n\t\tHashMap<SuitePARAM, Object> params = new HashMap<>();\r\n\t\tparams.put(aparam, avalue);\r\n\t\treturn getInitializedInstance(suite, mode, params, null);\r\n\t}\r\n\t\r\n\r\n\tpublic interface SuiteReceiver{\r\n\t\tpublic void receiveInitializedInstance(Suite suite);\r\n\t}\r\n}\r",
"public enum _T {\r\n\tCAPIDNListWindow_nokeys,\r\n\tCAPIDNListWindow_title,\r\n\tCAPI_DNnotfound,\r\n\tCrocoFilereader_already,\r\n\tCrocoFilereader_decrypting,\r\n\tCrocoFilewriter_encrypting,\r\n\tDecryptWindow_already,\r\n\tDecryptWindow_cancel,\r\n\tDecryptWindow_destination,\r\n\tDecryptWindow_failedgeneral,\r\n\tDecryptWindow_failedspecific,\r\n\tDecryptWindow_folderisfile,\r\n\tDecryptWindow_folderreadonly,\r\n\tDecryptWindow_invalid,\r\n\tDecryptWindow_nofile,\r\n\tDecryptWindow_success,\r\n\tDecryptWindow_text,\r\n\tDecryptWindow_title,\r\n\tDecryptWindow_unknownfile,\r\n\tDecryptWindow_wrongversion,\r\n\tDecrypt_Start,\r\n\tEncryptListChoose,\r\n\tEncryptListChooseMulti,\r\n\tEncryptWindow_EncryptedFile,\r\n\tEncryptWindow_Multidir,\r\n\tEncryptWindow_Multifile,\r\n\tEncryptWindow_MultifileMultidir,\r\n\tEncryptWindow_MultifileSingledir,\r\n\tEncryptWindow_Singledir,\r\n\tEncryptWindow_Singlefile,\r\n\tEncryptWindow_SinglefileMultidir,\r\n\tEncryptWindow_SinglefileSingledir,\r\n\tEncryptWindow_already,\r\n\tEncryptWindow_alreadydir,\r\n\tEncryptWindow_cancel,\r\n\tEncryptWindow_createdir,\r\n\tEncryptWindow_destination,\r\n\tEncryptWindow_failedgeneral,\r\n\tEncryptWindow_failedspecific,\r\n\tEncryptWindow_folderreadonly,\r\n\tEncryptWindow_multisources,\r\n\tEncryptWindow_success,\r\n\tEncryptWindow_title,\r\n\tFileSelection_dec4cloak,\r\n\tFileSelection_dec4enc,\r\n\tFileSelection_selectbutton,\r\n\tFileSelection_title,\r\n\tFileSelection_title4cloak,\r\n\tFilepathFailure,\r\n\tGeneral_cancel,\r\n\tGeneral_done,\r\n\tGeneral_empty,\r\n\tGeneral_none,\r\n\tGeneral_open,\r\n\tGeneral_password,\r\n\tGeneral_quit,\r\n\tGeneral_synchronize,\r\n\tJCEPolicyError_title,\r\n\tJCEPolicyError_text,\r\n\tLauncher_jcepolicyerr,\r\n\tLauncher_reallyquit,\r\n\tPasswordDecrypt_title,\r\n\tPasswordEncrypt_label,\r\n\tPasswordEncrypt_len,\r\n\tPasswordEncrypt_nomatch,\r\n\tPasswordEncrypt_retype,\r\n\tPasswordEncrypt_itcount,\r\n\tPasswordEncrypt_itcountdescr,\r\n\tPasswordEncrypt_title,\r\n\tPassword_caps,\r\n\tPassword_PBEinProgress,\r\n\tPGP_errorNokey,\r\n\tPGP_errorSeckeyfailed,\r\n\tPGP_nokeyfile,\r\n\tPGP_novalidprivkey,\r\n\tPGP_privkey_wrongfile,\r\n\tPGP_privkeypasstitle,\r\n\tPGP_selprivkey,\r\n\tPGP_selprivkeyTitle,\r\n\tPGP_selpubkey,\r\n\tPBKDF2Interstep_start,\r\n\tPBKDF2Interstep_found,\r\n\tPBKDF2Interstep_steplong,\r\n\tSuite_CAPI_RSAAES,\r\n\tSuite_PBE1_AES,\r\n\tSuite_PBE1_TWOFISH,\r\n\tSuite_PBE1_SERPENT,\r\n\tSuite_PBE1_CAMELLIA,\r\n\tSuite_PGP_AES,\r\n\tSuite_PBECLOAKED_AESTWO,\r\n\tSuite_PBECLOAKED1MB_AESTWO,\r\n\r\n\t;\r\n\t\r\n\t\r\n\tprivate static ResourceBundle rb;\r\n\tstatic{\r\n\t\ttry {\r\n\t\t\trb = ResourceBundle.getBundle(ResourceCenter.getTexts() + \"text\", ResourceCenter.getLocale());\r\n\t\t} catch (Exception e) {\r\n\t\t\trb = ResourceBundle.getBundle(ResourceCenter.getTexts() + \"text\", Locale.ENGLISH);\r\n\t\t}\r\n\t}\r\n\t\r\n\t\r\n\tpublic String val(){\r\n\t\treturn rb.getString(name());\r\n\t}\r\n\t\r\n\tpublic String msg(Object... obj){\r\n\t\treturn MessageFormat.format(toString(), obj);\r\n\t}\r\n\t\r\n\t@Override\r\n\tpublic String toString() {\r\n\t\treturn val();\r\n\t};\r\n}\r",
"public class Codes {\r\n\tpublic static final String UTF8 = \"UTF-8\";\r\n\t\r\n\tpublic static final int ZIP_BUFFERSIZE = 1024*1024*4;\r\n}\r",
"public enum StreamResult{\r\n\tOK,\r\n\tEndOfStream,\r\n\tReadException,\r\n}\r",
"public interface StatusUpdate {\r\n\tpublic void start();\r\n\tpublic void finished();\r\n\tpublic boolean isActive();\r\n\tpublic void receiveMessageSummary(String msg);\r\n\tpublic void receiveMessageDetails(String msg);\r\n\tpublic void receiveProgress(int perc);\r\n\tpublic void receiveDetailsProgress(int perc);\r\n}\r"
] | import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.InflaterInputStream;
import org.crococryptfile.datafile.DumpHeader;
import org.crococryptfile.datafile.IndexEntry;
import org.crococryptfile.suites.Suite;
import org.crococryptfile.ui.resources._T;
import org.fhissen.utils.Codes;
import org.fhissen.utils.StreamMachine.StreamResult;
import org.fhissen.utils.ui.StatusUpdate;
| package org.crococryptfile.datafile.experimental;
public class DumpReaderStreamonly {
private StatusUpdate status;
private long max_len = 0;
private long offset = -1;
private ItemZipper dest = null;
private CountingBAInputStream dump = null;
private final byte[] buffer = new byte[1024 * 1024];
public DumpReaderStreamonly(long offset){
this.offset = offset;
}
public void setStatusReader(StatusUpdate status){
this.status = status;
}
| public void main(CountingBAInputStream src, ItemZipper dst, Suite dfile, DumpHeader dh) throws IOException, FileNotFoundException{
| 0 |
DataBiosphere/terra-cloud-resource-lib | google-billing/src/test/java/bio/terra/cloudres/google/billing/CloudBillingClientCowTest.java | [
"public static final String BILLING_ACCOUNT_NAME = \"billingAccounts/01A82E-CA8A14-367457\";",
"public class ProjectUtils {\n /** What parent resource (organization or folder) to create projects within. */\n // TODO(PF-67): Figure out how to pipe configuration to test.\n // Current value from vault 'config/terraform/terra/crl-test/default/container_folder_id'.\n public static final String PARENT_RESOURCE = \"folders/866104354540\";\n\n private static CloudResourceManagerCow managerCow;\n\n public static CloudResourceManagerCow getManagerCow() throws Exception {\n if (managerCow == null) {\n managerCow =\n CloudResourceManagerCow.create(\n IntegrationUtils.DEFAULT_CLIENT_CONFIG,\n IntegrationCredentials.getAdminGoogleCredentialsOrDie());\n }\n return managerCow;\n }\n\n /** Creates a new Google Project in GCP for testing. */\n public static Project executeCreateProject() throws Exception {\n Project project = new Project().setProjectId(randomProjectId()).setParent(PARENT_RESOURCE);\n Operation operation = getManagerCow().projects().create(project).execute();\n OperationCow<Operation> operationCow = managerCow.operations().operationCow(operation);\n OperationTestUtils.pollAndAssertSuccess(\n operationCow, Duration.ofSeconds(5), Duration.ofSeconds(60));\n return managerCow.projects().get(project.getProjectId()).execute();\n }\n\n public static String randomProjectId() {\n // Project ids must start with a letter and be no more than 30 characters long.\n return \"p\" + IntegrationUtils.randomName().substring(0, 29);\n }\n}",
"public class ServiceUsageCow {\n private final Logger logger = LoggerFactory.getLogger(ServiceUsageCow.class);\n\n private final ClientConfig clientConfig;\n private final OperationAnnotator operationAnnotator;\n private final ServiceUsage serviceUsage;\n\n public ServiceUsageCow(ClientConfig clientConfig, ServiceUsage.Builder serviceUsageBuilder) {\n this.clientConfig = clientConfig;\n operationAnnotator = new OperationAnnotator(clientConfig, logger);\n serviceUsage = serviceUsageBuilder.build();\n }\n\n /** Create a {@link ServiceUsageCow} with some default configurations for convenience. */\n public static ServiceUsageCow create(\n ClientConfig clientConfig, GoogleCredentials googleCredentials)\n throws GeneralSecurityException, IOException {\n return new ServiceUsageCow(\n clientConfig,\n new ServiceUsage.Builder(\n Defaults.httpTransport(),\n Defaults.jsonFactory(),\n new HttpCredentialsAdapter(\n googleCredentials.createScoped(ServiceUsageScopes.all())))\n .setApplicationName(clientConfig.getClientName()));\n }\n\n /** See {@link ServiceUsage#services}. */\n public Services services() {\n return new Services(serviceUsage.services());\n }\n\n /** See {@link ServiceUsage.Services}. */\n public class Services {\n private final ServiceUsage.Services services;\n\n private Services(ServiceUsage.Services services) {\n this.services = services;\n }\n\n /** See {@link ServiceUsage.Services#batchEnable(String, BatchEnableServicesRequest)}. */\n public BatchEnable batchEnable(String parent, BatchEnableServicesRequest content)\n throws IOException {\n return new BatchEnable(services.batchEnable(parent, content), content);\n }\n\n /** See {@link ServiceUsage.Services.BatchEnable}. */\n public class BatchEnable extends AbstractRequestCow<Operation> {\n private final ServiceUsage.Services.BatchEnable batchEnable;\n private final BatchEnableServicesRequest content;\n\n public BatchEnable(\n ServiceUsage.Services.BatchEnable batchEnable, BatchEnableServicesRequest content) {\n super(\n ServiceUsageOperation.GOOGLE_BATCH_ENABLE_SERVICES,\n clientConfig,\n operationAnnotator,\n batchEnable);\n this.batchEnable = batchEnable;\n this.content = content;\n }\n\n @Override\n protected JsonObject serialize() {\n JsonObject result = new JsonObject();\n result.addProperty(\"parent\", batchEnable.getParent());\n result.add(\"content\", new Gson().toJsonTree(content));\n return result;\n }\n }\n\n /** See {@link ServiceUsage.Services#list}. */\n public List list(String parent) throws IOException {\n return new List(services.list(parent));\n }\n\n /** See {@link ServiceUsage.Services.List}. */\n public class List extends AbstractRequestCow<ListServicesResponse> {\n private final ServiceUsage.Services.List list;\n\n private List(ServiceUsage.Services.List list) {\n super(ServiceUsageOperation.GOOGLE_LIST_SERVICES, clientConfig, operationAnnotator, list);\n this.list = list;\n }\n\n /** See {@link ServiceUsage.Services.List#setFilter}. */\n public List setFilter(String filter) {\n list.setFilter(filter);\n return this;\n }\n\n /** See {@link ServiceUsage.Services.List#setFields}. */\n public List setFields(String fields) {\n list.setFields(fields);\n return this;\n }\n\n @Override\n protected JsonObject serialize() {\n JsonObject result = new JsonObject();\n result.addProperty(\"parent\", list.getParent());\n result.addProperty(\"filter\", list.getFilter());\n result.addProperty(\"fields\", list.getFields());\n return result;\n }\n }\n }\n\n /** See {@link ServiceUsage#operations()}. */\n public Operations operations() {\n return new Operations(serviceUsage.operations());\n }\n\n /** See {@link ServiceUsage.Operations}. */\n public class Operations {\n private final ServiceUsage.Operations operations;\n\n private Operations(ServiceUsage.Operations operations) {\n this.operations = operations;\n }\n\n /** See {@link ServiceUsage.Operations#get(String)} */\n public Get get(String name) throws IOException {\n return new Get(operations.get(name));\n }\n\n public class Get extends AbstractRequestCow<Operation> {\n private final ServiceUsage.Operations.Get get;\n\n public Get(ServiceUsage.Operations.Get get) {\n super(\n ServiceUsageOperation.GOOGLE_SERVICE_USAGE_OPERATION_GET,\n clientConfig,\n operationAnnotator,\n get);\n this.get = get;\n }\n\n @Override\n protected JsonObject serialize() {\n JsonObject result = new JsonObject();\n result.addProperty(\"operation_name\", get.getName());\n return result;\n }\n }\n\n public OperationCow<Operation> operationCow(Operation operation) {\n return new OperationCow<>(\n operation, ServiceUsageOperationAdapter::new, op -> get(op.getName()));\n }\n }\n}",
"public class IntegrationCredentials {\n /**\n * Path to the admin service account credentials file.\n *\n * <p>The admin service account has the roles needed to operate the CRL APIs in the integration\n * test project, e.g. create and delete resources\n */\n private static final String GOOGLE_SERVICE_ACCOUNT_ADMIN_PATH =\n \"integration_service_account_admin.json\";\n\n /**\n * Path to the regular user service account credentials file.\n *\n * <p>The user service account doesn't have any permissions, but should be used as a test\n * non-admin user to reference\n */\n private static final String GOOGLE_SERVICE_ACCOUNT_USER_PATH =\n \"integration_service_account_user.json\";\n\n /**\n * Path to the janitor client service account credentials file to publish message to Janitor.\n *\n * <p>This service accounts generated by Terraform and pulled from vault.\n *\n * @see <a\n * href=https://github.com/broadinstitute/terraform-ap-deployments/blob/f26945d9d857e879f01671726188cecdc2d7fb10/terra-env/vault_crl_janitor.tf#L43>Terraform</a>\n * TODO(PF-67): Find solution for piping configs and secrets.\n */\n private static final String GOOGLE_SERVICE_ACCOUNT_JANITOR_CLIENT_PATH =\n \"integration_service_account_janitor_client.json\";\n\n public static ServiceAccountCredentials getAdminGoogleCredentialsOrDie() {\n return getGoogleCredentialsOrDie(GOOGLE_SERVICE_ACCOUNT_ADMIN_PATH);\n }\n\n public static ServiceAccountCredentials getUserGoogleCredentialsOrDie() {\n return getGoogleCredentialsOrDie(GOOGLE_SERVICE_ACCOUNT_USER_PATH);\n }\n\n public static ServiceAccountCredentials getJanitorClientGoogleCredentialsOrDie() {\n return getGoogleCredentialsOrDie(GOOGLE_SERVICE_ACCOUNT_JANITOR_CLIENT_PATH);\n }\n\n private static ServiceAccountCredentials getGoogleCredentialsOrDie(String serviceAccountPath) {\n try {\n return ServiceAccountCredentials.fromStream(\n Thread.currentThread().getContextClassLoader().getResourceAsStream(serviceAccountPath));\n } catch (Exception e) {\n throw new RuntimeException(\n \"Unable to load GoogleCredentials from \" + serviceAccountPath + \"\\n\", e);\n }\n }\n}",
"public class IntegrationUtils {\n private IntegrationUtils() {}\n\n public static final String DEFAULT_CLIENT_NAME = \"crl-integration-test\";\n\n // TODO(CA-874): Consider setting per-integration run environment variable for the cleanup id.\n // TODO(yonghao): Figure a better config pulling solution to replace the hardcoded configs.\n public static final CleanupConfig DEFAULT_CLEANUP_CONFIG =\n CleanupConfig.builder()\n .setTimeToLive(Duration.ofHours(2))\n .setCleanupId(\"crl-integration\")\n .setCredentials(IntegrationCredentials.getJanitorClientGoogleCredentialsOrDie())\n .setJanitorTopicName(\"crljanitor-tools-pubsub-topic\")\n .setJanitorProjectId(\"terra-kernel-k8s\")\n .build();\n\n public static final ClientConfig DEFAULT_CLIENT_CONFIG =\n ClientConfig.Builder.newBuilder()\n .setClient(DEFAULT_CLIENT_NAME)\n .setCleanupConfig(DEFAULT_CLEANUP_CONFIG)\n .build();\n\n /** Generates a random name to use for a cloud resource. */\n public static String randomName() {\n return UUID.randomUUID().toString();\n }\n\n /** Generates a random name to and replace '-' with '_'. */\n public static String randomNameWithUnderscore() {\n return UUID.randomUUID().toString().replace('-', '_');\n }\n\n /**\n * Sets longer timeout because some operation(e.g. Dns.ManagedZones.Create) may take longer than\n * default timeout. We pass a {@link HttpRequestInitializer} to accept a requestInitializer to\n * allow chaining, since API clients have exactly one initializer and credentials are typically\n * required as well.\n */\n public static HttpRequestInitializer setHttpTimeout(\n final HttpRequestInitializer requestInitializer) {\n return httpRequest -> {\n requestInitializer.initialize(httpRequest);\n httpRequest.setConnectTimeout(5 * 60000); // 5 minutes connect timeout\n httpRequest.setReadTimeout(5 * 60000); // 5 minutes read timeout\n };\n }\n}"
] | import static bio.terra.cloudres.google.billing.testing.CloudBillingUtils.BILLING_ACCOUNT_NAME;
import static org.junit.jupiter.api.Assertions.*;
import bio.terra.cloudres.google.cloudresourcemanager.testing.ProjectUtils;
import bio.terra.cloudres.google.serviceusage.ServiceUsageCow;
import bio.terra.cloudres.testing.IntegrationCredentials;
import bio.terra.cloudres.testing.IntegrationUtils;
import com.google.api.services.cloudresourcemanager.v3.model.Project;
import com.google.cloud.billing.v1.ProjectBillingInfo;
import java.io.IOException;
import java.security.GeneralSecurityException;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test; | package bio.terra.cloudres.google.billing;
@Tag("integration")
public class CloudBillingClientCowTest {
private static final String BILLING_SERVICE_ID = "cloudbilling.googleapis.com";
private static CloudBillingClientCow defaultBillingCow() throws IOException {
return new CloudBillingClientCow(
IntegrationUtils.DEFAULT_CLIENT_CONFIG,
IntegrationCredentials.getAdminGoogleCredentialsOrDie());
}
private static ServiceUsageCow defaultServiceUsage()
throws GeneralSecurityException, IOException {
return ServiceUsageCow.create(
IntegrationUtils.DEFAULT_CLIENT_CONFIG,
IntegrationCredentials.getAdminGoogleCredentialsOrDie());
}
@Test
public void getSetProjectBillingInfo() throws Exception {
Project project = ProjectUtils.executeCreateProject();
try (CloudBillingClientCow billingCow = defaultBillingCow()) {
ProjectBillingInfo initialBilling =
billingCow.getProjectBillingInfo("projects/" + project.getProjectId());
assertEquals(project.getProjectId(), initialBilling.getProjectId());
assertEquals("", initialBilling.getBillingAccountName());
ProjectBillingInfo setBilling = | ProjectBillingInfo.newBuilder().setBillingAccountName(BILLING_ACCOUNT_NAME).build(); | 0 |
trygvis/javax-usb-libusb1 | usbtools/src/main/java/io/trygvis/usb/tools/Fx2Programmer.java | [
"public class Fx2Device implements Closeable {\n public static final short CPUCS = (short) 0xE600;\n public static final short FX2_ID_VENDOR = 0x04b4;\n public static final short FX2_ID_PRODUCT = (short) 0x8613;\n\n private final UsbDevice device;\n\n public static Fx2Device findFx2Device(UsbHub hub) throws UsbException {\n UsbDevice device = ExtraUsbUtil.findUsbDevice(hub, FX2_ID_VENDOR, FX2_ID_PRODUCT);\n\n if (device == null) {\n return null;\n }\n\n return new Fx2Device(device/*, null*/);\n }\n\n public Fx2Device(UsbDevice device/*, UsbInterface usbInterface*/) {\n if (device == null) {\n throw new NullPointerException(\"device\");\n }\n\n this.device = device;\n }\n\n public void close() throws IOException {\n }\n\n public void setReset() throws UsbException {\n System.err.println(\"Fx2Device.setReset\");\n // TODO: Read the value first before manipulating the value\n write(CPUCS, new byte[]{0x01});\n }\n\n public void releaseReset() throws UsbException {\n System.err.println(\"Fx2Device.releaseReset\");\n // TODO: Read the value first before manipulating the value\n write(CPUCS, new byte[]{0x00});\n }\n\n public void write(int address, byte[] bytes) throws UsbException {\n write(address, bytes, 0, bytes.length);\n }\n\n public void write(int address, byte[] bytes, int offset, int length) throws UsbException {\n // System.err.println(\"Fx2Device.write: address=\" + toHexString((short)address) + \", bytes=\" + length);\n byte bmRequestType = 0x40; // Vendor request, IN\n byte bRequest = (byte) 0xa0;\n short wValue = (short) address;\n short wIndex = 0;\n UsbControlIrp irp = device.createUsbControlIrp(bmRequestType, bRequest, wValue, wIndex);\n irp.setData(bytes);\n irp.setOffset(offset);\n irp.setLength(length);\n device.syncSubmit(irp);\n }\n\n public byte[] read(int address, int count) throws UsbException {\n // System.err.println(\"Fx2Device.read: address=\" + toHexString(address) + \", count=\" + count);\n byte bmRequestType = (byte) 0xc0; // Vendor request, OUT\n byte bRequest = (byte) 0xa0;\n short wValue = (short) address;\n short wIndex = 0;\n byte[] bytes = new byte[count];\n device.syncSubmit(new DefaultUsbControlIrp(bytes, 0, count, true, bmRequestType, bRequest, wValue, wIndex));\n\n return bytes;\n }\n\n public OutputStream toOutputStream() {\n return new OutputStream() {\n int address = 0;\n\n @Override\n public void write(byte[] bytes, int offset, int length) throws IOException {\n try {\n Fx2Device.this.write(address, bytes, offset, length);\n address += length;\n } catch (UsbException e) {\n throw new IOException(e.getMessage());\n }\n }\n\n @Override\n public void write(int b) throws IOException {\n try {\n Fx2Device.this.write(address, new byte[]{(byte) b});\n address++;\n } catch (UsbException e) {\n throw new IOException(e.getMessage());\n }\n }\n };\n }\n}",
"public class IntelHex {\n public static List<IntelHexPacket> openIntelHexFile(final File file) throws IOException {\n return openIntelHexFile(new FileInputStream(file));\n }\n\n public static List<IntelHexPacket> openIntelHexFile(final InputStream is) throws IOException {\n final BufferedReader reader = new BufferedReader(new InputStreamReader(is, \"ascii\"));\n String line = reader.readLine();\n\n if (line == null) {\n throw new IOException(\"The Intel hex file must contain at least one line\");\n }\n\n IntelHexPacket packet = parseLine(0, line);\n\n List<IntelHexPacket> list = new ArrayList<IntelHexPacket>();\n\n while (true) {\n list.add(packet);\n\n line = reader.readLine();\n if (line == null) {\n break;\n }\n\n packet = parseLine(packet.lineNo, line);\n }\n\n return list;\n }\n\n public static enum RecordType {\n DATA(0),\n END_OF_FILE(1);\n //EXTENDED_SEGMENT_ADDRESS_RECORD,\n //START_SEGMENT_ADDRESS_RECORD,\n //EXTENDED_LINEAR_ADDRESS_RECORD,\n //START_LINEAR_ADDRESS_RECORD;\n\n byte id;\n\n RecordType(int id) {\n this.id = (byte)id;\n }\n\n public static RecordType lookup(int i) throws IOException {\n for (RecordType recordType : values()) {\n if (recordType.id == i) {\n return recordType;\n }\n }\n\n throw new IOException(\"Unknown record type: \" + i + \".\");\n }\n }\n\n public static class IntelHexPacket {\n public final int lineNo;\n public final RecordType recordType;\n public final int address;\n public final byte[] data;\n\n public IntelHexPacket(int lineNo, RecordType recordType, int address, byte[] data) {\n this.lineNo = lineNo;\n this.recordType = recordType;\n this.address = address;\n this.data = data;\n }\n }\n\n public static String createLine(RecordType recordType, int address, byte[] data) {\n if(recordType != DATA && recordType != END_OF_FILE) {\n throw new RuntimeException(\"Un-supported record type: \" + recordType + \".\");\n }\n\n StringBuilder builder = new StringBuilder(9 + data.length * 2);\n builder.append(':')\n .append(UsbUtil.toHexString((byte) data.length))\n .append(UsbUtil.toHexString((short) address))\n .append('0')\n .append(recordType.id);\n\n int checksum = (byte) data.length + (short) address + recordType.id;\n\n for (byte b : data) {\n builder.append(UsbUtil.toHexString(b));\n checksum += b;\n }\n\n return builder.append(UsbUtil.toHexString((byte) -(checksum & 0xff))).toString().toUpperCase();\n }\n\n public static IntelHexPacket parseLine(int lineNo, String line) throws IOException {\n if (line.length() < 9) {\n throw new IOException(\"line \" + lineNo + \": the line must contain at least 9 characters.\");\n }\n lineNo++;\n\n char startCode = line.charAt(0);\n int count = parseInt(line.substring(1, 3), 16);\n int address = parseInt(line.substring(3, 7), 16);\n int r = parseInt(line.substring(7, 9), 16);\n\n if (startCode != ':') {\n throw new IOException(\"line \" + lineNo + \": The first character must be ':'.\");\n }\n\n RecordType recordType = lookup(r);\n\n if (recordType == DATA) {\n int expectedLineLength = 9 + count * 2 + 2;\n if (line.length() != expectedLineLength) {\n throw new IOException(\"line \" + lineNo + \": Expected line to be \" + expectedLineLength + \" characters, was \" + line.length() + \".\");\n }\n\n byte data[] = new byte[count];\n\n int x = 9;\n for (int i = 0; i < count; i++) {\n data[i] = (byte) parseInt(line.substring(x, x + 2), 16);\n x += 2;\n }\n\n return new IntelHexPacket(lineNo, recordType, address, data);\n }\n else if(recordType == END_OF_FILE) {\n return new IntelHexPacket(lineNo, recordType, address, new byte[0]);\n }\n\n throw new IOException(\"line \" + lineNo + \": Unknown record type: 0x\" + Long.toHexString(r) + \".\");\n }\n}",
"public static enum RecordType {\n DATA(0),\n END_OF_FILE(1);\n //EXTENDED_SEGMENT_ADDRESS_RECORD,\n //START_SEGMENT_ADDRESS_RECORD,\n //EXTENDED_LINEAR_ADDRESS_RECORD,\n //START_LINEAR_ADDRESS_RECORD;\n\n byte id;\n\n RecordType(int id) {\n this.id = (byte)id;\n }\n\n public static RecordType lookup(int i) throws IOException {\n for (RecordType recordType : values()) {\n if (recordType.id == i) {\n return recordType;\n }\n }\n\n throw new IOException(\"Unknown record type: \" + i + \".\");\n }\n}",
"public static List<IntelHexPacket> openIntelHexFile(final File file) throws IOException {\n return openIntelHexFile(new FileInputStream(file));\n}",
"public class UsbCliUtil {\n\n /**\n * Tries to find a device with either the id given or the vendor/product id given.\n * <p/>\n * This method will use stdout/stderr to print error messages so no messages should be\n *\n * @return Returns null if no device could be found.\n */\n public static UsbDevice findDevice(UsbHub hub, Short idVendor, Short idProduct, String id) {\n // TODO: Parse out --id=VVVV.PPPP[.N] and --device=[device path]\n\n if (id != null) {\n int i = id.indexOf(':');\n if (i == 4) {\n // this is an id on the form VVVV.PPPP\n idVendor = (short) parseInt(id.substring(0, 4), 16);\n idProduct = (short) parseInt(id.substring(5, 9), 16);\n\n id = null;\n }\n }\n\n if (id != null) {\n // As this library is implemented with libusb which returns\n // everything in a single, flat list for now just do this simple search.\n\n int index;\n try {\n index = parseInt(id);\n } catch (NumberFormatException e) {\n System.err.println(\"Invalid 'id' parameter, has to be an integer.\");\n return null;\n }\n\n List<UsbDevice> devices = hub.getAttachedUsbDevices();\n\n if (index >= devices.size() || index < 0) {\n System.err.println(\"'id' parameter is out of range.\");\n return null;\n }\n\n return devices.get(index);\n } else if (idProduct != null && idVendor != null) {\n UsbDevice usbDevice = findUsbDevice(hub, idVendor, idProduct);\n\n if (usbDevice == null) {\n System.err.println(\"Could not find device with id \" + deviceIdToString(idVendor, idProduct) + \".\");\n }\n\n return usbDevice;\n }\n return null;\n }\n\n public static void listDevices(UsbHub hub, short idVendor, short idProduct) {\n listDevices(\"0\", hub, idVendor, idProduct);\n }\n\n private static void listDevices(String prefix, UsbHub hub, short idVendor, short idProduct) {\n List<UsbDevice> list = hub.getAttachedUsbDevices();\n for (int i = 0; i < list.size(); i++) {\n UsbDevice device = list.get(i);\n if (device.isUsbHub()) {\n listDevices(prefix + \".\" + i, (UsbHub) device, idVendor, idProduct);\n } else {\n UsbDeviceDescriptor deviceDescriptor = device.getUsbDeviceDescriptor();\n\n System.err.print(prefix + \".\" + i + \" \" + toHexString(deviceDescriptor.idVendor()) + \":\" + toHexString(deviceDescriptor.idProduct()));\n\n if (isUsbDevice(deviceDescriptor, idVendor, idProduct)) {\n System.err.print(\" (Unconfigured FX2)\");\n }\n System.err.println();\n }\n }\n }\n}"
] | import static java.lang.Thread.*;
import static java.util.Arrays.*;
import static io.trygvis.usb.tools.Fx2Device.*;
import io.trygvis.usb.tools.IntelHex.*;
import static io.trygvis.usb.tools.IntelHex.RecordType.*;
import static io.trygvis.usb.tools.IntelHex.openIntelHexFile;
import static io.trygvis.usb.tools.UsbCliUtil.*;
import javax.usb.*;
import java.io.*;
import java.util.ArrayList;
import java.util.*; | package io.trygvis.usb.tools;
public class Fx2Programmer {
public static void main(String[] a) throws Exception {
UsbServices usbServices = UsbHostManager.getUsbServices();
UsbHub hub = usbServices.getRootUsbHub();
short idVendor = FX2_ID_VENDOR;
short idProduct = FX2_ID_PRODUCT;
String id = null;
List<String> args = new ArrayList<String>(asList(a));
Iterator<String> it = args.iterator();
while (it.hasNext()) {
String arg = it.next();
if (arg.equals("--list")) {
listDevices(hub, idVendor, idProduct);
break;
} else if (arg.startsWith("--id=")) {
id = arg.substring(5);
it.remove();
} else {
UsbDevice usbDevice = findDevice(hub, idVendor, idProduct, id);
if (usbDevice == null) {
return;
}
commandPhase(usbDevice, args);
break;
}
}
}
private static void commandPhase(UsbDevice usbDevice, List<String> args) throws Exception {
| Fx2Device fx2 = new Fx2Device(usbDevice); | 0 |
coding4people/mosquito-report-api | src/main/java/com/coding4people/mosquitoreport/api/controllers/AuthFacebookController.java | [
"public class AuthenticationService {\n @Inject\n Env env;\n\n public String generateToken(String userGuid) {\n return Base64.getEncoder().encodeToString(\n (userGuid + '.' + BCrypt.hashpw(env.get(\"SECRET\").orElse(\"\") + userGuid, BCrypt.gensalt(12)))\n .getBytes());\n }\n\n public String identify(String token) {\n final String raw;\n\n try {\n raw = new String(Base64.getDecoder().decode(token));\n } catch (Throwable t) {\n throw new ForbiddenException(\"Invalid authorization token\");\n }\n\n if (raw.length() <= 37) {\n throw new ForbiddenException(\"Invalid authorization token\");\n }\n\n String guid = raw.substring(0, 36);\n String hash = raw.substring(37);\n\n boolean valid;\n\n try {\n valid = BCrypt.checkpw(env.get(\"SECRET\").orElse(\"\") + guid, hash);\n } catch (IllegalArgumentException e) {\n throw new ForbiddenException(\"Invalid authorization token\");\n }\n\n if (!valid) {\n throw new ForbiddenException(\"Invalid authorization token\");\n }\n\n return guid;\n }\n}",
"@DynamoDBTable(tableName = \"email\")\npublic class Email {\n @DynamoDBHashKey\n private String email;\n \n @DynamoDBAttribute\n private String userguid;\n \n @DynamoDBAttribute\n @JsonIgnore\n private String password;\n\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n public String getUserguid() {\n return userguid;\n }\n\n public void setUserguid(String userguid) {\n this.userguid = userguid;\n }\n\n public String getPassword() {\n return password;\n }\n\n public void setPassword(String password) {\n this.password = password;\n }\n \n public static String encryptPassword(String rawPassword) {\n return BCrypt.hashpw(rawPassword, BCrypt.gensalt(12));\n }\n \n public static boolean checkPassword(String rawPassword, String password) {\n if(null == password || !password.startsWith(\"$2a$\")) {\n throw new IllegalArgumentException(\"Invalid hash provided for comparison\");\n }\n \n return BCrypt.checkpw(rawPassword, password);\n }\n}",
"@DynamoDBTable(tableName = \"facebookuser\")\npublic class FacebookUser {\n @DynamoDBHashKey\n private String token;\n \n @DynamoDBAttribute\n private String userguid;\n \n @DynamoDBAttribute\n private String id;\n \n @DynamoDBAttribute\n private String location;\n \n @DynamoDBAttribute\n private String link;\n\n public String getToken() {\n return token;\n }\n\n public void setToken(String token) {\n this.token = token;\n }\n\n public String getUserguid() {\n return userguid;\n }\n\n public void setUserguid(String userguid) {\n this.userguid = userguid;\n }\n\n public String getId() {\n return id;\n }\n\n public void setId(String id) {\n this.id = id;\n }\n\n public String getLocation() {\n return location;\n }\n\n public void setLocation(String location) {\n this.location = location;\n }\n\n public String getLink() {\n return link;\n }\n\n public void setLink(String link) {\n this.link = link;\n }\n}",
"@DynamoDBTable(tableName = \"user\")\npublic class User {\n @DynamoDBHashKey\n private String guid;\n \n @DynamoDBAttribute\n private String email;\n \n @DynamoDBAttribute\n private String firstname;\n \n @DynamoDBAttribute\n private String lastname;\n \n @DynamoDBAttribute\n private String location;\n \n @DynamoDBAttribute\n private String facebookurl;\n \n @DynamoDBAttribute\n private String twitter;\n \n @DynamoDBAttribute\n private String profilepictureguid;\n\n public String getGuid() {\n return guid;\n }\n\n public void setGuid(String guid) {\n this.guid = guid;\n }\n\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n public String getFirstname() {\n return firstname;\n }\n\n public void setFirstname(String firstname) {\n this.firstname = firstname;\n }\n\n public String getLastname() {\n return lastname;\n }\n\n public void setLastname(String lastname) {\n this.lastname = lastname;\n }\n\n public String getLocation() {\n return location;\n }\n\n public void setLocation(String location) {\n this.location = location;\n }\n\n public String getFacebookurl() {\n return facebookurl;\n }\n\n public void setFacebookurl(String facebookurl) {\n this.facebookurl = facebookurl;\n }\n\n public String getTwitter() {\n return twitter;\n }\n\n public void setTwitter(String twitter) {\n this.twitter = twitter;\n }\n\n public String getProfilepictureguid() {\n return profilepictureguid;\n }\n\n public void setProfilepictureguid(String profilepictureguid) {\n this.profilepictureguid = profilepictureguid;\n }\n}",
"@Singleton\npublic class EmailRepository extends Repository<Email> {\n @Override\n protected Class<Email> getType() {\n return Email.class;\n }\n}",
"@Singleton\npublic class FacebookUserRepository extends Repository<FacebookUser> {\n @Override\n protected Class<FacebookUser> getType() {\n return FacebookUser.class;\n }\n}",
"@Singleton\npublic class UserRepository extends Repository<User> {\n @Override\n protected Class<User> getType() {\n return User.class;\n }\n}"
] | import java.util.UUID;
import javax.inject.Inject;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import com.coding4people.mosquitoreport.api.auth.AuthenticationService;
import com.coding4people.mosquitoreport.api.models.Email;
import com.coding4people.mosquitoreport.api.models.FacebookUser;
import com.coding4people.mosquitoreport.api.models.User;
import com.coding4people.mosquitoreport.api.repositories.EmailRepository;
import com.coding4people.mosquitoreport.api.repositories.FacebookUserRepository;
import com.coding4people.mosquitoreport.api.repositories.UserRepository;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.restfb.DefaultFacebookClient;
import com.restfb.DefaultJsonMapper;
import com.restfb.Facebook;
import com.restfb.FacebookClient;
import com.restfb.Parameter;
import com.restfb.Version;
import com.restfb.WebRequestor;
| package com.coding4people.mosquitoreport.api.controllers;
@Path("/auth/facebook")
public class AuthFacebookController {
@Inject
WebRequestor webRequestor;
@Inject
EmailRepository emailRepository;
@Inject
UserRepository userRepository;
@Inject
FacebookUserRepository facebookUserRepository;
@Inject
| AuthenticationService authenticationService;
| 0 |
caprica/picam | src/test/java/uk/co/caprica/picam/tutorial/creation/MyCameraApplication6.java | [
"public final class Camera implements AutoCloseable {\n\n /**\n * Camera configuration, may be <code>null</code>.\n */\n private CameraConfiguration cameraConfiguration;\n\n /**\n * Flag tracks whether this component is currently \"open\" or not.\n *\n * @see #open()\n * @see #close()\n */\n private boolean opened;\n\n /**\n * Create a camera component with reasonable default configuration.\n * <p>\n * The camera will automatically be opened.\n * <p>\n * The camera should be closed via {@link #close()} when it is no longer needed.\n *\n * @see #Camera(CameraConfiguration)\n * @see #close()\n *\n * @throws CameraException if the camera could not be opened\n * */\n public Camera() throws CameraException {\n this(null);\n }\n\n /**\n * Create a camera component.\n * <p>\n * The camera will automatically be opened.\n * <p>\n * The camera should be closed via {@link #close()} when it is no longer needed.\n *\n * @see #close()\n *\n * @param cameraConfiguration camera configuration\n * @throws CameraException if the camera could not be opened\n */\n public Camera(CameraConfiguration cameraConfiguration) throws CameraException {\n this.cameraConfiguration = cameraConfiguration;\n if (!open()) {\n throw new CameraException(\"Failed to open camera\");\n }\n }\n\n /**\n * Open the camera, creating all of the necessary native resources.\n * <p>\n * If the camera is already open this method will do nothing.\n *\n * @see #close()\n * @return <code>true</code> if the camera is open; <code>false</code> if it is not\n */\n public boolean open() {\n if (!opened) {\n opened = create(cameraConfiguration);\n }\n return opened;\n }\n\n /**\n * Take a picture.\n * <p>\n * The camera must be open before taking a picture.\n * <p>\n * The capture handler will be invoked on a <strong>native</strong> callback thread.\n * <p>\n * The calling application must make sure that the {@link PictureCaptureHandler} instance is kept in-scope and\n * prevented from being garbage collected.\n *\n * @see #open()\n * @see #takePicture(PictureCaptureHandler, int)\n *\n * @param pictureCaptureHandler handler that will receive the picture capture data\n * @param <T> type that will be returned by the picture capture handler\n * @return picture capture handler result\n * @throws CaptureFailedException if an error occurs\n */\n public <T> T takePicture(PictureCaptureHandler<T> pictureCaptureHandler) throws CaptureFailedException {\n return takePicture(pictureCaptureHandler ,0);\n }\n\n /**\n * Take a picture, with an initial capture delay.\n * <p>\n * The camera must be open before taking a picture.\n * <p>\n * The capture handler will be invoked on a <strong>native</strong> callback thread.\n * <p>\n * The calling application must make sure that the {@link PictureCaptureHandler} instance is kept in-scope and\n * prevented from being garbage collected.\n *\n * @see #open()\n *\n * @param pictureCaptureHandler handler that will receive the picture capture data\n * @param delay delay before taking the picture, specified in milliseconds\n * @param <T> type that will be returned by the picture capture handler\n * @return picture capture handler result\n * @throws CaptureFailedException if an error occurs\n */\n public <T> T takePicture(PictureCaptureHandler<T> pictureCaptureHandler, int delay) throws CaptureFailedException {\n if (!opened) {\n throw new IllegalStateException(\"The camera must be opened first\");\n }\n\n if (capture(pictureCaptureHandler, delay)) {\n return pictureCaptureHandler.result();\n } else {\n throw new CaptureFailedException(\"Failed to trigger the capture\");\n }\n }\n\n /**\n * Close the camera, freeing up all of the associated native resources.\n * <p>\n * The camera can be reopened via {@link #open()}.\n * <p>\n * If the camera is already closed this method will do nothing.\n *\n * @see #open()\n */\n @Override\n public void close() {\n if (opened) {\n destroy();\n opened = false;\n }\n }\n\n /**\n * Private native method used to create the native camera component and all associated native resources.\n *\n * @param cameraConfiguration\n * @return <code>true</code> if the native resources were successfully created; <code>false</code> on error\n */\n private native boolean create(CameraConfiguration cameraConfiguration);\n\n /**\n * Private native method used to trigger a capture.\n *\n * @param handler handler used to process the captured image data\n * @param delay number of milliseconds to wait before performing the capture\n * @throws CaptureFailedException if the image capture failed for any reason\n */\n private native boolean capture(PictureCaptureHandler<?> handler, int delay) throws CaptureFailedException;\n\n /**\n * Private native method used to destroy the native camera component and all associated native resources.\n */\n private native void destroy();\n\n}",
"public final class CameraConfiguration {\n\n private static final Integer DEFAULT_WIDTH = 2592;\n\n private static final Integer DEFAULT_HEIGHT = 1944;\n\n private Integer cameraNumber = 0;\n\n private Integer customSensorConfig = 0;\n\n private Integer width = DEFAULT_WIDTH;\n\n private Integer height = DEFAULT_HEIGHT;\n\n private Encoding encoding = PNG;\n\n private Integer quality;\n\n private StereoscopicMode stereoscopicMode = StereoscopicMode.NONE;\n\n private Boolean decimate = Boolean.FALSE;\n\n private Boolean swapEyes = Boolean.FALSE;\n\n private Integer brightness;\n\n private Integer contrast;\n\n private Integer saturation;\n\n private Integer sharpness;\n\n private Boolean videoStabilisation;\n\n private Integer shutterSpeed;\n\n private Integer iso;\n\n private ExposureMode exposureMode;\n\n private ExposureMeteringMode exposureMeteringMode;\n\n private Integer exposureCompensation;\n\n private DynamicRangeCompressionStrength dynamicRangeCompressionStrength;\n\n private AutomaticWhiteBalanceMode automaticWhiteBalanceMode;\n\n private Float automaticWhiteBalanceRedGain;\n\n private Float automaticWhiteBalanceBlueGain;\n\n private ImageEffect imageEffect;\n\n private Mirror mirror;\n\n private Integer rotation;\n\n private Double cropX;\n\n private Double cropY;\n\n private Double cropW;\n\n private Double cropH;\n\n private Boolean colourEffect;\n\n private Integer u;\n\n private Integer v;\n\n private Integer captureTimeout = 0;\n\n private CameraConfiguration() {\n }\n\n public static CameraConfiguration cameraConfiguration() {\n return new CameraConfiguration();\n }\n\n public CameraConfiguration width(Integer width) {\n this.width = width;\n return this;\n }\n\n public CameraConfiguration height(Integer height) {\n this.height = height;\n return this;\n }\n\n public CameraConfiguration size(Integer width, Integer height) {\n this.width = width;\n this.height = height;\n return this;\n }\n\n public CameraConfiguration encoding(Encoding encoding) {\n this.encoding = encoding;\n return this;\n }\n\n public CameraConfiguration quality(Integer quality) {\n if (quality < 0 || quality > 100) {\n throw new IllegalArgumentException(\"Quality must be in the range 0 to 100\");\n }\n this.quality = quality;\n return this;\n }\n\n public CameraConfiguration stereoscopicMode(StereoscopicMode stereoscopicMode, Boolean decimate, Boolean swapEyes) {\n this.stereoscopicMode = stereoscopicMode;\n this.decimate = decimate;\n this.swapEyes = swapEyes;\n return this;\n }\n\n public CameraConfiguration brightness(Integer brightness) {\n if (brightness < 0 || brightness > 100) {\n throw new IllegalArgumentException(\"Brightness must be in the range 0 to 100\");\n }\n this.brightness = brightness;\n return this;\n }\n\n public CameraConfiguration contrast(Integer contrast) {\n if (contrast < -100 || contrast > 100) {\n throw new IllegalArgumentException(\"Contrast must be in the range -100 to 100\");\n }\n this.contrast = contrast;\n return this;\n }\n\n public CameraConfiguration saturation(Integer saturation) {\n if (saturation < -100 || saturation > 100) {\n throw new IllegalArgumentException(\"Saturation must be in the range -100 to 100\");\n }\n this.saturation = saturation;\n return this;\n }\n\n public CameraConfiguration sharpness(Integer sharpness) {\n if (sharpness < -100 || sharpness > 100) {\n throw new IllegalArgumentException(\"Sharpness must be in the range -100 to 100\");\n }\n this.sharpness = sharpness;\n return this;\n }\n\n public CameraConfiguration videoStabilisation(Boolean videoStabilisation) {\n this.videoStabilisation = videoStabilisation;\n return this;\n }\n\n public CameraConfiguration shutterSpeed(Integer shutterSpeed) {\n this.shutterSpeed = shutterSpeed;\n return this;\n }\n\n public CameraConfiguration iso(Integer iso) {\n this.iso = iso;\n return this;\n }\n\n public CameraConfiguration exposureMode(ExposureMode exposureMode) {\n this.exposureMode = exposureMode;\n return this;\n }\n\n public CameraConfiguration exposureMeteringMode(ExposureMeteringMode exposureMeteringMode) {\n this.exposureMeteringMode = exposureMeteringMode;\n return this;\n }\n\n public CameraConfiguration exposureCompensation(Integer exposureCompensation) {\n if (exposureCompensation < -10 || exposureCompensation > 10) {\n throw new IllegalArgumentException(\"Exposure Compensation must be in the range -10 to 10\");\n }\n this.exposureCompensation = exposureCompensation;\n return this;\n }\n\n public CameraConfiguration dynamicRangeCompressionStrength(DynamicRangeCompressionStrength dynamicRangeCompressionStrength) {\n this.dynamicRangeCompressionStrength = dynamicRangeCompressionStrength;\n return this;\n }\n\n public CameraConfiguration automaticWhiteBalanceMode(AutomaticWhiteBalanceMode automaticWhiteBalanceMode) {\n this.automaticWhiteBalanceMode = automaticWhiteBalanceMode;\n return this;\n }\n\n public CameraConfiguration automaticWhiteBalanceRedGain(float automaticWhiteBalanceRedGain) {\n this.automaticWhiteBalanceRedGain = automaticWhiteBalanceRedGain;\n return this;\n }\n\n public CameraConfiguration automaticWhiteBalanceBlueGain(float automaticWhiteBalanceBlueGain) {\n this.automaticWhiteBalanceBlueGain = automaticWhiteBalanceBlueGain;\n return this;\n }\n\n public CameraConfiguration automaticWhiteBalanceGains(float automaticWhiteBalanceRedGain, float automaticWhiteBalanceBlueGain) {\n this.automaticWhiteBalanceRedGain = automaticWhiteBalanceRedGain;\n this.automaticWhiteBalanceBlueGain = automaticWhiteBalanceBlueGain;\n return this;\n }\n\n public CameraConfiguration imageEffect(ImageEffect imageEffect) {\n this.imageEffect = imageEffect;\n return this;\n }\n\n public CameraConfiguration colourEffect(Boolean enable, Integer u, Integer v) {\n this.colourEffect = enable;\n this.u = u;\n this.v = v;\n return this;\n }\n\n public CameraConfiguration mirror(Mirror mirror) {\n this.mirror = mirror;\n return this;\n }\n\n public CameraConfiguration rotation(Integer rotation) {\n this.rotation = rotation;\n return this;\n }\n\n public CameraConfiguration crop(double x, double y, double width, double height) {\n this.cropX = x;\n this.cropY = y;\n this.cropW = width;\n this.cropH = height;\n return this;\n }\n\n public CameraConfiguration captureTimeout(Integer captureTimeout) {\n this.captureTimeout = captureTimeout;\n return this;\n }\n\n /**\n * Create a new camera based on the configuration.\n *\n * @return\n * @throws CameraException if the camera failed to open\n */\n public Camera camera() throws CameraException {\n return new Camera(this);\n }\n\n public Integer cameraNumber() {\n return cameraNumber;\n }\n\n public Integer customSensorConfig() {\n return customSensorConfig;\n }\n\n public Integer width() {\n return width;\n }\n\n public Integer height() {\n return height;\n }\n\n public Encoding encoding() {\n return encoding;\n }\n\n public Integer quality() {\n return quality;\n }\n\n public StereoscopicMode stereoscopicMode() {\n return stereoscopicMode;\n }\n\n public Boolean decimate() {\n return decimate;\n }\n\n public Boolean swapEyes() {\n return swapEyes;\n }\n\n public Integer brightness() {\n return brightness;\n }\n\n public Integer contrast() {\n return contrast;\n }\n\n public Integer saturation() {\n return saturation;\n }\n\n public Integer sharpness() {\n return sharpness;\n }\n\n public Boolean videoStabilisation() {\n return videoStabilisation;\n }\n\n public Integer shutterSpeed() {\n return shutterSpeed;\n }\n\n public Integer iso() {\n return iso;\n }\n\n public ExposureMode exposureMode() {\n return exposureMode;\n }\n\n public ExposureMeteringMode exposureMeteringMode() {\n return exposureMeteringMode;\n }\n\n public Integer exposureCompensation() {\n return exposureCompensation;\n }\n\n public DynamicRangeCompressionStrength dynamicRangeCompressionStrength() {\n return dynamicRangeCompressionStrength;\n }\n\n public AutomaticWhiteBalanceMode automaticWhiteBalanceMode() {\n return automaticWhiteBalanceMode;\n }\n\n public Float automaticWhiteBalanceRedGain() {\n return automaticWhiteBalanceRedGain;\n }\n\n public Float automaticWhiteBalanceBlueGain() {\n return automaticWhiteBalanceBlueGain;\n }\n\n public ImageEffect imageEffect() {\n return imageEffect;\n }\n\n public Boolean colourEffect() {\n return colourEffect;\n }\n\n public Integer u() {\n return u;\n }\n\n public Integer v() {\n return v;\n }\n\n public Mirror mirror() {\n return mirror;\n }\n\n public Integer rotation() {\n return rotation;\n }\n\n public Double cropX() {\n return cropX;\n }\n\n public Double cropY() {\n return cropY;\n }\n\n public Double cropW() {\n return cropW;\n }\n\n public Double cropH() {\n return cropH;\n }\n\n public Integer captureTimeout() {\n return captureTimeout;\n }\n\n}",
"public final class CameraException extends Exception {\n\n public CameraException(String message) {\n super(message);\n }\n\n}",
"public final class NativeLibraryException extends Exception {\n\n public NativeLibraryException(String message) {\n super(message);\n }\n\n public NativeLibraryException(String message, Throwable cause) {\n super(message, cause);\n }\n\n}",
"public enum AutomaticWhiteBalanceMode {\n\n OFF(0),\n AUTO(1),\n SUNLIGHT(2),\n CLOUDY(3),\n SHADE(4),\n TUNGSTEN(5),\n FLUORESCENT(6),\n INCANDESCENT(7),\n FLASH(8),\n HORIZON(9),\n MAX(0x7fffffff);\n\n private final int value;\n\n AutomaticWhiteBalanceMode(int value) {\n this.value = value;\n }\n\n public int value() {\n return value;\n }\n}",
"public enum Encoding {\n\n BMP(\"BMP \"),\n GIF(\"GIF \"),\n I420(\"I420\"),\n JPEG(\"JPEG\"),\n PNG(\"PNG \"),\n RGB24(\"RGB3\"),\n BGR24(\"BGR3\"),\n\n OPAQUE(\"OPQV\");\n\n private final int value;\n\n Encoding(String encoding) {\n this.value = fourCC(encoding);\n }\n\n public int value() {\n return value;\n }\n\n private static int fourCC(String value) {\n return value.charAt(0) | (value.charAt(1) << 8) | (value.charAt(2) << 16) | (value.charAt(3) << 24);\n }\n}",
"public static CameraConfiguration cameraConfiguration() {\n return new CameraConfiguration();\n}",
"public static Path installTempLibrary() throws NativeLibraryException {\n Path installPath = installLibrary(Paths.get(System.getProperty(\"java.io.tmpdir\")), true);\n installPath.toFile().deleteOnExit();\n return installPath;\n}"
] | import uk.co.caprica.picam.Camera;
import uk.co.caprica.picam.CameraConfiguration;
import uk.co.caprica.picam.CameraException;
import uk.co.caprica.picam.NativeLibraryException;
import uk.co.caprica.picam.enums.AutomaticWhiteBalanceMode;
import uk.co.caprica.picam.enums.Encoding;
import static uk.co.caprica.picam.CameraConfiguration.cameraConfiguration;
import static uk.co.caprica.picam.PicamNativeLibrary.installTempLibrary; | /*
* This file is part of picam.
*
* picam 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.
*
* picam 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 picam. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright 2016-2019 Caprica Software Limited.
*/
package uk.co.caprica.picam.tutorial.creation;
public class MyCameraApplication6 {
public static void main(String[] args) throws NativeLibraryException { | installTempLibrary(); | 7 |
JamesNorris/Ablockalypse | src/com/github/jamesnorris/ablockalypse/event/bukkit/PlayerMove.java | [
"public class Ablockalypse extends JavaPlugin {\n private static Ablockalypse instance;\n private static DataContainer data = new DataContainer();\n private static MainThread mainThread;\n private static External external;\n private static BaseCommand commandInstance;\n private static Tracker tracker;\n\n public static BaseCommand getBaseCommandInstance() {\n return commandInstance;\n }\n\n public static DataContainer getData() {\n return data;\n }\n\n public static External getExternal() {\n return external;\n }\n\n public static Ablockalypse getInstance() {\n return instance;\n }\n\n public static MainThread getMainThread() {\n return mainThread;\n }\n\n public static Tracker getTracker() {\n return tracker;\n }\n\n // Kills the plugin.\n protected static void kill() {\n Ablockalypse.instance.setEnabled(false);\n }\n\n @Override public void onDisable() {\n for (Game game : data.getObjectsOfType(Game.class)) {\n game.organizeObjects();\n PermanentAspect.save(game, external.getSavedDataFile(game.getName(), true));\n if ((Boolean) Setting.PRINT_STORAGE_DATA_TO_FILE.getSetting()) {\n try {\n PermanentAspect.printData(game);\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n game.remove(false);\n }\n for (PlayerState state : PlayerJoin.toLoad) {\n PlayerQuit.playerSaves.put(state.getPlayer().getPlayer(), state);\n }\n for (Player player : PlayerQuit.playerSaves.keySet()) {\n PlayerState state = PlayerQuit.playerSaves.get(player);\n PermanentAspect.save(state, external.getSavedPlayerDataFile(player, true));\n }\n mainThread.cancel();\n }\n\n @SuppressWarnings(\"unchecked\") @Override public void onEnable() {\n Ablockalypse.instance = this;\n external = new External(this);\n tracker = new Tracker(\"Ablockalypse\", getDescription().getVersion(), \"https://github.com/JamesNorris/Ablockalypse/issues\", (Integer) Setting.MAX_FATALITY.getSetting());\n commandInstance = new BaseCommand();\n register();\n initServerThreads(false);\n try {\n for (File file : external.getSavedDataFolder().listFiles()) {\n if (file != null && !file.isDirectory()) {\n Map<String, Object> save = (Map<String, Object>) External.load(file);\n PermanentAspect.load(Game.class, save);\n }\n }\n for (File file : external.getSavedPlayerDataFolder().listFiles()) {\n if (file != null && !file.isDirectory()) {\n Map<String, Object> save = (Map<String, Object>) External.load(file);\n PlayerJoin.toLoad.add((PlayerState) PermanentAspect.load(PlayerState.class, save));\n file.delete();\n }\n }\n } catch (EOFException e) {\n // nothing, the file is empty and no data was saved\n } catch (IOException e) {\n e.printStackTrace();\n } catch (ClassNotFoundException e) {\n e.printStackTrace();\n }\n mainThread.run();// starts the main thread, which was told not to autorun earlier. Done to prevent NPEs with loading saves and running threads.\n }\n\n protected void initServerThreads(boolean startMain) {\n mainThread = new MainThread(startMain);\n new ServerBarrierActionTask(true);\n new ServerMobSpawnPreventionTask(360, (Boolean) Setting.CLEAR_MOBS.getSetting());\n new ServerHellhoundActionTask(20, true);\n new ServerTeleporterActionTask(20, true);\n }\n\n protected void register() {\n PluginManager pm = getServer().getPluginManager();\n /* EVENTS */\n for (Listener listener : new Listener[] {new EntityDamage(), new PlayerDeath(), new PlayerInteract(),\n new SignChange(), new EntityDeath(), new PlayerPickupItem(), new ProjectileHit(), new PlayerMove(),\n new EntityBreakDoor(), new PlayerTeleport(), new PlayerQuit(), new EntityTarget(), new PlayerRespawn(),\n new EntityExplode(), new EntityDamageByEntity(), new PlayerJoin(), new BlockBreak(),\n new PlayerDropItem(), new PlayerKick(), new BlockPlace(), new BlockRedstone(), new PlayerToggleSneak()}) {\n pm.registerEvents(listener, instance);\n }\n /* COMMANDS */\n instance.getCommand(\"za\").setExecutor(commandInstance);\n }\n}",
"public class DataContainer {\n public static DataContainer fromObject(Object obj) {\n try {\n for (Field field : obj.getClass().getDeclaredFields()) {\n if (field.getType() == DataContainer.class) {\n return (DataContainer) field.get(obj);\n }\n }\n return (DataContainer) obj.getClass().getDeclaredField(\"data\").get(obj);// if a DataContainer field is not found otherwise...\n } catch (Exception ex) {\n ex.printStackTrace();\n }\n return null;\n }\n\n public Material[] modifiableMaterials = new Material[] {Material.FLOWER_POT};// default materials\n public CopyOnWriteArrayList<Object> objects = new CopyOnWriteArrayList<Object>();\n\n public boolean gameExists(String gamename) {\n return getObjectsOfType(Game.class).contains(getGame(gamename, false));\n }\n\n public Barrier getBarrier(Location loc) {\n return getGameObjectByLocation(Barrier.class, loc);\n }\n\n public Claymore getClaymore(Location loc) {\n return getGameObjectByLocation(Claymore.class, loc);\n }\n\n public <O extends GameAspect> O getClosest(Class<O> type, Location loc) {\n return getClosest(type, loc, Double.MAX_VALUE, Double.MAX_VALUE, Double.MAX_VALUE);\n }\n\n public <O extends GameAspect> O getClosest(Class<O> type, Location loc, double distX, double distY, double distZ) {\n O object = null;\n double lowestDist = Double.MAX_VALUE;\n for (O obj : getObjectsOfType(type)) {\n if (obj.getDefiningBlocks() == null) {\n continue;\n }\n Location objLoc = obj.getDefiningBlock().getLocation();\n double xDif = Math.abs(objLoc.getX() - loc.getX());\n double yDif = Math.abs(objLoc.getY() - loc.getY());\n double zDif = Math.abs(objLoc.getZ() - loc.getZ());\n if (xDif < distX && yDif < distY && zDif < distZ && xDif + yDif + zDif < lowestDist) {\n object = obj;\n }\n }\n return object;\n }\n\n public Entity getEntityByUUID(World world, UUID uuid) {\n for (Entity entity : world.getEntities()) {\n if (entity.getUniqueId().compareTo(uuid) == 0) {\n return entity;\n }\n }\n return null;\n }\n\n public Game getGame(String name, boolean force) {\n List<Game> games = getObjectsOfType(Game.class);\n Game correctGame = null;\n for (Game game : games) {\n if (game.getName().equalsIgnoreCase(name)) {\n correctGame = game;\n }\n }\n return correctGame != null ? correctGame : force ? new Game(name) : null;\n }\n\n public <O extends GameAspect> O getGameObjectByLocation(Class<O> type, Location loc) {\n for (O obj : getObjectsOfType(type)) {\n if (obj.getDefiningBlocks() == null) {\n continue;\n }\n for (Block matchBlock : obj.getDefiningBlocks()) {\n if (BukkitUtility.locationMatch(matchBlock.getLocation(), loc)) {\n return obj;\n }\n }\n }\n return null;\n }\n\n public GameAspect getGameObjectByLocation(Location loc) {\n return getGameObjectByLocation(GameAspect.class, loc);\n }\n\n public Grenade getGrenade(Entity entity) {\n for (Grenade grenade : getObjectsOfType(Grenade.class)) {\n if (grenade.getLocation() != null && grenade.getGrenadeEntity() != null && grenade.getGrenadeEntity().getUniqueId().compareTo(entity.getUniqueId()) == 0) {\n return grenade;\n }\n }\n return null;\n }\n\n public Hellhound getHellhound(LivingEntity e) {\n return (Hellhound) getZAMobByEntity(e);\n }\n\n public Teleporter getMainframe(Location loc) {\n return getGameObjectByLocation(Teleporter.class, loc);\n }\n\n public MobSpawner getMobSpawner(Location loc) {\n return getGameObjectByLocation(MobSpawner.class, loc);\n }\n\n public MysteryBox getMysteryChest(Location loc) {\n return getGameObjectByLocation(MysteryBox.class, loc);\n }\n\n @SuppressWarnings(\"unchecked\") public <O extends Object> List<O> getObjectsOfType(Class<O> type) {\n ArrayList<O> list = new ArrayList<O>();\n for (Object obj : objects) {\n if (type.isAssignableFrom(obj.getClass())) {\n list.add((O) obj);\n }\n }\n return list;\n }\n\n public Passage getPassage(Location loc) {\n return getGameObjectByLocation(Passage.class, loc);\n }\n\n public ArrayList<MobSpawner> getSpawns(String gamename) {\n ArrayList<MobSpawner> spawners = new ArrayList<MobSpawner>();\n for (MobSpawner spawn : getObjectsOfType(MobSpawner.class)) {\n if (spawn.getGame().getName().equalsIgnoreCase(gamename)) {\n spawners.add(spawn);\n }\n }\n return spawners;\n }\n\n @SuppressWarnings(\"unchecked\") public <T extends Task> List<T> getTasksOfType(Class<T> type) {\n ArrayList<T> list = new ArrayList<T>();\n for (Task thread : getObjectsOfType(Task.class)) {\n if (thread.getClass().isInstance(type)) {\n list.add((T) thread);\n }\n }\n return list;\n }\n\n public Teleporter getTeleporter(Location loc) {\n return getGameObjectByLocation(Teleporter.class, loc);\n }\n\n public ZAMob getZAMob(LivingEntity e) {\n return getZAMobByEntity(e);\n }\n\n public ZAMob getZAMobByEntity(LivingEntity ent) {\n for (ZAMob mob : getObjectsOfType(ZAMob.class)) {\n if (mob.getEntity().getUniqueId().compareTo(ent.getUniqueId()) == 0) {\n return mob;\n }\n }\n return null;\n }\n\n public ZAPlayer getZAPlayer(Player player) {\n for (ZAPlayer zap : getObjectsOfType(ZAPlayer.class)) {\n if (zap.getPlayer().getName().equals(player.getName())) {\n return zap;\n }\n }\n return null;\n }\n\n public ZAPlayer getZAPlayer(Player player, String gamename, boolean force) {\n if (getZAPlayer(player) != null) {\n return getZAPlayer(player);\n } else if (getGame(gamename, false) != null && force) {\n return new ZAPlayer(player, getGame(gamename, false));\n } else if (force) {\n return new ZAPlayer(player, getGame(gamename, true));\n }\n return null;\n }\n\n public Zombie getZombie(LivingEntity e) {\n return (Zombie) getZAMobByEntity(e);\n }\n\n public boolean isBarrier(Location loc) {\n return getBarrier(loc) != null;\n }\n\n public boolean isClaymore(Location loc) {\n return getClaymore(loc) != null;\n }\n\n public boolean isGame(String name) {\n return getGame(name, false) != null;\n }\n\n public boolean isGameObject(Location loc) {\n return getGameObjectByLocation(loc) != null;\n }\n\n public boolean isGrenade(Entity entity) {\n return getGrenade(entity) != null;\n }\n\n public boolean isHellhound(LivingEntity e) {\n return getHellhound(e) != null;\n }\n\n public boolean isMainframe(Location loc) {\n return getMainframe(loc) != null;\n }\n\n public boolean isMobSpawner(Location loc) {\n return getMobSpawner(loc) != null;\n }\n\n public boolean isModifiable(Material type) {\n for (Material m : modifiableMaterials) {\n if (m == type) {\n return true;\n }\n }\n return false;\n }\n\n public boolean isMysteryChest(Location loc) {\n return getMysteryChest(loc) != null;\n }\n\n public boolean isPassage(Location loc) {\n return getPassage(loc) != null;\n }\n\n public boolean isTeleporter(Location loc) {\n return getTeleporter(loc) != null;\n }\n\n public boolean isUndead(LivingEntity e) {\n return getZombie(e) != null;\n }\n\n public boolean isZAMob(LivingEntity e) {\n return getZAMob(e) != null;\n }\n\n public boolean isZAPlayer(Player player) {\n return getZAPlayer(player) != null;\n }\n\n public void setModifiableMaterials(Material[] materials) {\n modifiableMaterials = materials;\n }\n}",
"public class Barrier extends SpecificGameAspect implements MapDatable, Targettable {\n private CopyOnWriteArrayList<BlockState> states = new CopyOnWriteArrayList<BlockState>();\n private Zone zone;\n private Location center, spawnloc;\n private boolean correct;\n private DataContainer data = Ablockalypse.getData();\n private Game game;\n private int hp = 5;\n private UUID uuid = UUID.randomUUID();\n private Task warning;\n\n /**\n * Creates a new instance of a Barrier, where center is the center of the 3x3 barrier.\n * \n * @param center The center of the barrier\n * @param game The game to involve this barrier in\n */\n public Barrier(Location center, Game game) {\n super(game, new Cube(center, 1).getLocations(), !game.hasStarted());\n this.center = center;\n this.game = game;\n spawnloc = BukkitUtility.getNearbyLocation(center, 2, 5, 0, 0, 2, 5);\n for (Location loc : new Cube(center, 1).getLocations()) {\n Block b = loc.getBlock();\n if (b != null && !b.isEmpty() && b.getType() != null) {\n states.add(b.getState());\n }\n }\n load();\n setIsCorrectlySetup(states.size() >= 9);\n }\n\n public Barrier(Map<String, Object> savings) {\n this(SerialLocation.returnLocation((SerialLocation) savings.get(\"center_location\")), Ablockalypse.getData().getGame((String) savings.get(\"game_name\"), true));\n List<BlockState> blocks = new CopyOnWriteArrayList<BlockState>();\n @SuppressWarnings(\"unchecked\") List<SerialLocation> serialBlockLocations = (List<SerialLocation>) savings.get(\"all_block_locations\");\n for (SerialLocation serialLoc : serialBlockLocations) {\n blocks.add(serialLoc.getWorld().getBlockAt(SerialLocation.returnLocation(serialLoc)).getState());\n }\n states = (CopyOnWriteArrayList<BlockState>) blocks;\n center = SerialLocation.returnLocation((SerialLocation) savings.get(\"center_location\"));\n spawnloc = SerialLocation.returnLocation((SerialLocation) savings.get(\"spawn_location\"));\n correct = (Boolean) savings.get(\"setup_is_correct\");\n game = Ablockalypse.getData().getGame((String) savings.get(\"game_name\"), true);\n uuid = savings.get(\"uuid\") == null ? uuid : (UUID) savings.get(\"uuid\");\n }\n\n /**\n * Slowly breaks the blocks of the barrier.\n * \n * @param liveEntity The entityliving that is breaking the barrier\n */\n public void breakBarrier(LivingEntity liveEntity) {\n super.setBlinking(false);\n new BarrierBreakTask(this, liveEntity, true);\n }\n\n /**\n * Changes all blocks within the barrier to air.\n */\n public void breakPanels() {\n for (BlockState state : states) {\n state.getBlock().setType(Material.AIR);\n ZAEffect.SMOKE.play(state.getLocation());\n }\n hp = 0;\n }\n\n /**\n * Slowly fixes the blocks of the barrier.\n * \n * @param zap The ZAPlayer that is going to be fixing this barrier\n */\n public void fixBarrier(ZAPlayer zap) {\n super.setBlinking(false);\n new BarrierFixTask(this, zap, true);\n }\n\n @SuppressWarnings(\"serial\") @Override public List<Block> getBlinkerBlocks() {\n if (center == null) {\n return super.getBlinkerBlocks();\n }\n return new ArrayList<Block>() {\n {\n add(center.getBlock());\n }\n };\n }\n\n /**\n * Returns the list of blocks in the barrier.\n * \n * @return A list of blocks located in the barrier\n */\n public CopyOnWriteArrayList<Block> getBlocks() {\n CopyOnWriteArrayList<Block> blocks = new CopyOnWriteArrayList<Block>();\n for (BlockState state : states) {\n blocks.add(state.getBlock());\n }\n return blocks;\n }\n\n /**\n * Gets the center location of the barrier.\n * \n * @return The center of the barrier\n */\n public Location getCenter() {\n return getDefiningBlock().getLocation();\n }\n\n @Override public Block getDefiningBlock() {\n if (center == null) {\n return super.getDefiningBlock();\n }\n return center.getBlock();\n }\n\n /**\n * Gets the blocks that defines this object as an object.\n * \n * @return The blocks assigned to this object\n */\n @Override public List<Block> getDefiningBlocks() {\n if (states == null) {\n return super.getDefiningBlocks();\n }\n ArrayList<Block> blockArray = new ArrayList<Block>();\n for (BlockState state : states) {\n blockArray.add(state.getBlock());\n }\n return blockArray;\n }\n\n public int getHP() {\n return hp;\n }\n\n @Override public int getLoadPriority() {\n return 2;\n }\n\n @Override public Location getPointClosestToOrigin() {\n Location origin = new Location(center.getWorld(), 0, 0, 0, 0, 0);\n Location loc = null;\n for (BlockState state : states) {\n Block block = state.getBlock();\n if (loc == null || block.getLocation().distanceSquared(origin) <= loc.distanceSquared(origin)) {\n loc = block.getLocation();\n }\n }\n return loc;\n }\n\n @Override public Map<String, Object> getSave() {\n Map<String, Object> savings = new HashMap<String, Object>();\n savings.put(\"uuid\", getUUID());\n List<SerialLocation> serialBlocks = new ArrayList<SerialLocation>();\n for (BlockState state : states) {\n serialBlocks.add(new SerialLocation(state.getBlock().getLocation()));\n }\n savings.put(\"all_block_locations\", serialBlocks);\n savings.put(\"center_location\", center == null ? null : new SerialLocation(center));\n savings.put(\"spawn_location\", spawnloc == null ? null : new SerialLocation(spawnloc));\n savings.put(\"setup_is_correct\", correct);\n savings.put(\"game_name\", game.getName());\n return savings;\n }\n\n /**\n * Gets the mob spawn location for this barrier.\n * \n * @return The mob spawn location around this barrier\n */\n public Location getSpawnLocation() {\n return spawnloc;\n }\n\n @Override public UUID getUUID() {\n return uuid;\n }\n\n public Zone getZone() {\n return zone;\n }\n\n /**\n * Tells whether or not the barrier has any missing blocks.\n * \n * @return Whether or not the barrier is broken\n */\n public boolean isBroken() {\n if (center.getBlock().isEmpty()) {\n return true;\n }\n return false;\n }\n\n /**\n * Checks if the barrier is setup correctly or not.\n * \n * @return Whether or not the barrier is setup correctly\n */\n public boolean isCorrect() {\n return correct;\n }\n\n @Override public boolean isResponsive() {\n return hp != 0;\n }\n\n @Override public boolean isTargettedBy(ZAMob mob) {\n return false;\n }\n\n @Override public void onGameEnd() {\n replacePanels();\n setBlinking(true);\n }\n\n @Override public void onGameStart() {\n setBlinking(false);\n }\n\n @Override public void paste(Location pointClosestToOrigin) {\n Location old = getPointClosestToOrigin();\n Location toLoc = pointClosestToOrigin.add(center.getX() - old.getX(), center.getY() - old.getY(), center.getZ() - old.getZ());\n center = toLoc;\n spawnloc = BukkitUtility.getNearbyLocation(center, 2, 5, 0, 0, 2, 5);\n refreshBlinker();\n }\n\n /**\n * Removes the barrier.\n */\n @Override public void remove() {\n replacePanels();\n if (warning != null) {\n data.objects.remove(warning);\n }\n super.remove();\n }\n\n /**\n * Replaces all holes in the barrier.\n */\n public void replacePanels() {\n for (BlockState state : states) {\n state.update(true);\n ZAEffect.SMOKE.play(state.getLocation());\n }\n ZASound.BARRIER_REPAIR.play(center);\n hp = 5;\n }\n\n public void setHP(int hp) {\n if (hp < 0) {\n hp = 0;\n return;\n }\n if (warning != null) {\n data.objects.remove(warning);\n }\n if (hp < 5) {\n warning = AblockalypseUtility.scheduleNearbyWarning(center, ChatColor.GRAY + \"Hold \" + ChatColor.AQUA + \"SHIFT\" + ChatColor.GRAY + \" to fix barrier.\", 2, 3, 2, 10000);\n }\n this.hp = hp;\n }\n\n @Override public Location updateTarget() {\n return center;\n }\n}",
"public class ZAPlayer extends ZACharacter {\r\n private Player player;\r\n private Game game;\r\n private PlayerStatus status = PlayerStatus.NORMAL;\r\n private List<ZAPerk> perks = new ArrayList<ZAPerk>();\r\n private double pointGainModifier = 1, pointLossModifier = 1;\r\n private PlayerState beforeGame, beforeLS;\r\n private int points, kills;\r\n private boolean sentIntoGame, instakill, removed;\r\n\r\n @SuppressWarnings(\"unchecked\") public ZAPlayer(Map<String, Object> savings) {\r\n super(savings);\r\n player = super.getPlayer();\r\n game = super.getGame();\r\n status = super.getStatus();\r\n Map<String, Object> beforeGameState = (Map<String, Object>) savings.get(\"before_game_state\");\r\n if (beforeGameState != null) {\r\n beforeGame = new PlayerState(beforeGameState);\r\n }\r\n Map<String, Object> beforeLSState = (Map<String, Object>) savings.get(\"before_last_stand_state\");\r\n if (beforeLSState != null) {\r\n beforeLS = new PlayerState(beforeLSState);\r\n }\r\n if (!player.isOnline()) {\r\n PlayerJoin.queuePlayer(this, SerialLocation.returnLocation((SerialLocation) savings.get(\"player_in_game_location\")), savings);\r\n return;\r\n }\r\n removed = false;\r\n loadSavedVersion(savings);\r\n }\r\n\r\n public ZAPlayer(Player player, Game game) {\r\n super(player, game);\r\n this.player = player;\r\n this.game = game;\r\n }\r\n\r\n public void addKills(int kills) {\r\n this.kills += kills;\r\n }\r\n\r\n public void addPerk(ZAPerk perk) {\r\n if (hasPerk(perk)) {\r\n return;// prevents recursion\r\n }\r\n perks.add(perk);\r\n perk.givePerk(this);\r\n }\r\n\r\n public void addPoints(int points) {\r\n this.points += points * pointGainModifier;\r\n }\r\n\r\n public void clearPerks() {\r\n for (ZAPerk perk : perks) {\r\n perk.removePerk(this);\r\n }\r\n perks.clear();\r\n }\r\n\r\n public void decrementKills() {\r\n subtractKills(1);\r\n }\r\n\r\n public int getKills() {\r\n return kills;\r\n }\r\n\r\n @Override public int getLoadPriority() {\r\n return 1;\r\n }\r\n\r\n public List<ZAPerk> getPerks() {\r\n return perks;\r\n }\r\n\r\n public double getPointGainModifier() {\r\n return pointGainModifier;\r\n }\r\n\r\n public double getPointLossModifier() {\r\n return pointLossModifier;\r\n }\r\n\r\n public int getPoints() {\r\n return points;\r\n }\r\n\r\n @Override public Map<String, Object> getSave() {\r\n Map<String, Object> savings = new HashMap<String, Object>();\r\n savings.put(\"uuid\", getUUID());\r\n savings.put(\"game_name\", game.getName());\r\n savings.put(\"points\", points);\r\n savings.put(\"kills\", kills);\r\n savings.put(\"point_gain_modifier\", pointGainModifier);\r\n savings.put(\"point_loss_modifier\", pointLossModifier);\r\n if (beforeGame != null) {\r\n savings.put(\"before_game_state\", beforeGame.getSave());\r\n }\r\n if (beforeLS != null) {\r\n savings.put(\"before_last_stand_state\", beforeLS.getSave());\r\n }\r\n List<Integer> perkIds = new ArrayList<Integer>();\r\n for (ZAPerk perk : perks) {\r\n perkIds.add(perk.getId());\r\n }\r\n savings.put(\"perk_ids\", perkIds);\r\n savings.put(\"has_been_sent_into_the_game\", sentIntoGame);\r\n savings.put(\"has_instakill\", instakill);\r\n savings.put(\"player_in_game_location\", player == null ? null : new SerialLocation(player.getLocation()));\r\n savings.putAll(super.getSave());\r\n return savings;\r\n }\r\n\r\n public void giveItem(ItemStack item) {\r\n Ablockalypse.getExternal().getItemFileManager().giveItem(player, item);\r\n }\r\n\r\n public void givePowerup(PowerupType type, Entity cause) {\r\n type.play(game, player, cause, data);\r\n }\r\n\r\n public boolean hasBeenSentIntoGame() {\r\n return sentIntoGame;\r\n }\r\n\r\n public boolean hasInstaKill() {\r\n return instakill;\r\n }\r\n\r\n public boolean hasPerk(ZAPerk perk) {\r\n return perks.contains(perk);\r\n }\r\n\r\n public void incrementKills() {\r\n addKills(1);\r\n }\r\n\r\n public boolean isInLastStand() {\r\n return status == PlayerStatus.LAST_STAND;\r\n }\r\n\r\n public boolean isInLimbo() {\r\n return status == PlayerStatus.LIMBO;\r\n }\r\n\r\n public boolean isTeleporting() {\r\n return status == PlayerStatus.TELEPORTING;\r\n }\r\n\r\n public void loadPlayerToGame(String name, boolean showMessages) {\r\n /* Use an old game to add the player to the game */\r\n if (data.isGame(name)) {\r\n Game zag = data.getGame(name, false);\r\n PlayerJoinGameEvent GPJE = new PlayerJoinGameEvent(this, zag);\r\n Bukkit.getPluginManager().callEvent(GPJE);\r\n if (!GPJE.isCancelled()) {\r\n int max = (Integer) Setting.MAX_PLAYERS.getSetting();\r\n if (zag.getPlayers().size() < max) {\r\n if (game.getMainframe() == null) {\r\n Teleporter newMainframe = new Teleporter(game, player.getLocation().clone().subtract(0, 1, 0));\r\n game.setMainframe(newMainframe);\r\n newMainframe.setBlinking(false);\r\n }\r\n removed = false;\r\n zag.addPlayer(player);\r\n prepare();\r\n sendToMainframe(showMessages ? ChatColor.GRAY + \"Teleporting to mainframe...\" : null, \"Loading player to a game\");\r\n if (showMessages) {\r\n player.sendMessage(ChatColor.GRAY + \"You have joined the game: \" + name);\r\n }\r\n return;\r\n } else {\r\n if (showMessages) {\r\n player.sendMessage(ChatColor.RED + \"This game has \" + max + \"/\" + max + \" players!\");\r\n }\r\n }\r\n }\r\n } else if (showMessages) {\r\n player.sendMessage(ChatColor.RED + \"That game does not exist!\");\r\n }\r\n }\r\n\r\n public void loadSavedVersion(Map<String, Object> savings) {\r\n points = (Integer) savings.get(\"points\");\r\n kills = (Integer) savings.get(\"kills\");\r\n pointGainModifier = (Integer) savings.get(\"point_gain_modifier\");\r\n pointLossModifier = (Integer) savings.get(\"point_loss_modifier\");\r\n List<ItemStack> stacks = new ArrayList<ItemStack>();\r\n @SuppressWarnings(\"unchecked\") List<Map<String, Object>> serialStacks = (List<Map<String, Object>>) savings.get(\"inventory\");\r\n for (Map<String, Object> serialStack : serialStacks) {\r\n stacks.add(ItemStack.deserialize(serialStack));\r\n }\r\n player.getInventory().setContents(stacks.toArray(new ItemStack[stacks.size()]));\r\n List<ZAPerk> loadedPerks = new ArrayList<ZAPerk>();\r\n @SuppressWarnings(\"unchecked\") List<Integer> perkIds = (List<Integer>) savings.get(\"perk_ids\");\r\n for (Integer id : perkIds) {\r\n loadedPerks.add(ZAPerk.getById(id));\r\n }\r\n perks = loadedPerks;\r\n sentIntoGame = (Boolean) savings.get(\"has_been_sent_into_the_game\");\r\n instakill = (Boolean) savings.get(\"has_instakill\");\r\n }\r\n\r\n @Override public void onGameEnd() {\r\n player.sendMessage(ChatColor.BOLD + \"\" + ChatColor.GRAY + \"The game has ended. You made it to level \" + game.getLevel());\r\n ZASound.END.play(player.getLocation());\r\n game.removePlayer(player);\r\n }\r\n\r\n @Override public void onLevelEnd() {\r\n ZASound.PREV_LEVEL.play(player.getLocation());\r\n //@formatter:off\r\n player.sendMessage(ChatColor.BOLD + \"Level \" + ChatColor.RESET + ChatColor.RED + game.getLevel() + ChatColor.RESET + ChatColor.BOLD \r\n + \" over... Next level: \" + ChatColor.RED + (game.getLevel() + 1) + \"\\n\" + ChatColor.RESET + ChatColor.BOLD + \"Time to next level: \"\r\n + ChatColor.RED + Setting.LEVEL_TRANSITION_TIME.getSetting() + ChatColor.RESET + ChatColor.BOLD + \" seconds.\");\r\n //@formatter:on\r\n // showPoints();//with the new scoreboard, there is not longer any need\r\n }\r\n\r\n @Override public void onNextLevel() {\r\n int level = game.getLevel();\r\n if (level != 0) {\r\n player.setLevel(level);\r\n player.sendMessage(ChatColor.BOLD + \"Level \" + ChatColor.RESET + ChatColor.RED + level + ChatColor.RESET + ChatColor.BOLD + \" has started.\");\r\n if (level != 1) {\r\n showPoints();\r\n }\r\n }\r\n }\r\n\r\n @Override public void remove() {\r\n if (removed) {\r\n return;// prevents recursion with ZAMob.kill(), which calls game.removeObject(), which calls this, which calls ZAMob.kill()... you get the idea\r\n }\r\n restoreStatus();\r\n game = null;\r\n super.remove();\r\n removed = true;\r\n }\r\n\r\n public void removeFromGame() {\r\n if (removed) {\r\n return;// prevents recursion with remove()\r\n }\r\n remove();\r\n }\r\n\r\n public void removePerk(ZAPerk perk) {\r\n if (!hasPerk(perk)) {\r\n return;// prevents recursion\r\n }\r\n perks.remove(perk);\r\n perk.removePerk(this);\r\n }\r\n\r\n @Override public void sendToMainframe(String message, String reason) {\r\n if (message != null) {\r\n player.sendMessage(message);\r\n }\r\n Location loc = game.getMainframe().getLocation().clone().add(0, 1, 0);\r\n Chunk c = loc.getChunk();\r\n if (!c.isLoaded()) {\r\n c.load();\r\n }\r\n player.teleport(loc);\r\n if (!sentIntoGame) {\r\n ZASound.START.play(loc);\r\n sentIntoGame = true;\r\n } else {\r\n ZASound.TELEPORT.play(loc);\r\n }\r\n if ((Boolean) Setting.DEBUG.getSetting()) {\r\n System.out.println(\"[Ablockalypse] [DEBUG] Mainframe TP reason: (\" + game.getName() + \") \" + reason);\r\n }\r\n }\r\n\r\n public void setInstaKill(boolean instakill) {\r\n this.instakill = instakill;\r\n }\r\n\r\n public void setKills(int kills) {\r\n this.kills = kills;\r\n }\r\n\r\n public void setPointGainModifier(double modifier) {\r\n pointGainModifier = modifier;\r\n }\r\n\r\n public void setPointLossModifier(double modifier) {\r\n pointLossModifier = modifier;\r\n }\r\n\r\n public void setPoints(int points) {\r\n double modifier = 1;\r\n if (points > this.points) {\r\n modifier = pointGainModifier;\r\n } else if (points < this.points) {\r\n modifier = pointLossModifier;\r\n }\r\n this.points = (int) Math.round(points * modifier);\r\n }\r\n\r\n public void setSentIntoGame(boolean sent) {\r\n sentIntoGame = sent;\r\n }\r\n\r\n public void showPoints() {\r\n for (ZAPlayer zap2 : game.getPlayers()) {\r\n Player p2 = zap2.getPlayer();\r\n player.sendMessage(ChatColor.RED + p2.getName() + ChatColor.RESET + \" - \" + ChatColor.GRAY + zap2.getPoints());\r\n }\r\n }\r\n\r\n public void subtractKills(int kills) {\r\n if (this.kills < kills) {\r\n this.kills = 0;\r\n return;\r\n }\r\n this.kills -= kills;\r\n }\r\n\r\n public void subtractPoints(int points) {\r\n if (this.points < points * pointLossModifier) {\r\n this.points = 0;\r\n return;\r\n }\r\n this.points -= points * pointLossModifier;\r\n }\r\n\r\n public void toggleLastStand() {\r\n if (status != PlayerStatus.LAST_STAND) {\r\n sitDown();\r\n } else {\r\n pickUp();\r\n }\r\n }\r\n\r\n private void pickUp() {\r\n LastStandEvent lse = new LastStandEvent(player, this, false);\r\n Bukkit.getServer().getPluginManager().callEvent(lse);\r\n if (!lse.isCancelled()) {\r\n beforeLS.update();\r\n player.sendMessage(ChatColor.GRAY + \"You have been picked up!\");\r\n game.broadcast(ChatColor.RED + player.getName() + ChatColor.GRAY + \" has been revived.\", player);\r\n status = PlayerStatus.NORMAL;\r\n // Breakable.setSitting(player, false);\r\n getSeat().removePassenger();\r\n getSeat().remove();\r\n player.setCanPickupItems(true);\r\n if (player.getVehicle() != null) {\r\n player.getVehicle().remove();\r\n }\r\n player.setFoodLevel(20);\r\n Entity v = player.getVehicle();\r\n if (v != null) {\r\n v.remove();\r\n }\r\n }\r\n }\r\n\r\n /* Saving the player status, so when the player is removed from the game, they are set back to where they were before. */\r\n @SuppressWarnings(\"deprecation\") private void prepare() {\r\n beforeGame = new PlayerState(player);\r\n ZASound.START.play(player.getLocation());\r\n player.setGameMode(GameMode.SURVIVAL);\r\n player.getInventory().clear();\r\n player.setLevel(game.getLevel());\r\n player.setExp(0);\r\n player.setHealth(20);\r\n player.setFoodLevel(20);\r\n player.setSaturation(0);\r\n player.getActivePotionEffects().clear();\r\n player.getInventory().setArmorContents(null);\r\n player.setSleepingIgnored(true);\r\n player.setFireTicks(0);\r\n player.setFallDistance(0F);\r\n player.setExhaustion(0F);\r\n ItemManager itemManager = Ablockalypse.getExternal().getItemFileManager();\r\n if (itemManager != null && itemManager.getStartingItemsMap() != null) {\r\n Map<Integer, BuyableItemData> startingItems = itemManager.getStartingItemsMap();\r\n for (int id : startingItems.keySet()) {\r\n itemManager.giveItem(player, startingItems.get(id).toItemStack());\r\n }\r\n }\r\n rename(\"\", player.getName(), \"0\");\r\n player.updateInventory();\r\n }\r\n\r\n /* Restoring the player status to the last saved status before the game. */\r\n private void restoreStatus() {\r\n if (status == PlayerStatus.LAST_STAND) {\r\n toggleLastStand();\r\n }\r\n for (PotionEffect pe : player.getActivePotionEffects()) {\r\n PotionEffectType pet = pe.getType();\r\n player.removePotionEffect(pet);\r\n }\r\n player.setDisplayName(player.getName());\r\n if (beforeGame != null) {\r\n beforeGame.update();\r\n }\r\n }\r\n\r\n private void sitDown() {\r\n LastStandEvent lse = new LastStandEvent(player, this, true);\r\n Bukkit.getServer().getPluginManager().callEvent(lse);\r\n if (!lse.isCancelled()) {\r\n player.sendMessage(ChatColor.GRAY + \"You have been knocked down!\");\r\n if (getGame().getRemainingPlayers().size() < 1 && (Boolean) Setting.END_ON_LAST_PLAYER_LAST_STAND.getSetting()) {\r\n removeFromGame();\r\n return;\r\n }\r\n beforeLS = new PlayerState(player);\r\n status = PlayerStatus.LAST_STAND;\r\n Entity v = player.getVehicle();\r\n if (v != null) {\r\n v.remove();\r\n }\r\n rename(\"\", player.getName(), \"[LS]\");\r\n player.setFoodLevel(0);\r\n player.setHealth((Double) Setting.LAST_STAND_HEALTH_THRESHOLD.getSetting());\r\n ZASound.LAST_STAND.play(player.getLocation());\r\n getSeat().moveLocation(player.getLocation());\r\n getSeat().sit(player);\r\n player.getInventory().clear();\r\n player.setCanPickupItems(false);\r\n game.broadcast(ChatColor.RED + player.getName() + ChatColor.GRAY + \" is down and needs revival\", player);\r\n new LastStandFallenTask(this, true);\r\n if ((Boolean) Setting.LOSE_PERKS_ON_LAST_STAND.getSetting()) {\r\n clearPerks();\r\n }\r\n }\r\n }\r\n}\r",
"public enum ZAPerk {\n DEADSHOT_DAIQUIRI(1, Local.PERK_DEADSHOT_DAIQUIRI_STRING.getSetting(), (Integer) Setting.PERK_DURATION.getSetting(), (Integer) Setting.DEADSHOT_DAIQUIRI_COST.getSetting(), (Integer) Setting.DEADSHOT_DAIQUIRI_LEVEL.getSetting()) {\n @Override public void givePerk(ZAPlayer zap) {\n zap.getPlayer().addPotionEffect(new PotionEffect(PotionEffectType.INCREASE_DAMAGE, getDuration(), 1));\n zap.addPerk(this);\n }\n\n @Override public void removePerk(ZAPlayer zap) {\n zap.getPlayer().removePotionEffect(PotionEffectType.INCREASE_DAMAGE);\n zap.removePerk(this);\n }\n },\n JUGGERNOG(2, Local.PERK_JUGGERNOG_STRING.getSetting(), (Integer) Setting.PERK_DURATION.getSetting(), (Integer) Setting.JUGGERNOG_COST.getSetting(), (Integer) Setting.JUGGERNOG_LEVEL.getSetting()) {\n private double oldAbsorption;\n\n @Override public void givePerk(ZAPlayer zap) {\n oldAbsorption = zap.getHitAbsorption();\n zap.setHitAbsorption(1);// 1 full heart per hit\n zap.addPerk(this);\n }\n\n @Override public void removePerk(ZAPlayer zap) {\n zap.setHitAbsorption(oldAbsorption);\n zap.removePerk(this);\n }\n },\n PHD_FLOPPER(3, Local.PERK_PHD_FLOPPER_STRING.getSetting(), (Integer) Setting.PERK_DURATION.getSetting(), (Integer) Setting.PHD_FLOPPER_COST.getSetting(), (Integer) Setting.PHD_FLOPPER_LEVEL.getSetting()) {\n @Override public void givePerk(ZAPlayer zap) {\n // PlayerMove.java does all the work\n zap.addPerk(this);\n }\n\n @Override public void removePerk(ZAPlayer zap) {\n zap.removePerk(this);\n }\n },\n STAMINUP(4, Local.PERK_STAMINUP_STRING.getSetting(), (Integer) Setting.PERK_DURATION.getSetting(), (Integer) Setting.STAMINUP_COST.getSetting(), (Integer) Setting.STAMINUP_LEVEL.getSetting()) {\n @Override public void givePerk(ZAPlayer zap) {\n zap.getPlayer().addPotionEffect(new PotionEffect(PotionEffectType.SPEED, getDuration(), 1));\n zap.addPerk(this);\n }\n\n @Override public void removePerk(ZAPlayer zap) {\n zap.getPlayer().removePotionEffect(PotionEffectType.SPEED);\n zap.removePerk(this);\n }\n };\n private int id, duration, cost, level;\n private String label;\n private final static Map<Integer, ZAPerk> BY_ID = Maps.newHashMap();\n static {\n for (ZAPerk perk : values()) {\n BY_ID.put(perk.id, perk);\n }\n }\n\n public static ZAPerk getById(int id) {\n return BY_ID.get(id);\n }\n\n ZAPerk(int id, String label, int duration, int cost, int level) {\n this.id = id;\n this.label = label;\n this.duration = duration;\n this.cost = cost;\n this.level = level;\n if (duration == -1) {\n duration = Integer.MAX_VALUE;\n }\n }\n\n public int getCost() {\n return cost;\n }\n\n public int getDuration() {\n return duration;\n }\n\n public int getId() {\n return id;\n }\n\n public String getLabel() {\n return label;\n }\n\n public int getLevel() {\n return level;\n }\n\n public abstract void givePerk(ZAPlayer zap);\n\n public abstract void removePerk(ZAPlayer zap);\n}",
"public class BukkitUtility {\n public static List<Material> swords = new ArrayList<Material>() {{\n add(Material.WOODEN_SWORD);\n add(Material.STONE_SWORD);\n add(Material.IRON_SWORD);\n add(Material.GOLDEN_SWORD);\n add(Material.DIAMOND_SWORD);\n }};\n\n public static HashMap<DyeColor, Material> woolByColor;\n\n private static Random rand = new Random();\n private static String nms_version = \"v1.5.2\";\n static {\n String bukkitVersion = Bukkit.getVersion();\n String cleanedVersion = bukkitVersion.split(Pattern.quote(\"(MC:\"))[1].split(Pattern.quote(\")\"))[0].trim();\n nms_version = \"v\" + cleanedVersion;\n\n woolByColor = new HashMap<DyeColor, Material>()\n woolByColor.put(DyeColor.BLACK, Material.BLACK_WOOL);\n woolByColor.put(DyeColor.BLUE, Material.BLUE_WOOL);\n woolByColor.put(DyeColor.BROWN, Material.BROWN_WOOL);\n woolByColor.put(DyeColor.CYAN, Material.CYAN_WOOL);\n woolByColor.put(DyeColor.GRAY, Material.GRAY_WOOL);\n woolByColor.put(DyeColor.GREEN, Material.GREEN_WOOL);\n woolByColor.put(DyeColor.LIGHT_BLUE, Material.LIGHT_BLUE_WOOL);\n woolByColor.put(DyeColor.LIGHT_GRAY, Material.LIGHT_GRAY_WOOL);\n woolByColor.put(DyeColor.LIME, Material.LIME_WOOL);\n woolByColor.put(DyeColor.MAGENTA, Material.MAGENTA_WOOL);\n woolByColor.put(DyeColor.ORANGE, Material.ORANGE_WOOL);\n woolByColor.put(DyeColor.PINK, Material.PINK_WOOL);\n woolByColor.put(DyeColor.PURPLE, Material.PURPLE_WOOL);\n woolByColor.put(DyeColor.RED, Material.RED_WOOL);\n woolByColor.put(DyeColor.WHITE, Material.WHITE_WOOL);\n woolByColor.put(DyeColor.YELLOW, Material.YELLOW_WOOL);\n }\n\n public static Material getWoolByColor(DyeColor color) {\n return woolByColor.get(color);\n }\n\n public static Location floorLivingEntity(LivingEntity entity) {\n Location eyeLoc = entity.getEyeLocation().clone();\n double eyeHeight = entity.getEyeHeight();\n Location floor = eyeLoc.clone().subtract(0, Math.floor(eyeHeight) + .5, 0);\n for (int y = eyeLoc.getBlockY(); y > 0; y--) {\n Location loc = new Location(floor.getWorld(), floor.getX(), y, floor.getZ(), floor.getYaw(), floor.getPitch());\n if (!loc.getBlock().isEmpty()) {\n floor = loc;\n break;\n }\n }\n return eyeLoc.clone().subtract(0, eyeLoc.getY() - floor.getY() - 2 * eyeHeight, 0);\n }\n\n public static OfflinePlayer forceObtainPlayer(String name) {\n OfflinePlayer player = Bukkit.getPlayer(name);\n if (player == null) {\n return Bukkit.getOfflinePlayer(name);\n }\n if (player == null || !player.hasPlayedBefore()) {\n // npes will be thrown... player doesnt exist and never did (why was it saved?)\n return null;\n }\n return player;\n }\n\n public static Location fromString(String loc) {\n loc = loc.substring(loc.indexOf(\"{\") + 1);\n loc = loc.substring(loc.indexOf(\"{\") + 1);\n String worldName = loc.substring(loc.indexOf(\"=\") + 1, loc.indexOf(\"}\"));\n loc = loc.substring(loc.indexOf(\",\") + 1);\n String xCoord = loc.substring(loc.indexOf(\"=\") + 1, loc.indexOf(\",\"));\n loc = loc.substring(loc.indexOf(\",\") + 1);\n String yCoord = loc.substring(loc.indexOf(\"=\") + 1, loc.indexOf(\",\"));\n loc = loc.substring(loc.indexOf(\",\") + 1);\n String zCoord = loc.substring(loc.indexOf(\"=\") + 1, loc.indexOf(\",\"));\n loc = loc.substring(loc.indexOf(\",\") + 1);\n String pitch = loc.substring(loc.indexOf(\"=\") + 1, loc.indexOf(\",\"));\n loc = loc.substring(loc.indexOf(\",\") + 1);\n String yaw = loc.substring(loc.indexOf(\"=\") + 1, loc.indexOf(\"}\"));\n return new Location(Bukkit.getWorld(worldName), Double.parseDouble(xCoord), Double.parseDouble(yCoord), Double.parseDouble(zCoord), Float.parseFloat(yaw), Float.parseFloat(pitch));\n }\n\n public static Block getHighestEmptyBlockUnder(Location loc) {\n for (int y = loc.getBlockY(); y > 0; y--) {\n Location floor = new Location(loc.getWorld(), loc.getX(), y, loc.getZ(), loc.getYaw(), loc.getPitch());\n Block block = floor.getBlock();\n if (!block.isEmpty()) {\n return block;\n }\n }\n return loc.getBlock();\n }\n\n public static List<Entity> getNearbyEntities(Location loc, double x, double y, double z) {\n List<Entity> entities = new ArrayList<Entity>();\n for (Chunk chunk : getRelativeChunks(loc.getChunk())) {\n for (Entity entity : chunk.getEntities()) {\n Location entLoc = entity.getLocation();\n if (Math.abs(entLoc.getX() - loc.getX()) <= x && Math.abs(entLoc.getY() - loc.getY()) <= y && Math.abs(entLoc.getZ() - loc.getZ()) <= z && !entities.contains(entity)) {\n entities.add(entity);\n }\n }\n }\n return entities;\n }\n\n public static Location getNearbyLocation(Location loc, double minXdif, double maxXdif, double minYdif, double maxYdif, double minZdif, double maxZdif) {\n double modX = difInRandDirection(maxXdif, minXdif);\n double modY = difInRandDirection(maxXdif, minXdif);\n double modZ = difInRandDirection(maxXdif, minXdif);\n return loc.clone().add(modX, modY, modZ);\n }\n\n public static String getNMSVersionSlug() {\n return nms_version;\n }\n\n /**\n * Gets all nearby chunks\n * @param chunk The chunk to find relatives\n * @return All nearby chunks, including the one passed as a parameter\n */\n public static Chunk[] getRelativeChunks(Chunk chunk) {\n World world = chunk.getWorld();\n return new Chunk[] {\n chunk, //TODO check current chunk?\n world.getChunkAt(chunk.getX() - 16, chunk.getZ() - 16),\n world.getChunkAt(chunk.getX() - 16, chunk.getZ()),\n world.getChunkAt(chunk.getX(), chunk.getZ() - 16),\n world.getChunkAt(chunk.getX(), chunk.getZ()), \n world.getChunkAt(chunk.getX() + 16, chunk.getZ() - 16),\n world.getChunkAt(chunk.getX() - 16, chunk.getZ() + 16),\n world.getChunkAt(chunk.getX() + 16, chunk.getZ()), \n world.getChunkAt(chunk.getX(), chunk.getZ() + 16)\n };\n }\n\n public static Block getSecondChest(Block b) {\n BlockFace[] faces = new BlockFace[] {BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST};\n for (BlockFace face : faces) {\n Block bl = b.getRelative(face);\n if (bl.getState() instanceof Chest || bl.getState() instanceof DoubleChest) {\n return bl;\n }\n }\n return null;\n }\n\n public static boolean isDoubleChest(Block block) {\n if (block == null || !(block.getState() instanceof Chest)) {\n return false;\n }\n Chest chest = (Chest) block.getState();\n return chest.getInventory().getContents().length == 54;\n }\n\n public static boolean isEnchantableLikeSwords(ItemStack item) {\n return swords.Contains(item.getType());\n }\n\n public static boolean locationMatch(Location loc1, Location loc2) {\n boolean nearX = Math.floor(loc1.getBlockX()) == Math.floor(loc2.getBlockX());\n boolean nearY = Math.floor(loc1.getBlockY()) == Math.floor(loc2.getBlockY());\n boolean nearZ = Math.floor(loc1.getBlockZ()) == Math.floor(loc2.getBlockZ());\n return nearX && nearY && nearZ;\n }\n\n public static boolean locationMatch(Location loc1, Location loc2, int distance) {// TODO this method is exact, fix\n return Math.abs(loc1.getX() - loc2.getX()) <= distance && Math.abs(loc1.getY() - loc2.getY()) <= distance && Math.abs(loc1.getZ() - loc2.getZ()) <= distance;\n }\n\n public static boolean locationMatchExact(Location loc1, Location loc2) {\n return locationMatchExact(loc1, loc2, 0);\n }\n\n public static boolean locationMatchExact(Location loc1, Location loc2, double distance) {\n return loc1.distanceSquared(loc2) <= Math.pow(distance, 2);\n }\n\n public static void setChestOpened(List<Player> players, Block block, boolean opened) {\n if (block == null || !(block.getState() instanceof Chest)) {\n return;\n }\n byte open = opened ? (byte) 1 : (byte) 0;\n for (Player player : players) {\n player.playNote(block.getLocation(), (byte) 1, open);\n if (isDoubleChest(block)) {\n player.playNote(getSecondChest(block).getLocation(), (byte) 1, open);\n }\n }\n }\n\n public static void setChestOpened(Player player, Block block, boolean opened) {\n if (block == null || !(block.getState() instanceof Chest)) {\n return;\n }\n byte open = opened ? (byte) 1 : (byte) 0;\n player.playNote(block.getLocation(), (byte) 1, open);\n if (isDoubleChest(block)) {\n player.playNote(getSecondChest(block).getLocation(), (byte) 1, open);\n }\n }\n\n private static double difInRandDirection(double max, double min) {\n return (rand.nextBoolean() ? 1 : -1) * (rand.nextDouble() * Math.abs(max - min) + Math.abs(min));\n }\n}"
] | import java.util.HashMap;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerMoveEvent;
import com.github.jamesnorris.ablockalypse.Ablockalypse;
import com.github.jamesnorris.ablockalypse.DataContainer;
import com.github.jamesnorris.ablockalypse.aspect.Barrier;
import com.github.jamesnorris.ablockalypse.aspect.ZAPlayer;
import com.github.jamesnorris.ablockalypse.enumerated.ZAPerk;
import com.github.jamesnorris.ablockalypse.utility.BukkitUtility; | package com.github.jamesnorris.ablockalypse.event.bukkit;
public class PlayerMove implements Listener {
private DataContainer data = Ablockalypse.getData();
private HashMap<String, Double> PHDPlayers = new HashMap<String, Double>();
public boolean isMoving(PlayerMoveEvent event) {
return isMoving(event, 0);
}
public boolean isMoving(PlayerMoveEvent event, double threshold) {
Location from = event.getFrom();
Location to = event.getTo();
boolean anyX = Math.abs(to.getX() - from.getX()) < threshold;
boolean upY = from.getY() - to.getY() < threshold;
boolean anyZ = Math.abs(to.getZ() - from.getZ()) < threshold;
return !anyX || !upY || !anyZ;
}
/* Called whenever a player moves.
* Mostly used for preventing players from going through barriers. */
@EventHandler(priority = EventPriority.HIGHEST) public void PME(PlayerMoveEvent event) {
Player p = event.getPlayer();
Location from = event.getFrom();
Location to = event.getTo();
if (data.isZAPlayer(p)) {
String name = p.getName();
ZAPlayer zap = data.getZAPlayer(p); | if (zap.getPerks().contains(ZAPerk.PHD_FLOPPER)) { | 4 |
TheCBProject/EnderStorage | src/main/java/codechicken/enderstorage/client/render/tile/RenderTileEnderChest.java | [
"public final class Frequency implements Copyable<Frequency> {\n\n public EnumColour left;\n public EnumColour middle;\n public EnumColour right;\n public UUID owner;\n public ITextComponent ownerName;\n\n public Frequency() {\n this(EnumColour.WHITE, EnumColour.WHITE, EnumColour.WHITE);\n }\n\n public Frequency(EnumColour left, EnumColour middle, EnumColour right) {\n this(left, middle, right, null, null);\n }\n\n public Frequency(EnumColour left, EnumColour middle, EnumColour right, UUID owner, ITextComponent ownerName) {\n this.left = left;\n this.middle = middle;\n this.right = right;\n this.owner = owner;\n this.ownerName = ownerName;\n }\n\n public Frequency(CompoundNBT tagCompound) {\n read_internal(tagCompound);\n }\n\n public static Frequency fromString(String left, String middle, String right) {\n return fromString(left, middle, right, null, null);\n }\n\n public static Frequency fromString(String left, String middle, String right, UUID owner, ITextComponent ownerName) {\n EnumColour c1 = EnumColour.fromName(left);\n EnumColour c2 = EnumColour.fromName(middle);\n EnumColour c3 = EnumColour.fromName(right);\n if (c1 == null) {\n throw new RuntimeException(left + \" is an invalid colour!\");\n }\n if (c2 == null) {\n throw new RuntimeException(middle + \" is an invalid colour!\");\n }\n if (c3 == null) {\n throw new RuntimeException(right + \" is an invalid colour!\");\n }\n return new Frequency(c1, c2, c3, owner, ownerName);\n }\n\n public Frequency setLeft(EnumColour left) {\n if (left != null) {\n this.left = left;\n }\n return this;\n }\n\n public Frequency setMiddle(EnumColour middle) {\n if (middle != null) {\n this.middle = middle;\n }\n return this;\n }\n\n public Frequency setRight(EnumColour right) {\n if (right != null) {\n this.right = right;\n }\n return this;\n }\n\n public Frequency setOwner(UUID owner) {\n this.owner = owner;\n return this;\n }\n\n public Frequency setOwnerName(ITextComponent ownerName) {\n this.ownerName = ownerName;\n return this;\n }\n\n public boolean hasOwner() {\n return owner != null && ownerName != null;\n }\n\n public Frequency set(EnumColour[] colours) {\n setLeft(colours[0]);\n setMiddle(colours[1]);\n setRight(colours[2]);\n return this;\n }\n\n public Frequency set(Frequency frequency) {\n setLeft(frequency.left);\n setMiddle(frequency.middle);\n setRight(frequency.right);\n setOwner(frequency.owner);\n setOwnerName(frequency.ownerName);\n return this;\n }\n\n public EnumColour getLeft() {\n return left;\n }\n\n public EnumColour getMiddle() {\n return middle;\n }\n\n public EnumColour getRight() {\n return right;\n }\n\n public UUID getOwner() {\n return owner;\n }\n\n public ITextComponent getOwnerName() {\n return ownerName;\n }\n\n public EnumColour[] toArray() {\n return new EnumColour[] { left, middle, right };\n }\n\n protected Frequency read_internal(CompoundNBT tagCompound) {\n left = EnumColour.fromWoolMeta(tagCompound.getInt(\"left\"));\n middle = EnumColour.fromWoolMeta(tagCompound.getInt(\"middle\"));\n right = EnumColour.fromWoolMeta(tagCompound.getInt(\"right\"));\n if (tagCompound.hasUUID(\"owner\")) {\n owner = tagCompound.getUUID(\"owner\");\n }\n if (tagCompound.contains(\"owner_name\")) {\n ownerName = ITextComponent.Serializer.fromJson(tagCompound.getString(\"owner_name\"));\n }\n return this;\n }\n\n protected CompoundNBT write_internal(CompoundNBT tagCompound) {\n tagCompound.putInt(\"left\", left.getWoolMeta());\n tagCompound.putInt(\"middle\", middle.getWoolMeta());\n tagCompound.putInt(\"right\", right.getWoolMeta());\n if (owner != null) {\n tagCompound.putUUID(\"owner\", owner);\n }\n if (ownerName != null) {\n tagCompound.putString(\"owner_name\", ITextComponent.Serializer.toJson(ownerName));\n }\n return tagCompound;\n }\n\n public CompoundNBT writeToNBT(CompoundNBT tagCompound) {\n write_internal(tagCompound);\n return tagCompound;\n }\n\n public void writeToPacket(MCDataOutput packet) {\n packet.writeCompoundNBT(write_internal(new CompoundNBT()));\n }\n\n public static Frequency readFromPacket(MCDataInput packet) {\n return new Frequency(packet.readCompoundNBT());\n }\n\n public static Frequency readFromStack(ItemStack stack) {\n if (stack.hasTag()) {\n CompoundNBT stackTag = stack.getTag();\n if (stackTag.contains(\"Frequency\")) {\n return new Frequency(stackTag.getCompound(\"Frequency\"));\n }\n }\n return new Frequency();\n }\n\n public ItemStack writeToStack(ItemStack stack) {\n CompoundNBT tagCompound = stack.getOrCreateTag();\n tagCompound.put(\"Frequency\", write_internal(new CompoundNBT()));\n return stack;\n }\n\n public String toModelLoc() {\n return \"left=\" + getLeft().getSerializedName() + \",middle=\" + getMiddle().getSerializedName() + \",right=\" + getRight().getSerializedName() + \",owned=\" + hasOwner();\n }\n\n @Override\n public String toString() {\n String owner = \"\";\n if (hasOwner()) {\n owner = \",owner=\" + this.owner;\n }\n return \"left=\" + getLeft().getSerializedName() + \",middle=\" + getMiddle().getSerializedName() + \",right=\" + getRight().getSerializedName() + owner;\n }\n\n public ITextComponent getTooltip() {\n return new TranslationTextComponent(getLeft().getUnlocalizedName())//\n .append(\"/\")//\n .append(new TranslationTextComponent(getMiddle().getUnlocalizedName()))//\n .append(\"/\")//\n .append(new TranslationTextComponent(getRight().getUnlocalizedName()));\n }\n\n @Override\n public int hashCode() {\n return toString().hashCode();\n }\n\n @Override\n public Frequency copy() {\n return new Frequency(this.left, this.middle, this.right, this.owner, this.ownerName);\n }\n}",
"public class BlockEnderChest extends BlockEnderStorage {\n\n private static final IndexedVoxelShape CHEST = new IndexedVoxelShape(VoxelShapeCache.getShape(new Cuboid6(1 / 16D, 0, 1 / 16D, 15 / 16D, 14 / 16D, 15 / 16D)), 0);\n private static final IndexedVoxelShape[][] BUTTONS = new IndexedVoxelShape[4][3];\n private static final IndexedVoxelShape[] LATCH = new IndexedVoxelShape[4];\n\n private static final VoxelShape[][] SHAPES = new VoxelShape[4][2];\n\n public static final Transformation[] buttonT = new Transformation[3];\n\n static {\n for (int button = 0; button < 3; button++) {\n buttonT[button] = new Translation(-(3 / 16D) + ((3D / 16D) * button), 14D / 16D, 0);\n }\n for (int rot = 0; rot < 4; rot++) {\n //Build buttons and latch.\n for (int button = 0; button < 3; button++) {\n Cuboid6 cuboid = TileFrequencyOwner.selection_button.copy();\n cuboid.apply(new Translation(0.5, 0, 0.5));\n cuboid.apply(buttonT[button]);\n cuboid.apply(new Rotation((-90 * (rot)) * MathHelper.torad, Vector3.Y_POS).at(new Vector3(0.5, 0, 0.5)));\n BUTTONS[rot][button] = new IndexedVoxelShape(VoxelShapeCache.getShape(cuboid), button + 1);\n }\n LATCH[rot] = new IndexedVoxelShape(VoxelShapeCache.getShape(new Cuboid6(new EnderKnobSlot(rot).getSelectionBB())), 4);\n\n //Build all VoxelShapes.\n for (int state = 0; state < 2; state++) {\n ImmutableSet.Builder<IndexedVoxelShape> cuboids = ImmutableSet.builder();\n cuboids.add(CHEST);\n if (state == 0) {\n cuboids.add(BUTTONS[rot]);\n cuboids.add(LATCH[rot]);\n }\n SHAPES[rot][state] = new MultiIndexedVoxelShape(CHEST, cuboids.build());\n }\n }\n }\n\n public BlockEnderChest(Properties properties) {\n super(properties);\n }\n\n @Override\n public VoxelShape getShape(BlockState state, IBlockReader worldIn, BlockPos pos, ISelectionContext context) {\n VoxelShape shape = CHEST;\n TileEntity t = worldIn.getBlockEntity(pos);\n if (t instanceof TileEnderChest) {\n TileEnderChest tile = (TileEnderChest) t;\n shape = SHAPES[tile.rotation][tile.getRadianLidAngle(0) >= 0 ? 0 : 1];\n }\n return shape;\n }\n\n @Override\n public boolean hasAnalogOutputSignal(BlockState state) {\n return true;\n }\n\n @Override\n public boolean hasTileEntity(BlockState state) {\n return true;\n }\n\n @Nullable\n @Override\n public TileEntity createTileEntity(BlockState state, IBlockReader world) {\n return new TileEnderChest();\n }\n\n}",
"public class ButtonModelLibrary {\n\n public static CCModel button;\n\n static {\n generateButton();\n }\n\n private static void generateButton() {\n button = CCModel.quadModel(20);\n Vector3 min = TileFrequencyOwner.selection_button.min;\n Vector3 max = TileFrequencyOwner.selection_button.max;\n Vector3[] corners = new Vector3[8];\n corners[0] = new Vector3(min.x, min.y, min.z);\n corners[1] = new Vector3(max.x, min.y, min.z);\n corners[3] = new Vector3(min.x, max.y, min.z);\n corners[2] = new Vector3(max.x, max.y, min.z);\n corners[4] = new Vector3(min.x, min.y, max.z);\n corners[5] = new Vector3(max.x, min.y, max.z);\n corners[7] = new Vector3(min.x, max.y, max.z);\n corners[6] = new Vector3(max.x, max.y, max.z);\n\n int i = 0;\n Vertex5[] verts = button.verts;\n\n verts[i++] = new Vertex5(corners[7], 0.0938, 0.0625);\n verts[i++] = new Vertex5(corners[6], 0.1562, 0.0625);\n verts[i++] = new Vertex5(corners[2], 0.1562, 0.1875);\n verts[i++] = new Vertex5(corners[3], 0.0938, 0.1875);\n\n verts[i++] = new Vertex5(corners[4], 0.0938, 0.0313);\n verts[i++] = new Vertex5(corners[5], 0.1562, 0.0624);\n verts[i++] = new Vertex5(corners[6], 0.1562, 0.0624);\n verts[i++] = new Vertex5(corners[7], 0.0938, 0.0313);\n\n verts[i++] = new Vertex5(corners[0], 0.0938, 0.2186);\n verts[i++] = new Vertex5(corners[3], 0.0938, 0.1876);\n verts[i++] = new Vertex5(corners[2], 0.1562, 0.1876);\n verts[i++] = new Vertex5(corners[1], 0.1562, 0.2186);\n\n verts[i++] = new Vertex5(corners[6], 0.1563, 0.0626);\n verts[i++] = new Vertex5(corners[5], 0.1874, 0.0626);\n verts[i++] = new Vertex5(corners[1], 0.1874, 0.1874);\n verts[i++] = new Vertex5(corners[2], 0.1563, 0.1874);\n\n verts[i++] = new Vertex5(corners[7], 0.0937, 0.0626);\n verts[i++] = new Vertex5(corners[3], 0.0937, 0.1874);\n verts[i++] = new Vertex5(corners[0], 0.0626, 0.1874);\n verts[i++] = new Vertex5(corners[4], 0.0626, 0.0626);\n\n button.computeNormals();\n }\n}",
"public class ModelEnderChest {\n\n public ModelRenderer chestLid;\n public ModelRenderer chestBelow;\n public ModelRenderer chestKnob;\n public ModelRenderer diamondKnob;\n\n public ModelEnderChest() {\n chestLid = new ModelRenderer(64, 64, 0, 0);\n chestLid.addBox(0.0F, -5F, -14F, 14, 5, 14, 0.0F);\n chestLid.x = 1.0F;\n chestLid.y = 7F;\n chestLid.z = 15F;\n chestKnob = new ModelRenderer(64, 64, 0, 0);\n chestKnob.addBox(-1F, -2F, -15F, 2, 4, 1, 0.0F);\n chestKnob.x = 8F;\n chestKnob.y = 7F;\n chestKnob.z = 15F;\n diamondKnob = new ModelRenderer(64, 64, 0, 5);\n diamondKnob.addBox(-1F, -2F, -15F, 2, 4, 1, 0.0F);\n diamondKnob.x = 8F;\n diamondKnob.y = 7F;\n diamondKnob.z = 15F;\n chestBelow = new ModelRenderer(64, 64, 0, 19);\n chestBelow.addBox(0.0F, 0.0F, 0.0F, 14, 10, 14, 0.0F);\n chestBelow.x = 1.0F;\n chestBelow.y = 6F;\n chestBelow.z = 1.0F;\n }\n\n public void render(MatrixStack stack, IVertexBuilder builder, int packedLight, int packedOverlay, boolean personal) {\n chestKnob.xRot = chestLid.xRot;\n diamondKnob.xRot = chestLid.xRot;\n chestLid.render(stack, builder, packedLight, packedOverlay);\n chestBelow.render(stack, builder, packedLight, packedOverlay);\n if (personal) {\n diamondKnob.render(stack, builder, packedLight, packedOverlay);\n } else {\n chestKnob.render(stack, builder, packedLight, packedOverlay);\n }\n }\n\n}",
"public class RenderCustomEndPortal {\n\n private static final FloatBuffer texBuffer = GLAllocation.createFloatBuffer(16);\n private static final List<RenderType.State> RENDER_STATES = IntStream.range(0, 16)//\n .mapToObj(i -> RenderType.State.builder()//\n .setTransparencyState(i == 0 ? RenderType.TRANSLUCENT_TRANSPARENCY : RenderType.ADDITIVE_TRANSPARENCY)//\n .setTextureState(new RenderState.TextureState(i == 0 ? EndPortalTileEntityRenderer.END_SKY_LOCATION : EndPortalTileEntityRenderer.END_PORTAL_LOCATION, false, false))//\n .createCompositeState(false)//\n )//\n .collect(ImmutableList.toImmutableList());\n\n private final Random randy = new Random();\n\n private final double surfaceY;\n private final double surfaceX1;\n private final double surfaceX2;\n private final double surfaceZ1;\n private final double surfaceZ2;\n\n public RenderCustomEndPortal(double y, double x1, double x2, double z1, double z2) {\n surfaceY = y;\n surfaceX1 = x1;\n surfaceX2 = x2;\n surfaceZ1 = z1;\n surfaceZ2 = z2;\n }\n\n public void render(Matrix4 mat, IRenderTypeBuffer getter, double yToCamera) {\n Vector3d projectedView = TileEntityRendererDispatcher.instance.camera.getPosition();\n mat = mat.copy();//Defensive copy, prevent external modifications.\n randy.setSeed(31100L);\n for (int i = 0; i < 16; i++) {\n RenderType.State state = RENDER_STATES.get(i);\n EndPortalRenderType renderType = new EndPortalRenderType(i, yToCamera, projectedView, mat, state);\n IVertexBuilder builder = getter.getBuffer(renderType);\n float r = (randy.nextFloat() * 0.5F + 0.1F) * renderType.f7;\n float g = (randy.nextFloat() * 0.5F + 0.4F) * renderType.f7;\n float b = (randy.nextFloat() * 0.5F + 0.5F) * renderType.f7;\n if (i == 0) {\n r = g = b = 1.0F * renderType.f7;\n }\n builder.vertex(surfaceX1, surfaceY, surfaceZ1).color(r, g, b, 1.0F).endVertex();\n builder.vertex(surfaceX1, surfaceY, surfaceZ2).color(r, g, b, 1.0F).endVertex();\n builder.vertex(surfaceX2, surfaceY, surfaceZ2).color(r, g, b, 1.0F).endVertex();\n builder.vertex(surfaceX2, surfaceY, surfaceZ1).color(r, g, b, 1.0F).endVertex();\n }\n }\n\n private static FloatBuffer bufferTexData(float f, float f1, float f2, float f3) {\n texBuffer.clear();\n texBuffer.put(f).put(f1).put(f2).put(f3);\n texBuffer.flip();\n return texBuffer;\n }\n\n public class EndPortalRenderType extends RenderType {\n\n private final int idx;\n private final Vector3d projectedView;\n private final Matrix4 mat;\n private final State state;\n\n //I have no idea what these field names could be changed to, blame decompiler. #borrowed form mojang\n public final float f5;\n public final float f6;\n public final float f7;\n public final float f8;\n public final float f9;\n public final float f10;\n public final float f11;\n\n public EndPortalRenderType(int idx, double posY, Vector3d projectedView, Matrix4 mat, RenderType.State state) {\n super(\"enderstorage:end_portal\", DefaultVertexFormats.POSITION_COLOR, GL11.GL_QUADS, 256, false, true, null, null);\n this.idx = idx;\n this.projectedView = projectedView;\n this.mat = mat;\n this.state = state;\n f5 = idx == 0 ? 65F : 16 - idx;\n f6 = idx == 0 ? 0.125F : (idx == 1 ? 0.5F : 0.0625F);\n f7 = idx == 0 ? 0.1F : 1.0F / (16 - idx + 1.0F);\n f8 = (float) (-(posY + surfaceY));\n f9 = (float) (f8 + projectedView.y);\n f10 = (float) (f8 + f5 + projectedView.y);\n f11 = (float) (posY + surfaceY) + (f9 / f10);\n }\n\n @Override\n @SuppressWarnings (\"deprecation\")\n public void setupRenderState() {\n state.states.forEach(RenderState::setupRenderState);\n RenderSystem.disableLighting();\n RenderSystem.pushMatrix();//Apply stack here.\n mat.glApply();\n RenderSystem.pushMatrix();\n GlStateManager._translated(projectedView.x, f11, projectedView.z);\n GlStateManager._texGenMode(GlStateManager.TexGen.S, GL11.GL_OBJECT_LINEAR);\n GlStateManager._texGenMode(GlStateManager.TexGen.T, GL11.GL_OBJECT_LINEAR);\n GlStateManager._texGenMode(GlStateManager.TexGen.R, GL11.GL_OBJECT_LINEAR);\n GlStateManager._texGenMode(GlStateManager.TexGen.Q, GL11.GL_EYE_LINEAR);\n GlStateManager._texGenParam(GlStateManager.TexGen.S, GL11.GL_OBJECT_PLANE, bufferTexData(1.0F, 0.0F, 0.0F, 0.0F));\n GlStateManager._texGenParam(GlStateManager.TexGen.T, GL11.GL_OBJECT_PLANE, bufferTexData(0.0F, 0.0F, 1.0F, 0.0F));\n GlStateManager._texGenParam(GlStateManager.TexGen.R, GL11.GL_OBJECT_PLANE, bufferTexData(0.0F, 0.0F, 0.0F, 1.0F));\n GlStateManager._texGenParam(GlStateManager.TexGen.Q, GL11.GL_EYE_PLANE, bufferTexData(0.0F, 1.0F, 0.0F, 0.0F));\n GlStateManager._enableTexGen(GlStateManager.TexGen.S);\n GlStateManager._enableTexGen(GlStateManager.TexGen.T);\n GlStateManager._enableTexGen(GlStateManager.TexGen.R);\n GlStateManager._enableTexGen(GlStateManager.TexGen.Q);\n RenderSystem.popMatrix();\n RenderSystem.matrixMode(GL11.GL_TEXTURE);\n RenderSystem.pushMatrix();\n RenderSystem.loadIdentity();\n RenderSystem.translatef(0.0F, System.currentTimeMillis() % 700000L / 700000F, 0.0F);\n RenderSystem.scalef(f6, f6, f6);\n RenderSystem.translatef(0.5F, 0.5F, 0.0F);\n RenderSystem.rotatef((idx * idx * 4321 + idx * 9) * 2.0F, 0.0F, 0.0F, 1.0F);\n RenderSystem.translatef(-0.5F, -0.5F, 0.0F);\n RenderSystem.translated(-projectedView.x, -projectedView.z, -projectedView.y);\n float f92 = f8 + (float) projectedView.y;\n RenderSystem.translated((projectedView.x * f5) / f92, (projectedView.z * f5) / f92, -projectedView.y + 20);\n }\n\n @Override\n @SuppressWarnings (\"deprecation\")\n public void clearRenderState() {\n RenderSystem.popMatrix();\n RenderSystem.matrixMode(GL11.GL_MODELVIEW);\n RenderSystem.popMatrix();//Pop stack here.\n GlStateManager._disableTexGen(GlStateManager.TexGen.S);\n GlStateManager._disableTexGen(GlStateManager.TexGen.T);\n GlStateManager._disableTexGen(GlStateManager.TexGen.R);\n GlStateManager._disableTexGen(GlStateManager.TexGen.Q);\n state.states.forEach(RenderState::clearRenderState);\n }\n\n @Override\n public boolean equals(Object other) {\n return other == this;\n }\n\n @Override\n public int hashCode() {\n return System.identityHashCode(this);\n }\n }\n}",
"public class TileEnderChest extends TileFrequencyOwner {\n\n public double a_lidAngle;\n public double b_lidAngle;\n public int c_numOpen;\n public int rotation;\n\n private LazyOptional<IItemHandler> itemHandler = LazyOptional.empty();\n\n public static EnderDyeButton[] buttons;\n\n static {\n buttons = new EnderDyeButton[3];\n for (int i = 0; i < 3; i++) {\n buttons[i] = new EnderDyeButton(i);\n }\n }\n\n public TileEnderChest() {\n super(ModContent.tileEnderChestType);\n }\n\n @Override\n public void tick() {\n super.tick();\n\n if (!level.isClientSide && (level.getGameTime() % 20 == 0 || c_numOpen != getStorage().getNumOpen())) {\n c_numOpen = getStorage().getNumOpen();\n level.blockEvent(getBlockPos(), getBlockState().getBlock(), 1, c_numOpen);\n level.updateNeighborsAt(worldPosition, getBlockState().getBlock());\n }\n\n b_lidAngle = a_lidAngle;\n a_lidAngle = MathHelper.approachLinear(a_lidAngle, c_numOpen > 0 ? 1 : 0, 0.1);\n\n if (b_lidAngle >= 0.5 && a_lidAngle < 0.5) {\n level.playSound(null, getBlockPos(), EnderStorageConfig.useVanillaEnderChestSounds ? ENDER_CHEST_CLOSE : CHEST_CLOSE, SoundCategory.BLOCKS, 0.5F, level.random.nextFloat() * 0.1F + 0.9F);\n } else if (b_lidAngle == 0 && a_lidAngle > 0) {\n level.playSound(null, getBlockPos(), EnderStorageConfig.useVanillaEnderChestSounds ? ENDER_CHEST_OPEN : CHEST_OPEN, SoundCategory.BLOCKS, 0.5F, level.random.nextFloat() * 0.1F + 0.9F);\n }\n }\n\n @Override\n public boolean triggerEvent(int id, int type) {\n if (id == 1) {\n c_numOpen = type;\n return true;\n }\n return false;\n }\n\n public double getRadianLidAngle(float frame) {\n double a = MathHelper.interpolate(b_lidAngle, a_lidAngle, frame);\n a = 1.0F - a;\n a = 1.0F - a * a * a;\n return a * 3.141593 * -0.5;\n }\n\n @Override\n public EnderItemStorage getStorage() {\n return EnderStorageManager.instance(level.isClientSide).getStorage(frequency, EnderItemStorage.TYPE);\n }\n\n @Override\n public void onFrequencySet() {\n itemHandler.invalidate();\n itemHandler = LazyOptional.of(() -> new InvWrapper(getStorage()));\n }\n\n @Override\n public void setRemoved() {\n super.setRemoved();\n itemHandler.invalidate();\n }\n\n @Override\n public void writeToPacket(MCDataOutput packet) {\n super.writeToPacket(packet);\n packet.writeByte(rotation);\n }\n\n @Override\n public void readFromPacket(MCDataInput packet) {\n super.readFromPacket(packet);\n rotation = packet.readUByte() & 3;\n }\n\n @Override\n public void onPlaced(LivingEntity entity) {\n rotation = entity != null ? (int) Math.floor(entity.yRot * 4 / 360 + 2.5D) & 3 : 0;\n onFrequencySet();\n }\n\n @Override\n public CompoundNBT save(CompoundNBT tag) {\n super.save(tag);\n tag.putByte(\"rot\", (byte) rotation);\n return tag;\n }\n\n @Override\n public void load(BlockState state, CompoundNBT tag) {\n super.load(state, tag);\n rotation = tag.getByte(\"rot\") & 3;\n }\n\n @Override\n public boolean activate(PlayerEntity player, int subHit, Hand hand) {\n getStorage().openContainer((ServerPlayerEntity) player, new TranslationTextComponent(getBlockState().getBlock().getDescriptionId()));\n return true;\n }\n\n @Override\n public boolean rotate() {\n if (!level.isClientSide) {\n rotation = (rotation + 1) % 4;\n PacketCustom.sendToChunk(getUpdatePacket(), level, worldPosition.getX() >> 4, worldPosition.getZ() >> 4);\n }\n return true;\n }\n\n @Override\n public int comparatorInput() {\n return itemHandler.map(ItemHandlerHelper::calcRedstoneFromInventory).orElse(0);\n }\n\n @Nonnull\n @Override\n public <T> LazyOptional<T> getCapability(@Nonnull Capability<T> cap, @Nullable Direction side) {\n if (!remove && cap == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) {\n return itemHandler.cast();\n }\n return super.getCapability(cap, side);\n }\n}"
] | import codechicken.enderstorage.api.Frequency;
import codechicken.enderstorage.block.BlockEnderChest;
import codechicken.enderstorage.client.model.ButtonModelLibrary;
import codechicken.enderstorage.client.model.ModelEnderChest;
import codechicken.enderstorage.client.render.RenderCustomEndPortal;
import codechicken.enderstorage.tile.TileEnderChest;
import codechicken.lib.colour.EnumColour;
import codechicken.lib.math.MathHelper;
import codechicken.lib.render.CCModel;
import codechicken.lib.render.CCModelLibrary;
import codechicken.lib.render.CCRenderState;
import codechicken.lib.render.RenderUtils;
import codechicken.lib.util.ClientUtils;
import codechicken.lib.vec.Matrix4;
import codechicken.lib.vec.Rotation;
import codechicken.lib.vec.Translation;
import codechicken.lib.vec.Vector3;
import codechicken.lib.vec.uv.UVTranslation;
import com.mojang.blaze3d.matrix.MatrixStack;
import net.minecraft.client.renderer.IRenderTypeBuffer;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.client.renderer.tileentity.TileEntityRenderer;
import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.vector.Quaternion; | package codechicken.enderstorage.client.render.tile;
/**
* Created by covers1624 on 4/12/2016.
*/
public class RenderTileEnderChest extends TileEntityRenderer<TileEnderChest> {
private static final RenderType chestType = RenderType.entityCutout(new ResourceLocation("enderstorage:textures/enderchest.png"));
private static final RenderType buttonType = RenderType.entitySolid(new ResourceLocation("enderstorage:textures/buttons.png"));
private static final RenderType pearlType = CCModelLibrary.getIcos4RenderType(new ResourceLocation("enderstorage:textures/hedronmap.png"), false);
private static final ModelEnderChest model = new ModelEnderChest(); | private static final RenderCustomEndPortal renderEndPortal = new RenderCustomEndPortal(0.626, 0.188, 0.812, 0.188, 0.812); | 4 |
jacarrichan/bis | src/main/java/com/avicit/bis/hr/user/service/impl/UserServiceImpl.java | [
"public interface UserDao extends IBaseDao<UserModel, Integer> {\n \n List<UserModel> query(int pn, int pageSize, UserQueryModel command);\n\n int countQuery(UserQueryModel command);\n\n}",
"@SuppressWarnings(\"serial\")\n@Entity\n@Table(name = \"tbl_user\")\n@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)\npublic class UserModel extends BaseEntity {\n\n @Id\n @GeneratedValue(strategy = GenerationType.AUTO)\n @Column(name = \"id\", nullable = false)\n private int id;\n \n \n @Pattern(regexp = \"[A-Za-z0-9]{5,20}\", message = \"{username.illegal}\") //java validator验证(用户名字母数字组成,长度为5-10)\n private String username;\n \n @NotEmpty(message = \"{email.illegal}\")\n @Email(message = \"{email.illegal}\") //错误消息会自动到MessageSource中查找\n private String email;\n \n @Pattern(regexp = \"[A-Za-z0-9]{5,20}\", message = \"{password.illegal}\") \n private String password;\n \n @DateFormat( message=\"{register.date.error}\")//自定义的验证器\n private Date registerDate;\n \n public int getId() {\n return id;\n }\n public void setId(int id) {\n this.id = id;\n }\n public String getUsername() {\n return username;\n }\n public void setUsername(String username) {\n this.username = username;\n }\n public String getEmail() {\n return email;\n }\n public void setEmail(String email) {\n this.email = email;\n }\n public String getPassword() {\n return password;\n }\n public void setPassword(String password) {\n this.password = password;\n }\n\n public Date getRegisterDate() {\n return registerDate;\n }\n \n public void setRegisterDate(Date registerDate) {\n this.registerDate = registerDate;\n }\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + id;\n return result;\n }\n @Override\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n if (obj == null)\n return false;\n if (getClass() != obj.getClass())\n return false;\n UserModel other = (UserModel) obj;\n if (id != other.id)\n return false;\n return true;\n }\n \n \n \n}",
"@SuppressWarnings(\"serial\")\npublic class UserQueryModel extends UserModel {\n\n \n}",
"public interface UserService extends BaseService<UserModel, Integer> {\n\n Page<UserModel> query(int pn, int pageSize, UserQueryModel command);\n}",
"public interface IBaseDao<M extends java.io.Serializable, PK extends java.io.Serializable> {\n \n public PK save(M model);\n\n public void saveOrUpdate(M model);\n \n public void update(M model);\n \n public void merge(M model);\n\n public void delete(PK id);\n\n public void deleteObject(M model);\n\n public M get(PK id);\n \n public int countAll();\n\n public List<M> listAll();\n\n public List<M> listAll(int pn, int pageSize);\n \n public List<M> pre(PK pk, int pn, int pageSize);\n public List<M> next(PK pk, int pn, int pageSize);\n \n boolean exists(PK id);\n \n public void flush();\n \n public void clear();\n\n\n\n}",
"public abstract class BaseServiceImpl<M extends java.io.Serializable, PK extends java.io.Serializable>\n\t\timplements BaseService<M, PK> {\n\n\tprotected IBaseDao<M, PK> baseDao;\n\n\tpublic abstract void setBaseDao(IBaseDao<M, PK> baseDao);\n\n\t@Override\n\tpublic M save(M model) {\n\t\tbaseDao.save(model);\n\t\treturn model;\n\t}\n\n\t@Override\n\tpublic void merge(M model) {\n\t\tbaseDao.merge(model);\n\t}\n\n\t@Override\n\tpublic void saveOrUpdate(M model) {\n\t\tbaseDao.saveOrUpdate(model);\n\t}\n\n\t@Override\n\tpublic void update(M model) {\n\t\tbaseDao.update(model);\n\t}\n\n\t@Override\n\tpublic void delete(PK id) {\n\t\tbaseDao.delete(id);\n\t}\n\n\t@Override\n\tpublic void deleteObject(M model) {\n\t\tbaseDao.deleteObject(model);\n\t}\n\n\t@Override\n\tpublic M get(PK id) {\n\t\treturn baseDao.get(id);\n\t}\n\n\t@Override\n\tpublic int countAll() {\n\t\treturn baseDao.countAll();\n\t}\n\n\t@Override\n\tpublic List<M> listAll() {\n\t\treturn baseDao.listAll();\n\t}\n\n\t@Override\n\tpublic Page<M> listAll(int pn) {\n\n\t\treturn this.listAll(pn, Constants.DEFAULT_PAGE_SIZE);\n\t}\n\n\tpublic Page<M> listAllWithOptimize(int pn) {\n\t\treturn this.listAllWithOptimize(pn, Constants.DEFAULT_PAGE_SIZE);\n\t}\n\n\t@Override\n\tpublic Page<M> listAll(int pn, int pageSize) {\n\t\tInteger count = countAll();\n\t\tList<M> items = baseDao.listAll(pn, pageSize);\n\t\treturn PageUtil.getPage(count, pn, items, pageSize);\n\t}\n\n\tpublic Page<M> listAllWithOptimize(int pn, int pageSize) {\n\t\tInteger count = countAll();\n\t\tList<M> items = baseDao.listAll(pn, pageSize);\n\t\treturn PageUtil.getPage(count, pn, items, pageSize);\n\t}\n\n\t@Override\n\tpublic Page<M> pre(PK pk, int pn, int pageSize) {\n\t\tInteger count = countAll();\n\t\tList<M> items = baseDao.pre(pk, pn, pageSize);\n\t\treturn PageUtil.getPage(count, pn, items, pageSize);\n\t}\n\n\t@Override\n\tpublic Page<M> next(PK pk, int pn, int pageSize) {\n\t\tInteger count = countAll();\n\t\tList<M> items = baseDao.next(pk, pn, pageSize);\n\t\treturn PageUtil.getPage(count, pn, items, pageSize);\n\t}\n\n\t@Override\n\tpublic Page<M> pre(PK pk, int pn) {\n\t\treturn pre(pk, pn, Constants.DEFAULT_PAGE_SIZE);\n\t}\n\n\t@Override\n\tpublic Page<M> next(PK pk, int pn) {\n\t\treturn next(pk, pn, Constants.DEFAULT_PAGE_SIZE);\n\t}\n\n}",
"public class Page<E> {\n private boolean hasPre;//是否首页\n private boolean hasNext;//是否尾页\n private List<E> items;//当前页包含的记录列表\n private int index;//当前页页码(起始为1)\n private IPageContext<E> context;\n \n public IPageContext<E> getContext() {\n return this.context;\n }\n\n public void setContext(IPageContext<E> context) {\n this.context = context;\n }\n\n public int getIndex() {\n return this.index;\n }\n\n public void setIndex(int index) {\n this.index = index;\n }\n\n public boolean isHasPre() {\n return this.hasPre;\n }\n\n public void setHasPre(boolean hasPre) {\n this.hasPre = hasPre;\n }\n\n public boolean isHasNext() {\n return this.hasNext;\n }\n\n public void setHasNext(boolean hasNext) {\n this.hasNext = hasNext;\n }\n\n public List<E> getItems() {\n return this.items == null ? Collections.<E>emptyList() : this.items;\n }\n\n public void setItems(List<E> items) {\n this.items = items;\n }\n \n}",
"public class PageUtil {\n \n private static final Logger LOGGER = LoggerFactory.getLogger(PageUtil.class);\n /**\n * 获取主键时缓存\n */\n private static Map<Class<?>, Field> classPKMap = new WeakHashMap<Class<?>, Field>();\n \n /**\n * 不关心总记录数\n * @param pageNumber\n * @param pageSize\n * @return\n */\n public static int getPageStart(int pageNumber, int pageSize) {\n return (pageNumber - 1) * pageSize;\n }\n \n /**\n * 计算分页获取数据时游标的起始位置\n * \n * @param totalCount 所有记录总和\n * @param pageNumber 页码,从1开始\n * @return\n */\n public static int getPageStart(int totalCount, int pageNumber, int pageSize) {\n int start = (pageNumber - 1) * pageSize;\n if (start >= totalCount) {\n start = 0;\n }\n\n return start;\n }\n\n /**\n * 构造分页对象\n * \n * @param totalCount 满足条件的所有记录总和\n * @param pageNumber 本次分页的页码\n * @param items\n * @return\n */\n public static <E> Page<E> getPage(int totalCount, int pageNumber, List<E> items, int pageSize) {\n IPageContext<E> pageContext = new QuickPageContext<E>(totalCount, pageSize, items);\n return pageContext.getPage(pageNumber);\n }\n \n public static Field getPkField(Class<?> cls) {\n Field pkField = classPKMap.get(cls);\n if(pkField == null) {\n synchronized (KeySynchronizer.acquire(cls)) {\n Field[] fields = cls.getDeclaredFields();\n for(Field field : fields) {\n if(field.isAnnotationPresent(Id.class)) {\n pkField = field;\n pkField.setAccessible(true);\n classPKMap.put(cls, pkField);\n }\n }\n }\n }\n if(pkField == null) {\n LOGGER.error(\"page error,{} : pk null\", cls);\n }\n return pkField;\n }\n \n public static <T> String getIdValue(T obj) {\n if(obj == null) {\n return \"\";\n }\n String retVal = \"\";\n Field pkField = getPkField(obj.getClass());\n try {\n retVal = pkField.get(obj).toString();\n } catch (Exception e) {\n LOGGER.error(\"page error,{} : get id value\", obj);\n }\n return retVal;\n }\n public static <T> String getIdName(T obj) {\n if(obj == null) {\n return \"\";\n }\n String retVal = \"\";\n Field pkField = getPkField(obj.getClass());\n try {\n retVal = pkField.getName();\n } catch (Exception e) {\n LOGGER.error(\"page error,{} : get id name\", obj);\n }\n return retVal;\n }\n}"
] | import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import com.avicit.bis.hr.user.dao.UserDao;
import com.avicit.bis.hr.user.model.UserModel;
import com.avicit.bis.hr.user.model.UserQueryModel;
import com.avicit.bis.hr.user.service.UserService;
import com.avicit.framework.support.dao.hibernate.IBaseDao;
import com.avicit.framework.support.service.impl.BaseServiceImpl;
import com.avicit.framework.web.support.pagination.Page;
import com.avicit.framework.web.support.pagination.PageUtil; | package com.avicit.bis.hr.user.service.impl;
/**
* User: Zhang Kaitao
* Date: 12-1-4 上午11:06
* Version: 1.0
*/
@Service("UserService")
public class UserServiceImpl extends BaseServiceImpl<UserModel, Integer> implements UserService {
protected static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);
private UserDao userDao;
@Autowired
@Qualifier("UserDao")
@Override
public void setBaseDao(IBaseDao<UserModel, Integer> userDao) {
this.baseDao = userDao;
this.userDao = (UserDao) userDao;
}
@Override
public Page<UserModel> query(int pn, int pageSize, UserQueryModel command) { | return PageUtil.getPage(userDao.countQuery(command) ,pn, userDao.query(pn, pageSize, command), pageSize); | 7 |
rrauschenbach/mobi-api4java | src/test/java/org/rr/mobi4java/MobiTestJapaneseTairytalesBook.java | [
"static byte[] createJpegCover(int width, int height) throws IOException {\n\tBufferedImage bufferedImage = new BufferedImage(100, 200, BufferedImage.TYPE_INT_RGB);\n\tGraphics2D g = bufferedImage.createGraphics();\n\tg.drawLine(0, 0, width, height);\n\tg.drawLine(width, 0, 0, height);\n\tg.dispose();\n\t\t\n\treturn getImageBytes(bufferedImage, \"image/jpeg\");\n}",
"static MobiDocument createReader(byte[] mobiData) throws IOException {\n\treturn readDoc(mobiData);\n}",
"static byte[] getResourceData(String resource) throws IOException {\n\treturn IOUtils.toByteArray(MobiTestUtils.class.getResourceAsStream(resource));\n}",
"static MobiDocument reReadDocument(MobiDocument doc) throws IOException {\n\tbyte[] newMobiData = writeDoc(doc);\n\tMobiDocument newDoc = readDoc(newMobiData);\n\treturn newDoc;\n}",
"static MobiDocument readDoc(byte[] newMobiData) throws IOException {\n\treturn new MobiReader().read(new ByteArrayInputStream(newMobiData));\n}",
"static byte[] writeDoc(MobiDocument doc) throws IOException {\n\tByteArrayOutputStream out = new ByteArrayOutputStream();\n\tnew MobiWriter(doc).write(out);\n\treturn out.toByteArray();\n}",
"public class DateRecordDelegate extends StringRecordDelegate implements RecordDelegate {\n\t\n\tprivate static final String DEFAULT_DATE_FORMAT_PATTERN = \"yyyy-MM-dd'T'HH:mm:ssZ\";\n\t\n\tprivate static final String[] DATE_PATTERN = new String[] { DEFAULT_DATE_FORMAT_PATTERN, \"yyyy-MM-dd\", \"dd.MM.yyyy\", \"MM/dd/yyyy\",\n\t\t\t\"yyyy/MM/dd\", \"yyyy.dd.MM\", \"yyyy-'W'ww-d\", \"yyyy-MM-dd hh:mm'Z'\", \"yyyy-MM-dd hh:mm:Z\", \"EEE, dd MMM yyyy HH:mm:ss z\",\n\t\t\t\"EEE, dd MMM yyyy HH:mm z\", \"dd MMM yyyy HH:mm:ss z\", \"EEE MMM dd HH:mm:ss z yyyy\", \"yyyyMMddhhmmssZ\", \"yyyyMMddhhmmZ\",\n\t\t\t\"yyyyMMddhhmmss\", \"yyyyMMddhhmm\", \"yyyyMMddhhmmZ\", \"'D:'yyyyMMddHHmmZ\", \"yyyy\" };\n\t\n\tpublic DateRecordDelegate(EXTHRecord record) {\n\t\tsuper(record);\n\t}\n\n\t/**\n\t * Get the data of this {@link EXTHRecord} instance as date.\n\t * \n\t * @return A new {@link Date} instance from the data of this {@link EXTHRecord} instance.\n\t * @throws ParseException \n\t */\n\tpublic Date getAsDate() throws ParseException {\n\t\ttry {\n\t\t\treturn DatatypeConverter.parseDate(getAsString(UTF_8)).getTime();\n\t\t} catch(Exception e) {\n\t\t\treturn DateUtils.parseDate(getAsString(UTF_8), DATE_PATTERN);\n\t\t}\n\t}\n\n\t/**\n\t * Set a date as value to this {@link EXTHRecord} instance.\n\t * \n\t * @param date The date used as value for this {@link EXTHRecord} instance.\n\t * @throws IllegalArgumentException if the given date is <code>null</code>.\n\t */\n\tpublic void setDateData(Date date) {\n\t\tif(date == null) {\n\t\t\tthrow new IllegalArgumentException(\"Value must not be null.\");\n\t\t}\n\t\ttry {\n\t\t\tsetStringData(DateFormatUtils.format(date, DEFAULT_DATE_FORMAT_PATTERN), UTF_8);\n\t\t} catch (UnsupportedEncodingException e) {\n\t\t\tthrow new RuntimeException(\"Failed to set date \" + date, e);\n\t\t}\n\t}\n}",
"public class ISBNRecordDelegate extends StringRecordDelegate implements RecordDelegate {\n\n\tprivate static final String ISBN13_PREFIX = \"978\";\n\t\n\tprivate static final String CheckDigits = \"0123456789X0\";\n\n\tpublic ISBNRecordDelegate(EXTHRecord record) {\n\t\tsuper(record);\n\t}\n\t\n\tpublic void setISBN(String isbn) {\n\t\ttry {\n\t\t\tif(isValidISBN(isbn)) {\n\t\t\t\tsetStringData(isbn, UTF_8);\n\t\t\t} else {\n\t\t\t\tthrow new IllegalArgumentException(\"The isbn \" + isbn + \" is not a valid isbn number.\");\n\t\t\t}\n\t\t} catch (UnsupportedEncodingException e) {\n\t\t\tthrow new RuntimeException(\"Failed to set isbn \" + isbn, e);\n\t\t}\n\t}\n\t\n\tpublic boolean isIsbn13() {\n\t\treturn StringUtils.startsWith(getIsbn(), ISBN13_PREFIX) && removeHyphen(getIsbn()).length() == 13;\n\t}\n\n\tpublic String getIsbn() {\n\t\treturn getAsString(UTF_8);\n\t}\n\t\n\tpublic String getAsIsbn13() {\n\t\tif(isIsbn13()) {\n\t\t\treturn removeHyphen(getIsbn());\n\t\t}\n\t\treturn isbn10To13(getIsbn());\n\t}\n\t\n\tpublic String getAsIsbn10() {\n\t\tif(!isIsbn13()) {\n\t\t\treturn removeHyphen(getIsbn());\n\t\t}\n\t\treturn isbn13To10(getIsbn());\n\t}\n\n\tprivate boolean isValidISBN(String isbn) {\n\t\tif(isbn == null) {\n\t\t\treturn false;\n\t\t}\n\t\t\n\t\treturn isValidISBN10(isbn) || isValidISBN13(isbn);\n\t\t\n\t}\n\t\n\tprotected boolean isValidISBN13(String isbn) {\n\t\treturn Pattern.compile(\"97(?:8|9)([ -]?)\\\\d{1,5}\\\\1\\\\d{1,7}\\\\1\\\\d{1,6}\\\\1\\\\d\").matcher(isbn).matches();\n\t}\n\t\n\tprotected boolean isValidISBN10(String isbn) {\n\t\treturn Pattern.compile(\"\\\\d{1,5}([- ]?)\\\\d{1,7}\\\\1\\\\d{1,6}\\\\1(\\\\d|X)\").matcher(isbn).matches();\n\t}\n\n\tprivate static String removeHyphen(String isbn) {\n\t\treturn StringUtils.remove(isbn, \"-\");\n\t}\n\n\t/**\n\t * Change the given character to its integer value.\n\t * \n\t * @return the integer value for the given character.\n\t */\n\tprivate static int charToInt(char c) {\n\t\treturn Character.getNumericValue(c);\n\t}\n\n\tprivate static String isbn13To10(String isbn) {\n\t\tint n = 0;\n\t\tString s9 = removeHyphen(isbn).substring(3, 12);\n\t\tfor (int i = 0; i < 9; i++) {\n\t\t\tint v = charToInt(s9.charAt(i));\n\t\t\tif (v == -1) {\n\t\t\t\tthrow new IllegalArgumentException(\"Failed to convert isbn number \" + isbn);\n\t\t\t} else {\n\t\t\t\tn = n + (10 - i) * v;\n\t\t\t}\n\t\t}\n\t\tn = 11 - (n % 11);\n\t\treturn s9 + CheckDigits.substring(n, n + 1);\n\t}\n\n\tprivate static String isbn10To13(String isbn) {\n\t\tint n = 0;\n\t\tString s12 = ISBN13_PREFIX + removeHyphen(isbn).substring(0, 9);\n\t\tfor (int i = 0; i < 12; i++) {\n\t\t\tint v = charToInt(s12.charAt(i));\n\t\t\tif (v == -1) {\n\t\t\t\tthrow new IllegalArgumentException(\"Failed to convert isbn number \" + isbn);\n\t\t\t} else {\n\t\t\t\tif ((i % 2) == 0) {\n\t\t\t\t\tn = n + v;\n\t\t\t\t} else {\n\t\t\t\t\tn = n + 3 * v;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tn = n % 10;\n\t\tif (n != 0) {\n\t\t\tn = 10 - n;\n\t\t}\n\t\treturn s12 + CheckDigits.substring(n, n + 1);\n\t}\n}",
"public class StringRecordDelegate implements RecordDelegate {\n\t\n\tprivate EXTHRecord record;\n\n\tpublic StringRecordDelegate(EXTHRecord record) {\n\t\tthis.record = record;\n\t}\n\n\t/**\n\t * Get the data of this {@link EXTHRecord} instance as string.\n\t * \n\t * @param encoding The character encoding for the result string. Use {@link MobiDocument#getCharacterEncoding()}.\n\t * @return A new string instance from the data of this {@link EXTHRecord} instance.\n\t */\n\tpublic String getAsString(String encoding) {\n\t\treturn getString(record.getData(), encoding);\n\t}\n\n\t/**\n\t * Set a string as value to this {@link EXTHRecord} instance.\n\t * \n\t * @param str The string used as value for this {@link EXTHRecord} instance.\n\t * @param encoding The character encoding for the given string. Use {@link MobiDocument#getCharacterEncoding()}.\n\t * @throws UnsupportedEncodingException if the given encoding is not supported by the java virtual machine.\n\t * @throws IllegalArgumentException if the given value is <code>null</code>.\n\t */\n\tpublic void setStringData(String str, String encoding) throws UnsupportedEncodingException {\n\t\tif(str == null) {\n\t\t\tthrow new IllegalArgumentException(\"Value must not be null.\");\n\t\t}\n\t\t\n\t\trecord.setData(getBytes(defaultString(str), encoding));\n\t}\n\n\t@Override\n\tpublic EXTHRecord getRecord() {\n\t\treturn record;\n\t}\n}"
] | import static org.apache.commons.lang3.CharEncoding.UTF_8;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.rr.mobi4java.MobiTestUtils.createJpegCover;
import static org.rr.mobi4java.MobiTestUtils.createReader;
import static org.rr.mobi4java.MobiTestUtils.getResourceData;
import static org.rr.mobi4java.MobiTestUtils.reReadDocument;
import static org.rr.mobi4java.MobiTestUtils.readDoc;
import static org.rr.mobi4java.MobiTestUtils.writeDoc;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import org.rr.mobi4java.exth.DateRecordDelegate;
import org.rr.mobi4java.exth.ISBNRecordDelegate;
import org.rr.mobi4java.exth.StringRecordDelegate; | package org.rr.mobi4java;
public class MobiTestJapaneseTairytalesBook {
private static final String JAPANESE_FAIRYTALES_MOBI = "/japanese_fairytales.mobi";
@Test
public void testReadWriteMobiFile() throws IOException { | byte[] mobiData = getResourceData(JAPANESE_FAIRYTALES_MOBI); | 2 |
DSH105/SparkTrail | src/main/java/com/dsh105/sparktrail/trail/EffectHolder.java | [
"public class SparkTrailPlugin extends DSHPlugin {\n\n private YAMLConfig config;\n private YAMLConfig dataConfig;\n private YAMLConfig langConfig;\n public AutoSave AS;\n public SparkTrailAPI api;\n\n public EffectManager EH;\n public SQLEffectManager SQLH;\n\n // Update data\n public boolean update = false;\n public String name = \"\";\n public long size = 0;\n public boolean updateCheck = false;\n\n public static boolean isUsingNetty;\n\n public BoneCP dbPool;\n public CommandMap CM;\n\n public ChatColor primaryColour = ChatColor.GREEN;\n public ChatColor secondaryColour = ChatColor.YELLOW;\n public String prefix = \"\" + ChatColor.DARK_GREEN + \"ST\" + ChatColor.GREEN + \" » \" + ChatColor.RESET;\n public String cmdString = \"trail\";\n\n public void onEnable() {\n super.onEnable();\n\n // meh\n if (Bukkit.getVersion().contains(\"1.7\")) {\n isUsingNetty = true;\n } else if (Bukkit.getVersion().contains(\"1.6\")) {\n isUsingNetty = false;\n }\n\n PluginManager manager = getServer().getPluginManager();\n Logger.initiate(this, \"SparkTrail\", \"[SparkTrail]\");\n\n /*if (!VersionUtil.compareVersions()) {\n ConsoleLogger.log(Logger.LogLevel.NORMAL, ChatColor.GREEN + \"SparkTrail \" + ChatColor.YELLOW\n + this.getDescription().getVersion() + ChatColor.GREEN\n + \" is only compatible with:\");\n ConsoleLogger.log(Logger.LogLevel.NORMAL, ChatColor.YELLOW + \" \" + VersionUtil.getMinecraftVersion() + \"-\" + VersionUtil.getCraftBukkitVersion() + \".\");\n ConsoleLogger.log(Logger.LogLevel.NORMAL, ChatColor.GREEN + \"Initialisation failed. Please update the plugin.\");\n\n manager.disablePlugin(this);\n return;\n }*/\n\n this.api = new SparkTrailAPI();\n\n String[] header = {\"SparkTrail By DSH105\", \"---------------------\",\n \"Configuration for SparkTrail 3\",\n \"See the SparkTrail Wiki before editing this file\"};\n try {\n config = this.getConfigManager().getNewConfig(\"config.yml\", header);\n new ConfigOptions(config);\n } catch (Exception e) {\n Logger.log(Logger.LogLevel.SEVERE, \"Failed to generate Configuration File (config.yml).\", e, true);\n }\n\n config.reloadConfig();\n\n ChatColor colour1 = ChatColor.getByChar(this.getConfig(ConfigType.MAIN).getString(\"primaryChatColour\", \"a\"));\n if (colour1 != null) {\n this.primaryColour = colour1;\n }\n ChatColor colour2 = ChatColor.getByChar(this.getConfig(ConfigType.MAIN).getString(\"secondaryChatColour\", \"e\"));\n if (colour2 != null) {\n this.secondaryColour = colour2;\n }\n\n try {\n dataConfig = this.getConfigManager().getNewConfig(\"data.yml\");\n } catch (Exception e) {\n Logger.log(Logger.LogLevel.SEVERE, \"Failed to generate Configuration File (data.yml).\", e, true);\n }\n dataConfig.reloadConfig();\n\n String[] langHeader = {\"SparkTrail By DSH105\", \"---------------------\",\n \"Language Configuration File\"};\n try {\n langConfig = this.getConfigManager().getNewConfig(\"language.yml\", langHeader);\n try {\n for (Lang l : Lang.values()) {\n String[] desc = l.getDescription();\n langConfig.set(l.getPath(), langConfig.getString(l.getPath(), l.getRaw()\n .replace(\"&a\", \"&\" + this.primaryColour.getChar())\n .replace(\"&e\", \"&\" + this.secondaryColour.getChar())),\n desc);\n }\n langConfig.saveConfig();\n } catch (Exception e) {\n Logger.log(Logger.LogLevel.SEVERE, \"Failed to generate Configuration File (language.yml).\", e, true);\n }\n\n } catch (Exception e) {\n }\n langConfig.reloadConfig();\n\n this.prefix = Lang.PREFIX.toString();\n\n this.EH = new EffectManager();\n this.SQLH = new SQLEffectManager();\n\n if (this.config.getBoolean(\"useSql\", false)) {\n String host = config.getString(\"sql.host\", \"localhost\");\n int port = config.getInt(\"sql.port\", 3306);\n String db = config.getString(\"sql.database\", \"SparkTrail\");\n String user = config.getString(\"sql.username\", \"none\");\n String pass = config.getString(\"sql.password\", \"none\");\n BoneCPConfig bcc = new BoneCPConfig();\n bcc.setJdbcUrl(\"jdbc:mysql://\" + host + \":\" + port + \"/\" + db);\n bcc.setUsername(user);\n bcc.setPassword(pass);\n bcc.setPartitionCount(2);\n bcc.setMinConnectionsPerPartition(3);\n bcc.setMaxConnectionsPerPartition(7);\n bcc.setConnectionTestStatement(\"SELECT 1\");\n try {\n dbPool = new BoneCP(bcc);\n } catch (SQLException e) {\n Logger.log(Logger.LogLevel.SEVERE, \"Failed to connect to MySQL! [MySQL DataBase: \" + db + \"].\", e, true);\n }\n if (dbPool != null) {\n Connection connection = null;\n Statement statement = null;\n try {\n connection = dbPool.getConnection();\n statement = connection.createStatement();\n statement.executeUpdate(\"CREATE TABLE IF NOT EXISTS PlayerEffects (\" +\n \"PlayerName varchar(255),\" +\n \"Effects varchar(255),\" +\n \"PRIMARY KEY (PlayerName)\" +\n \");\");\n\n statement.executeUpdate(\"CREATE TABLE IF NOT EXISTS LocationEffects (\" +\n \"Location varchar(255),\" +\n \"Effects varchar(255),\" +\n \"PRIMARY KEY (Location)\" +\n \");\");\n\n statement.executeUpdate(\"CREATE TABLE IF NOT EXISTS MobEffects (\" +\n \"MobUUID varchar(255),\" +\n \"Effects varchar(255),\" +\n \"PRIMARY KEY (MobUUID)\" +\n \");\");\n } catch (SQLException e) {\n Logger.log(Logger.LogLevel.SEVERE, \"MySQL DataBase Table initiation has failed.\", e, true);\n }\n }\n }\n\n if (this.config.getBoolean(\"autosave\", true)) {\n this.AS = new AutoSave(this.config.getInt(\"autosaveTimer\", 180));\n }\n\n // Register custom commands\n // Command string based off the string defined in config.yml\n try {\n Class craftServer = Class.forName(\"org.bukkit.craftbukkit.\" + VersionUtil.getServerVersion() + \".CraftServer\");\n if (craftServer.isInstance(Bukkit.getServer())) {\n final Field f = craftServer.getDeclaredField(\"commandMap\");\n f.setAccessible(true);\n CM = (CommandMap) f.get(Bukkit.getServer());\n }\n } catch (Exception e) {\n Logger.log(Logger.LogLevel.WARNING, \"Registration of commands failed.\", e, true);\n }\n\n String cmdString = this.config.getString(\"command\", \"trail\");\n if (CM.getCommand(cmdString) != null) {\n Logger.log(Logger.LogLevel.WARNING, \"A command under the name \" + ChatColor.RED + \"/\" + cmdString + ChatColor.YELLOW + \" already exists. Trail Command temporarily registered under \" + ChatColor.RED + \"/st:\" + cmdString, true);\n }\n\n CustomCommand cmd = new CustomCommand(cmdString);\n CM.register(\"st\", cmd);\n cmd.setExecutor(new TrailCommand(cmdString));\n cmd.setTabCompleter(new CommandComplete());\n this.cmdString = cmdString;\n\n manager.registerEvents(new MenuListener(), this);\n manager.registerEvents(new MenuChatListener(), this);\n manager.registerEvents(new PlayerListener(), this);\n manager.registerEvents(new InteractListener(), this);\n manager.registerEvents(new EntityListener(), this);\n\n try {\n Metrics metrics = new Metrics(this);\n metrics.start();\n } catch (IOException e) {\n Logger.log(Logger.LogLevel.WARNING, \"Plugin Metrics (MCStats) has failed to start.\", e, false);\n }\n\n this.checkUpdates();\n }\n\n public void onDisable() {\n Iterator<ItemSpray.ItemSprayRemoveTask> i = ItemSpray.TASKS.iterator();\n while (i.hasNext()) {\n ItemSpray.ItemSprayRemoveTask task = i.next();\n task.executeFinish(false);\n i.remove();\n }\n this.getServer().getScheduler().cancelTasks(this);\n if (this.EH != null) {\n this.EH.clearEffects();\n }\n super.onDisable();\n }\n\n public static SparkTrailPlugin getInstance() {\n return (SparkTrailPlugin) getPluginInstance();\n }\n\n public SparkTrailAPI getAPI() {\n return this.api;\n }\n\n public YAMLConfig getConfig(ConfigType type) {\n if (type == ConfigType.MAIN) {\n return this.config;\n } else if (type == ConfigType.DATA) {\n return this.dataConfig;\n } else if (type == ConfigType.LANG) {\n return this.langConfig;\n }\n return null;\n }\n\n public enum ConfigType {\n MAIN, DATA, LANG;\n }\n\n protected void checkUpdates() {\n if (this.getConfig(ConfigType.MAIN).getBoolean(\"checkForUpdates\", true)) {\n final File file = this.getFile();\n final Updater.UpdateType updateType = this.getConfig(ConfigType.MAIN).getBoolean(\"autoUpdate\", false) ? Updater.UpdateType.DEFAULT : Updater.UpdateType.NO_DOWNLOAD;\n getServer().getScheduler().runTaskAsynchronously(this, new Runnable() {\n @Override\n public void run() {\n Updater updater = new Updater(getInstance(), 47704, file, updateType, false);\n update = updater.getResult() == Updater.UpdateResult.UPDATE_AVAILABLE;\n if (update) {\n name = updater.getLatestName();\n ConsoleLogger.log(ChatColor.GOLD + \"An update is available: \" + name);\n ConsoleLogger.log(ChatColor.GOLD + \"Type /stupdate to update.\");\n }\n }\n });\n }\n }\n\n public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {\n if (commandLabel.equalsIgnoreCase(\"stupdate\")) {\n if (Permission.UPDATE.hasPerm(sender, true, true)) {\n if (updateCheck) {\n @SuppressWarnings(\"unused\")\n Updater updater = new Updater(this, 47704, this.getFile(), Updater.UpdateType.NO_VERSION_CHECK, true);\n return true;\n } else {\n sender.sendMessage(this.prefix + ChatColor.GREEN + \" An update is not available.\");\n return true;\n }\n } else return true;\n } else if (commandLabel.equalsIgnoreCase(\"sparktrail\")) {\n if (Permission.TRAIL.hasPerm(sender, true, true)) {\n PluginDescriptionFile pdFile = this.getDescription();\n sender.sendMessage(secondaryColour + \"-------- SparkTrail --------\");\n sender.sendMessage(primaryColour + \"Author: \" + ChatColor.YELLOW + \"DSH105\");\n sender.sendMessage(primaryColour + \"Description: \" + secondaryColour + pdFile.getDescription());\n sender.sendMessage(primaryColour + \"Version: \" + secondaryColour + pdFile.getVersion());\n sender.sendMessage(primaryColour + \"Website: \" + secondaryColour + pdFile.getWebsite());\n return true;\n } else return true;\n }\n return false;\n }\n}",
"public class ConfigOptions extends Options {\n\n public static ConfigOptions instance;\n\n public ConfigOptions(YAMLConfig config) {\n super(config);\n instance = this;\n this.setDefaults();\n this.setMaxTick();\n }\n\n public int maxTick = 0;\n\n public void setMaxTick() {\n for (String key : config.getConfigurationSection(\"effects\").getKeys(false)) {\n int i = config.getInt(\"effects.\" + key + \".frequency\", 20);\n if (this.maxTick < i) {\n this.maxTick = i;\n }\n }\n\n for (int i = maxTick; i >= maxTick; i++) {\n if (i % 20 == 0) {\n maxTick = i;\n break;\n }\n }\n }\n\n public boolean useSql() {\n return this.config.getBoolean(\"sql.use\", false);\n }\n\n public boolean sqlOverride() {\n if (useSql()) {\n return this.config.getBoolean(\"sql.overrideFile\");\n }\n return false;\n }\n\n @Override\n public void setDefaults() {\n set(\"command\", \"trail\");\n\n set(\"primaryChatColour\", \"a\");\n set(\"secondaryChatColour\", \"e\");\n\n set(\"autoUpdate\", false);\n set(\"checkForUpdates\", true);\n\n set(\"sql.overrideFile\", true, \"If true, data saved to the MySQL Database will override data saved to a file\");\n set(\"sql.use\", false);\n set(\"sql.host\", \"localhost\");\n set(\"sql.port\", 3306);\n set(\"sql.database\", \"SparkTrail\");\n set(\"sql.username\", \"none\");\n set(\"sql.password\", \"none\");\n\n set(\"autosave\", true, \"If true, SparkTrail will autosave all pet data to prevent data\", \"loss in the event of a server crash.\");\n set(\"autosaveTimer\", 180, \"AutoSave interval (in seconds)\");\n set(\"enableMenu\", true);\n\n // Just set this to 1 so we can have a description\n set(\"maxEffectAmount\", 1, \"Maximum amount of effects a player, location or mob is allowed to have. -1 allows an\", \"unlimited number.\");\n\n set(\"maxEffectAmount.player\", 1);\n set(\"maxEffectAmount.location\", 1);\n set(\"maxEffectAmount.mob\", 1);\n\n for (ParticleType pt : ParticleType.values()) {\n String name = pt.toString().toLowerCase();\n set(\"effects.\" + name + \".enable\", true);\n set(\"effects.\" + name + \".frequency\", 20);\n set(\"effects.\" + name + \".playType\", \"normal\");\n }\n\n this.config.saveConfig();\n }\n}",
"public class EffectCreator {\n\n private static EffectHolder createHolder(EffectHolder effectHolder) {\n EffectManager.getInstance().addHolder(effectHolder);\n effectHolder.start();\n return effectHolder;\n }\n\n public static EffectHolder createLocHolder(Location location) {\n EffectHolder effectHolder = new EffectHolder(EffectType.LOCATION);\n effectHolder.updateLocation(location);\n return createHolder(effectHolder);\n }\n\n public static EffectHolder createPlayerHolder(String playerName) {\n EffectHolder effectHolder = new EffectHolder(EffectType.PLAYER);\n effectHolder.getDetails().playerName = playerName;\n return createHolder(effectHolder);\n }\n\n public static EffectHolder createMobHolder(UUID uuid) {\n EffectHolder effectHolder = new EffectHolder(EffectType.MOB);\n effectHolder.getDetails().mobUuid = uuid;\n return createHolder(effectHolder);\n }\n\n public static EffectHolder prepareNew(WaitingData data) {\n EffectHolder eh = null;\n if (data.effectType == EffectHolder.EffectType.LOCATION) {\n eh = EffectManager.getInstance().getEffect(data.location);\n } else if (data.effectType == EffectHolder.EffectType.PLAYER) {\n eh = EffectManager.getInstance().getEffect(data.playerName);\n } else if (data.effectType == EffectHolder.EffectType.MOB) {\n eh = EffectManager.getInstance().getEffect(data.mobUuid);\n }\n\n if (eh == null) {\n if (data.effectType == EffectHolder.EffectType.PLAYER) {\n eh = EffectCreator.createPlayerHolder(data.playerName);\n } else if (data.effectType == EffectHolder.EffectType.LOCATION) {\n Location l = data.location;\n eh = EffectCreator.createLocHolder(l);\n } else if (data.effectType == EffectHolder.EffectType.MOB) {\n eh = EffectCreator.createMobHolder(data.mobUuid);\n }\n }\n return eh;\n }\n\n public static Effect createEffect(EffectHolder effectHolder, ParticleType particleType, Object[] o) {\n Effect e = null;\n\n if (particleType == ParticleType.BLOCKBREAK) {\n if (!checkArray(o, new Class[]{Integer.class, Integer.class})) {\n Logger.log(Logger.LogLevel.WARNING, \"Encountered Class Cast error initiating Trail effect (\" + particleType.toString() + \").\", true);\n return null;\n }\n e = new BlockBreak(effectHolder, (Integer) o[0], (Integer) o[1]);\n } else if (particleType == ParticleType.CRITICAL) {\n if (!checkArray(o, new Class[]{Critical.CriticalType.class})) {\n Logger.log(Logger.LogLevel.WARNING, \"Encountered Class Cast error initiating Trail effect (\" + particleType.toString() + \").\", true);\n return null;\n }\n e = new Critical(effectHolder, (Critical.CriticalType) o[0]);\n } else if (particleType == ParticleType.FIREWORK) {\n if (!checkArray(o, new Class[]{FireworkEffect.class})) {\n Logger.log(Logger.LogLevel.WARNING, \"Encountered Class Cast error initiating Trail effect (\" + particleType.toString() + \").\", true);\n return null;\n }\n e = new Firework(effectHolder, (FireworkEffect) o[0]);\n } else if (particleType == ParticleType.ITEMSPRAY) {\n if (!checkArray(o, new Class[]{Integer.class, Integer.class})) {\n Logger.log(Logger.LogLevel.WARNING, \"Encountered Class Cast error initiating Trail effect (\" + particleType.toString() + \").\", true);\n return null;\n }\n e = new ItemSpray(effectHolder, (Integer) o[0], (Integer) o[1]);\n } else if (particleType == ParticleType.POTION) {\n if (!checkArray(o, new Class[]{Potion.PotionType.class})) {\n Logger.log(Logger.LogLevel.WARNING, \"Encountered Class Cast error initiating Trail effect (\" + particleType.toString() + \").\", true);\n return null;\n }\n e = new Potion(effectHolder, (Potion.PotionType) o[0]);\n } else if (particleType == ParticleType.SMOKE) {\n if (!checkArray(o, new Class[]{Smoke.SmokeType.class})) {\n Logger.log(Logger.LogLevel.WARNING, \"Encountered Class Cast error initiating Trail effect (\" + particleType.toString() + \").\", true);\n return null;\n }\n e = new Smoke(effectHolder, (Smoke.SmokeType) o[0]);\n } else if (particleType == ParticleType.SWIRL) {\n if (!checkArray(o, new Class[]{Swirl.SwirlType.class, UUID.class})) {\n Logger.log(Logger.LogLevel.WARNING, \"Encountered Class Cast error initiating Trail effect (\" + particleType.toString() + \").\", true);\n return null;\n }\n e = new Swirl(effectHolder, (Swirl.SwirlType) o[0], (UUID) o[1]);\n } else if (particleType == ParticleType.SOUND) {\n if (!checkArray(o, new Class[]{org.bukkit.Sound.class})) {\n Logger.log(Logger.LogLevel.WARNING, \"Encountered Class Cast error initiating Trail effect (\" + particleType.toString() + \").\", true);\n return null;\n }\n e = new Sound(effectHolder, (org.bukkit.Sound) o[0]);\n } else {\n e = particleType.getEffectInstance(effectHolder);\n }\n\n return e;\n }\n\n private static boolean checkArray(Object[] o1, Class[] classes) {\n for (int i = 0; i < o1.length; i++) {\n if (!(o1[i].getClass().equals(classes[i]))) {\n return false;\n }\n }\n return true;\n }\n}",
"public class EffectManager {\n\n private static EffectManager instance;\n private HashSet<EffectHolder> effects = new HashSet<EffectHolder>();\n\n public EffectManager() {\n instance = this;\n }\n\n public static EffectManager getInstance() {\n return instance;\n }\n\n public void addHolder(EffectHolder effectHolder) {\n this.effects.add(effectHolder);\n }\n\n public void clearFromMemory(EffectHolder holder) {\n if (holder != null) {\n holder.stop();\n this.effects.remove(holder);\n }\n }\n\n public void clearEffects() {\n Iterator<EffectHolder> i = effects.iterator();\n while (i.hasNext()) {\n EffectHolder e = i.next();\n save(e);\n SQLEffectManager.instance.save(e);\n e.stop();\n i.remove();\n }\n }\n\n public HashSet<EffectHolder> getEffectHolders() {\n return this.effects;\n }\n\n public void save(EffectHolder e) {\n if (e.isPersistent()) {\n clearFromFile(e);\n if (e.getEffects().isEmpty()) {\n return;\n }\n YAMLConfig config = SparkTrailPlugin.getInstance().getConfig(SparkTrailPlugin.ConfigType.DATA);\n String path = \"effects.\";\n if (e.getEffectType() == EffectHolder.EffectType.PLAYER) {\n path = path + \"player.\" + e.getDetails().playerName + \".\";\n } else if (e.getEffectType() == EffectHolder.EffectType.LOCATION) {\n path = path + \"location.\" + DataFactory.serialiseLocation(e.getLocation()) + \".\";\n } else if (e.getEffectType() == EffectHolder.EffectType.MOB) {\n path = path + \"mob.\" + e.getDetails().mobUuid + \".\";\n }\n\n for (Effect effect : e.getEffects()) {\n if (effect == null || effect.getParticleType() == null) {\n continue;\n }\n if (effect.getParticleType().requiresDataMenu()) {\n ParticleType pt = effect.getParticleType();\n String value = null;\n if (pt == ParticleType.BLOCKBREAK) {\n value = ((BlockBreak) effect).idValue + \",\" + ((BlockBreak) effect).metaValue;\n } else if (pt == ParticleType.ITEMSPRAY) {\n value = ((ItemSpray) effect).idValue + \",\" + ((ItemSpray) effect).metaValue;\n } else if (pt == ParticleType.CRITICAL) {\n value = ((Critical) effect).criticalType.toString();\n } else if (pt == ParticleType.FIREWORK) {\n value = DataFactory.serialiseFireworkEffect(((Firework) effect).fireworkEffect, \",\");\n }\n /*else if (pt == ParticleType.NOTE) {\n value = ((Note) effect).noteType.toString();\n\t\t\t\t}*/\n else if (pt == ParticleType.POTION) {\n value = ((Potion) effect).potionType.toString();\n } else if (pt == ParticleType.SMOKE) {\n value = ((Smoke) effect).smokeType.toString();\n } else if (pt == ParticleType.SWIRL) {\n value = ((Swirl) effect).swirlType.toString();\n }\n if (value != null) {\n config.set(path + effect.getParticleType().toString().toLowerCase(), value);\n }\n } else {\n config.set(path + effect.getParticleType().toString().toLowerCase(), \"none\");\n }\n }\n\n config.saveConfig();\n }\n }\n\n public void clearFromFile(EffectHolder e) {\n if (e != null) {\n YAMLConfig config = SparkTrailPlugin.getInstance().getConfig(SparkTrailPlugin.ConfigType.DATA);\n String path = \"effects.\";\n if (e.getEffectType() == EffectHolder.EffectType.PLAYER) {\n path = path + \"player.\" + e.getDetails().playerName;\n } else if (e.getEffectType() == EffectHolder.EffectType.LOCATION) {\n path = path + \"location.\" + DataFactory.serialiseLocation(e.getLocation());\n } else if (e.getEffectType() == EffectHolder.EffectType.MOB) {\n path = path + \"mob.\" + e.getDetails().mobUuid;\n }\n config.set(path, null);\n config.saveConfig();\n }\n }\n\n public void clear(EffectHolder e) {\n clearFromFile(e);\n this.clearFromMemory(e);\n }\n\n public EffectHolder createFromFile(Location location) {\n YAMLConfig config = SparkTrailPlugin.getInstance().getConfig(SparkTrailPlugin.ConfigType.DATA);\n String path = \"effects.location.\" + DataFactory.serialiseLocation(location);\n if (config.get(path) == null) {\n return null;\n }\n EffectHolder eh = EffectCreator.createLocHolder(location);\n return createFromFile(path, eh);\n }\n\n public EffectHolder createFromFile(UUID uuid) {\n YAMLConfig config = SparkTrailPlugin.getInstance().getConfig(SparkTrailPlugin.ConfigType.DATA);\n String path = \"effects.mob.\" + uuid;\n if (config.get(path) == null) {\n return null;\n }\n EffectHolder eh = EffectCreator.createMobHolder(uuid);\n return createFromFile(path, eh);\n }\n\n public EffectHolder createFromFile(String playerName) {\n //Player p = Bukkit.getPlayerExact(playerName);\n /*if (p == null) {\n return null;\n\t\t}*/\n String path = \"effects.player.\" + playerName;\n YAMLConfig config = SparkTrailPlugin.getInstance().getConfig(SparkTrailPlugin.ConfigType.DATA);\n if (config.get(path) == null) {\n return null;\n }\n EffectHolder eh = EffectCreator.createPlayerHolder(playerName);\n return createFromFile(path, eh);\n }\n\n private EffectHolder createFromFile(String path, EffectHolder eh) {\n YAMLConfig config = SparkTrailPlugin.getInstance().getConfig(SparkTrailPlugin.ConfigType.DATA);\n if (config.get(path) == null) {\n return null;\n }\n ConfigurationSection cs = config.getConfigurationSection(path);\n for (String key : cs.getKeys(false)) {\n if (EnumUtil.isEnumType(ParticleType.class, key.toUpperCase())) {\n ParticleType pt = ParticleType.valueOf(key.toUpperCase());\n if (pt.requiresDataMenu()) {\n ParticleDetails pd = new ParticleDetails(pt);\n String value = config.getString(path + \".\" + key);\n if (pt == ParticleType.BLOCKBREAK || pt == ParticleType.ITEMSPRAY) {\n try {\n pd.blockId = Integer.parseInt(value.split(\",\")[0]);\n pd.blockMeta = Integer.parseInt(value.split(\",\")[1]);\n } catch (Exception e) {\n Logger.log(Logger.LogLevel.WARNING, \"Error creating Integer for Effect (\" + key + \"). Either SparkTrail didn't save properly or the data file was edited.\", true);\n return null;\n }\n } else if (pt == ParticleType.CRITICAL) {\n try {\n pd.criticalType = Critical.CriticalType.valueOf(value);\n } catch (Exception e) {\n Logger.log(Logger.LogLevel.WARNING, \"Error creating Effect (\" + key + \"). Either SparkTrail didn't save properly or the data file was edited.\", true);\n return null;\n }\n } else if (pt == ParticleType.FIREWORK) {\n pd.fireworkEffect = DataFactory.deserialiseFireworkEffect(value, \",\");\n }\n /*else if (pt == ParticleType.NOTE) {\n try {\n\t\t\t\t\t\t\tpd.noteType = Note.NoteType.valueOf(value);\n\t\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\t\tLogger.log(Logger.LogLevel.WARNING, \"Error creating Effect (\" + key + \"). Either SparkTrail didn't save properly or the data file was edited.\", true);\n\t\t\t\t\t\t\treturn null;\n\t\t\t\t\t\t}\n\t\t\t\t\t}*/\n else if (pt == ParticleType.POTION) {\n try {\n pd.potionType = Potion.PotionType.valueOf(value);\n } catch (Exception e) {\n Logger.log(Logger.LogLevel.WARNING, \"Error creating Effect (\" + key + \"). Either SparkTrail didn't save properly or the data file was edited.\", true);\n return null;\n }\n } else if (pt == ParticleType.SMOKE) {\n try {\n pd.smokeType = Smoke.SmokeType.valueOf(value);\n } catch (Exception e) {\n Logger.log(Logger.LogLevel.WARNING, \"Error creating Effect (\" + key + \"). Either SparkTrail didn't save properly or the data file was edited.\", true);\n return null;\n }\n } else if (pt == ParticleType.SWIRL) {\n try {\n UUID uuid = null;\n if (eh.getEffectType().equals(EffectHolder.EffectType.MOB)) {\n uuid = UUID.fromString(key);\n } else if (eh.getEffectType().equals(EffectHolder.EffectType.PLAYER)) {\n Player p = Bukkit.getPlayerExact(key);\n if (p == null) {\n continue;\n }\n uuid = p.getUniqueId();\n }\n if (eh.getEffectType().equals(EffectHolder.EffectType.LOCATION) || uuid == null) {\n continue;\n }\n pd.swirlType = Swirl.SwirlType.valueOf(value);\n pd.setMob(uuid);\n } catch (Exception e) {\n Logger.log(Logger.LogLevel.WARNING, \"Error creating Effect (\" + key + \"). Either SparkTrail didn't save properly or the data file was edited.\", true);\n return null;\n }\n }\n eh.addEffect(pd, false);\n } else {\n eh.addEffect(pt, false);\n }\n } else {\n Logger.log(Logger.LogLevel.WARNING, \"Error creating Effect (\" + key + \"). Either SparkTrail didn't save properly or the data file was edited.\", true);\n return null;\n }\n }\n return eh;\n }\n\n public EffectHolder getEffect(Location l) {\n return this.getEffect(l.getWorld(), (int) l.getX(), (int) l.getY(), (int) l.getZ());\n }\n\n public EffectHolder getEffect(World world, int x, int y, int z) {\n for (EffectHolder e : effects) {\n if (e.world.equals(world) && e.locX == x && e.locY == y && e.locZ == z) {\n return e;\n }\n }\n return null;\n }\n\n public EffectHolder getEffect(String playerName) {\n for (EffectHolder e : effects) {\n if (e.getDetails().playerName != null && e.getDetails().playerName.equals(playerName)) {\n return e;\n }\n }\n return null;\n }\n\n public EffectHolder getEffect(UUID mobUuid) {\n for (EffectHolder e : effects) {\n if (e.getDetails().mobUuid != null && e.getDetails().mobUuid == mobUuid) {\n return e;\n }\n }\n return null;\n }\n\n public void remove(EffectHolder e) {\n save(e);\n SQLEffectManager.instance.save(e);\n this.clearFromMemory(e);\n }\n}",
"public enum Lang {\n\n PREFIX(\"prefix\", \"&2ST&a » &r\"),\n\n NO_PERMISSION(\"no_permission\", \"&aYou are not permitted to do that.\"),\n COMMAND_ERROR(\"cmd_error\", \"&aError for input string: &e%cmd%&a. Use &e/\" + SparkTrailPlugin.getInstance().cmdString + \" help &afor help.\"),\n HELP_INDEX_TOO_BIG(\"help_index_too_big\", \"&aPage &e%index% &adoes not exist.\"),\n IN_GAME_ONLY(\"in_game_only\", \"&ePlease log in to do that.\"),\n STRING_ERROR(\"string_error\", \"&aError parsing String: [&e%string%&a]. Please revise command arguments.\"),\n NULL_PLAYER(\"null_player\", \"&e%player% &ais not online. Please try a different Player.\"),\n INT_ONLY(\"int_only\", \"&e%string% &aneeds to be an integer.\"),\n INT_ONLY_WITH_ARGS(\"int_only_with_args\", \"&e%string% &a[Arg &e%argNum%&a] needs to be an integer.\"),\n NO_SOUND_IN_STRING(\"no_sound_in_string\", \"&aError parsing String: [&e%string%&a]. Sound Trail could not be created.\"),\n WHUPS(\"whups\", \"&aWhups. Something bad happened. Please report this, along with information on what you did.\"),\n CONFIGS_RELOADED(\"configs_reloaded\", \"&aConfiguration files reloaded.\"),\n MENU_DISABLED(\"menu_disabled\", \"&aTrail menu has been globally disabled.\"),\n\n PLAYER_LIST_NO_ACTIVE_EFFECTS(\"player_list_no_active_effects\", \"&aThere are no Player Trail effects active.\"),\n PLAYER_NO_ACTIVE_EFFECTS(\"player_no_active_effects\", \"&aThere are no Player Trail effects active for &e%player%&a.\"),\n PLAYER_NO_EFFECTS_TO_LOAD(\"player_no_effects_to_load\", \"&aThere are no Trail effects to load for &e%player%&a.\"),\n PLAYER_EFFECTS_LOADED(\"player_effects_loaded\", \"&aTrail effects have been loaded for &e%player%&a.\"),\n PLAYER_EFFECTS_STOPPED(\"player_effects_stopped\", \"&aTrail effects stopped for &e%player%&a.\"),\n PLAYER_EFFECTS_CLEARED(\"player_effects_cleared\", \"&aTrail effects cleared for &e%player%&a.\"),\n\n NO_ACTIVE_EFFECTS(\"no_active_effects\", \"&aYou do not have any Trail effects active.\"),\n TIMEOUT_SET(\"timeout_set\", \"&aTimeout has been set to &e%timeout%&a.\"),\n MAX_EFFECTS_ALLOWED(\"max_effects_allowed\", \"&aMaximum number of effects reached.\"),\n EFFECT_CREATION_FAILED(\"effect_creation_failed\", \"&aEffect creation has failed. SparkTrail may have encountered a severe error.\"),\n CANCEL_EFFECT_CREATION(\"cancel_effect_creation\", \"&aEffect creation cancelled.\"),\n EFFECT_ADDED(\"effect_added\", \"&e%effect% &aeffect added.\"),\n EFFECT_REMOVED(\"effect_removed\", \"&e%effect% &aeffect removed.\"),\n EFFECTS_LOADED(\"effects_loaded\", \"&aYour Trail effects have been loaded.\"),\n EFFECTS_CLEARED(\"effects_cleared\", \"&aYour Trail effects have been cleared.\"),\n NO_EFFECTS_TO_LOAD(\"no_effects_to_load\", \"&aYou have no Trail effects to load.\"),\n EFFECTS_STOPPED(\"effects_stopped\", \"&aYour Trail effects have been stopped.\"),\n RANDOM_SELECT_FAILED(\"random_select_failed\", \"&aRandom Trail selection has failed.\"),\n SWIRL_NOT_ALLOWED(\"swirl_not_allowed\", \"&eSwirl &aTrail effect cannot be added to blocks.\"),\n\n LOC_NO_EFFECTS_RETRY_BLOCK_INTERACT(\"loc_no_effects_retry_block_interact\", \"&aLocation Trail effects do no exist for that block. Would you like to retry? [&eYES &aor &eNO&a]\"),\n LOC_EFFECTS_STARTED(\"loc_effects_started\", \"&aLocation Trail effect started.\"),\n LOC_EFFECTS_STOPPED(\"loc_effects_stopped\", \"&aLocation Trail effect stopped.\"),\n LOC_EFFECTS_CLEARED(\"loc_effects_cleared\", \"&aLocation Trail effect cleared.\"),\n LOC_EFFECTS_LOADED(\"loc_effects_loaded\", \"&Location Trail effects loaded.\"),\n LOC_NO_EFFECTS_TO_LOAD(\"loc_no_effects_to_load\", \"&aThere are no Trail effects to load for that location.\"),\n LOC_LIST_NO_ACTIVE_EFFECTS(\"loc_list_no_active_effects\", \"&aThere are no Location Trail effects active.\"),\n LOC_NO_ACTIVE_EFFECTS(\"loc_no_active_effects\", \"&aThere are no Trail effects active at that location.\"),\n LOC_NO_ACTIVE_EFFECTS_RETRY_BLOCK_INTERACT(\"loc_no_active_effects_retry_block_interact\", \"&aThere are no Location Trail effects active. Would you like to retry? [&eYES &aor &eNO&a]\"),\n LOC_STOP_ALL(\"loc_stop_all\", \"&aAll Location Trail effects have been stopped.\"),\n\n MOB_NO_EFFECTS_RETRY_INTERACT(\"mob_no_effects_retry_interact\", \"&aMob Trail effects do no exist for that block. Would you like to retry? [&eYES &aor &eNO&a]\"),\n MOB_EFFECTS_STOPPED(\"mob_effects_stopped\", \"&aMob Trail effect stopped.\"),\n MOB_EFFECTS_STARTED(\"mob_effects_started\", \"&aMob Trail effect started.\"),\n MOB_EFFECTS_CLEARED(\"mob_effects_cleared\", \"&aMob Trail effect cleared.\"),\n MOB_NO_EFFECTS_TO_LOAD(\"mob_no_effects_to_load\", \"&aThere are no Trail effects to load for that Mob.\"),\n MOB_LIST_NO_ACTIVE_EFFECTS(\"mob_list_no_active_effects\", \"&aThere are no Mob Trail effects active.\"),\n MOB_NO_ACTIVE_EFFECTS_RETRY_INTERACT(\"mob_no_active_effects_retry_interact\", \"&aThere are no Mob Trail effects active. Would you like to retry? [&eYES &aor &eNO&a]\"),\n\n INVALID_EFFECT_ARGS(\"invalid_effect_args\", \"&aInvalid &e%effect% &aeffect arguments entered. %extra_info%\"),\n CRITICAL_HELP(\"critical_help\", \"&eCritical &aeffects: &eNormal&a, &eMagic&a.\"),\n POTION_HELP(\"potion_help\", \"&ePotion &aeffects: &eAqua&a, &eBlack&a, &eBlue&a, &eCrimson&a, &eDarkBlue&a, &eDarkGreen&a, &eDarkRed&a, &eGold&a, &eGray&a, &eGreen&a, &ePink&a, &eRed&a.\"),\n SMOKE_HELP(\"smoke_help\", \"&eSmoke &aeffects: &eRed&a, &eBlack&a, &eRainbow&a.\"),\n SWIRL_HELP(\"swirl_help\", \"&eSwirl &aeffects: &eLightBlue&a, &eBlue&a, &eDarkBlue&a, &eRed&a, &eDarkRed&a, &eGreen&a, &eDarkGreen&a, &eYellow&a, &eOrange&a, &eGray&a, &eBlack&a, &eWhite&a, &ePurple&a, &ePink&a.\"),\n\n INPUT_FIRST_IDVALUE(\"input_first_idvalue\", \"&aWhat ID value would you like this effect to have?\"),\n INPUT_SECOND_METAVALUE(\"input_second_idvalue\", \"&aWhat Block Meta value would you like this effect to have?\"),\n INVALID_INPUT(\"invalid_input\", \"&aInvalid. Retry or enter &eexit &ato cancel.\"),\n INPUT_FIREWORK(\"input_firework\", \"&aWhat firework effects would you like this effect to have? Separate each parameter with a space.\"),\n INPUT_TIMEOUT(\"input_timeout\", \"&aHow long until this set of effects times out?\"),\n\n MENU_ERROR(\"menu_error\", \"&aThere has been a problem with the Trail GUI Menu. Please see the console for details.\"),\n OPEN_MENU(\"open_menu\", \"&aOpening Trail Effect GUI\"),\n ENTER_BLOCK_OR_ITEM(\"enter_block_break\", \"&aPlease enter effect parameters [&e%effect%&a]. Structure: &e<IdValue> <Meta>\"),\n ENTER_FIREWORK(\"enter_firework\", \"&aPlease enter effect parameters [&eFirework&a]. Separate each parameter with a space.\"),\n ENTER_TIMEOUT(\"enter_timeout\", \"&aPlease enter an integer.\"),\n INCORRECT_EFFECT_ARGS(\"incorrect_blockbreak_args\", \"&aCould not create &e%effect% &aeffect from String [&e%string%&a]. Would you like to retry? [&eYES &aor &eNO&a]\"),\n YES_OR_NO(\"yes_or_no\", \"&aPlease enter &eYES &aor &eNO&a.\"),\n INTERACT_BLOCK(\"interact_block\", \"&aPlease interact with a target block to modify its Trail effects.\"),\n INTERACT_MOB(\"interact_mob\", \"&aPlease interact with a target entity to modify its Trail effects.\"),\n RETRY_BLOCK_INTERACT(\"retry_block_interact\", \"&aUse the Trail command to create Air Trail effects. Would you like to retry creating a block effect? &e[YES or NO]\"),\n RETRY_MOB_INTERACT(\"retry_mob_interact\", \"&aInteract with an Entity (other than a Player) to modify its Trail effects. Would you like to retry? [&eYES &aor &eNO&a]\"),\n EXECUTE_LOC_LIST(\"execute_loc_list\", \"&aExecute &e/\" + SparkTrailPlugin.getInstance().cmdString + \" list &ato view the list of Location Trail effects. Use the IDs to run &e/\" + SparkTrailPlugin.getInstance().cmdString + \" stop <id>&a.\"),\n\n DEMO_BEGIN(\"demo_begin\", \"&aStarting Trail Demo. You may enter the following commands during the presentation: &eNAME&a, &eSTOP&a.\"),\n DEMO_STOP(\"demo_stop\", \"&aTrail Demo has been stopped.\"),\n DEMO_CURRENT_PARTICLE(\"demo_current_particle\", \"&aCurrent Trail effect: &e%effect%&a.\"),\n\n ADMIN_OPEN_MENU(\"open_player_menu\", \"&aOpening Trail Effect GUI for &e%player%&a.\"),;\n\n private String path;\n private String def;\n private String[] desc;\n\n Lang(String path, String def, String... desc) {\n this.path = path;\n this.def = def;\n this.desc = desc;\n }\n\n public String[] getDescription() {\n return this.desc;\n }\n\n public String getPath() {\n return this.path;\n }\n\n public static void sendTo(CommandSender sender, String msg) {\n if (msg != null || !msg.equalsIgnoreCase(\"\") && !msg.equalsIgnoreCase(\" \") && !msg.equalsIgnoreCase(\"none\")) {\n sender.sendMessage(SparkTrailPlugin.getInstance().prefix + msg);\n }\n }\n\n public static void sendTo(Player p, String msg) {\n if (msg != null && !msg.equalsIgnoreCase(\"\") && !msg.equalsIgnoreCase(\" \") && !(msg.equalsIgnoreCase(\"none\"))) {\n p.sendMessage(SparkTrailPlugin.getInstance().prefix + msg);\n }\n }\n\n @Override\n public String toString() {\n String result = SparkTrailPlugin.getInstance().getConfig(SparkTrailPlugin.ConfigType.LANG).getString(this.path, this.def);\n if (result != null && result != \"\" && result != \"none\") {\n return ChatColor.translateAlternateColorCodes('&', SparkTrailPlugin.getInstance().getConfig(SparkTrailPlugin.ConfigType.LANG).getString(this.path, this.def));\n } else {\n return \"\";\n }\n }\n\n public String getRaw() {\n return SparkTrailPlugin.getInstance().getConfig(SparkTrailPlugin.ConfigType.LANG).getString(this.path, this.def);\n }\n}"
] | import java.util.HashSet;
import java.util.Iterator;
import com.dsh105.sparktrail.SparkTrailPlugin;
import com.dsh105.sparktrail.config.ConfigOptions;
import com.dsh105.sparktrail.data.EffectCreator;
import com.dsh105.sparktrail.data.EffectManager;
import com.dsh105.sparktrail.trail.type.*;
import com.dsh105.sparktrail.util.Lang;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask; | /*
* This file is part of SparkTrail 3.
*
* SparkTrail 3 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.
*
* SparkTrail 3 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 SparkTrail 3. If not, see <http://www.gnu.org/licenses/>.
*/
package com.dsh105.sparktrail.trail;
public class EffectHolder extends BukkitRunnable {
private HashSet<Effect> effects = new HashSet<Effect>();
private BukkitTask task = null;
protected EffectType effectType;
protected EffectDetails details;
private boolean persistent = true;
public World world;
public int locX;
public int locY;
public int locZ;
private int tick = 0;
private int timeout = 0;
private int timeoutTicks = 0;
public EffectHolder(EffectType effectType) {
this.effectType = effectType;
this.details = new EffectDetails(effectType);
if (this.effectType == EffectType.MOB) {
this.persistent = false;
}
}
public boolean isPersistent() {
return this.persistent;
}
public HashSet<Effect> getEffects() {
return this.effects;
}
public EffectType getEffectType() {
return this.effectType;
}
public boolean addEffect(ParticleType particleType, boolean sendFailMessage) {
if (this.canAddEffect()) {
if (this.effectType == EffectType.PLAYER) {
ParticleDetails pd = new ParticleDetails(particleType);
pd.setPlayer(this.details.playerName, this.details.mobUuid);
Effect effect = EffectCreator.createEffect(this, particleType, pd.getDetails());
if (effect != null) {
this.effects.add(effect);
}
} else if (this.effectType == EffectType.LOCATION) {
ParticleDetails pd = new ParticleDetails(particleType);
Effect effect = EffectCreator.createEffect(this, particleType, pd.getDetails());
if (effect != null) {
this.effects.add(effect);
}
} else if (this.effectType == EffectType.MOB) {
ParticleDetails pd = new ParticleDetails(particleType);
pd.setMob(this.details.mobUuid);
Effect effect = EffectCreator.createEffect(this, particleType, pd.getDetails());
if (effect != null) {
this.effects.add(effect);
}
}
EffectManager.getInstance().save(this);
return true;
} else if (sendFailMessage) {
if (this.getEffectType().equals(EffectType.PLAYER)) { | Player p = SparkTrailPlugin.getInstance().getServer().getPlayerExact(this.getDetails().playerName); | 0 |
nongdenchet/android-data-binding | app/src/main/java/apidez/com/databinding/view/activity/PurchaseActivity.java | [
"public class MyApplication extends Application {\n private static Context mContext;\n protected AppComponent mAppComponent;\n protected ComponentBuilder mComponentBuilder;\n\n @Override\n public void onCreate() {\n super.onCreate();\n mContext = this;\n\n // Create app component\n mAppComponent = DaggerAppComponent.builder()\n .appModule(new AppModule())\n .build();\n\n // Create component builder\n mComponentBuilder = new ComponentBuilder(mAppComponent);\n }\n\n public AppComponent component() {\n return mAppComponent;\n }\n\n public ComponentBuilder builder() {\n return mComponentBuilder;\n }\n\n public static Context context() {\n return mContext;\n }\n}",
"public class TextWatcherAdapter implements TextWatcher {\n @Override\n public void beforeTextChanged(CharSequence s, int start, int count, int after) {\n\n }\n\n @Override\n public void onTextChanged(CharSequence s, int start, int before, int count) {\n\n }\n\n @Override\n public void afterTextChanged(Editable s) {\n\n }\n}",
"public class UiUtils {\n public static void showDialog(String text, Context context) {\n new AlertDialog.Builder(context)\n .setMessage(text)\n .setPositiveButton(android.R.string.yes, (dialog, which) -> {\n })\n .show();\n }\n\n public static void closeKeyboard(Activity context) {\n // Check if no view has focus:\n View view = context.getCurrentFocus();\n if (view != null) {\n InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);\n imm.hideSoftInputFromWindow(view.getWindowToken(), 0);\n }\n }\n}",
"public interface IPurchaseHandler {\n TextWatcher emailWatcher();\n TextWatcher creditCardWatcher();\n View.OnClickListener onSubmit();\n View.OnClickListener onInvalid();\n}",
"public interface IPurchaseViewModel {\n /**\n * Observable validation of card\n */\n ObservableInt creditCardError();\n\n /**\n * Observable validation of email\n */\n ObservableInt emailError();\n\n /**\n * Observable validation of submit\n */\n ObservableBoolean canSubmit();\n\n /**\n * set new credit card\n */\n void setCreditCard(String newCreditCard);\n\n /**\n * Set new email\n */\n void setEmail(String newEmail);\n\n /**\n * Command submit\n */\n rx.Observable<Boolean> submit();\n}"
] | import android.app.ProgressDialog;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import javax.inject.Inject;
import apidez.com.databinding.MyApplication;
import apidez.com.databinding.R;
import apidez.com.databinding.databinding.ActivityPurchaseBinding;
import apidez.com.databinding.utils.TextWatcherAdapter;
import apidez.com.databinding.utils.UiUtils;
import apidez.com.databinding.view.handler.IPurchaseHandler;
import apidez.com.databinding.viewmodel.IPurchaseViewModel;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers; | package apidez.com.databinding.view.activity;
/**
* Created by nongdenchet on 10/28/15.
*/
public class PurchaseActivity extends BaseActivity implements IPurchaseHandler {
private ProgressDialog mProgressDialog;
private ActivityPurchaseBinding binding;
@Inject
IPurchaseViewModel mViewModel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_purchase);
// Setup DI | ((MyApplication) getApplication()) | 0 |
mstojcevich/Radix | core/src/sx/lambda/voxel/net/mc/client/handlers/ChunkDataHandler.java | [
"public class RadixClient extends ApplicationAdapter {\n\n // TODO CLEANUP the render loop is VERY undocumented and things happen all over the place, clean that up\n\n public static final String GAME_TITLE = \"VoxelTest\";\n private static RadixClient theGame;\n\n private SettingsManager settingsManager;\n\n private boolean done; // Whether the game has finished and should shut down\n\n private boolean remote; // Whether the player is connected to a remote server\n private IWorld world;\n private Player player;\n private Vec3i selectedBlock; // selected block to break next\n private Vec3i selectedNextPlace; // selected block to place at next\n\n private MinecraftClientConnection mcClientConn;\n\n private final Queue<Runnable> glQueue = new ConcurrentLinkedDeque<>();\n\n private GuiScreen currentScreen;\n private TransitionAnimation transitionAnimation;\n private Renderer renderer;\n private GameRenderer gameRenderer; // renderer for when in game\n private MainMenu mainMenu;\n private IngameHUD hud;\n private ChatGUI chatGUI;\n\n private Texture blockTextureAtlas;\n private PerspectiveCamera camera;\n private OrthographicCamera hudCamera;\n private SpriteBatch guiBatch;\n\n private final MovementHandler movementHandler = new MovementHandler(this);\n private final RepeatedTask[] handlers = new RepeatedTask[]{new WorldLoader(this), movementHandler, new EntityUpdater(this)};\n\n // Android specific stuff\n private boolean android;\n private Stage androidStage;\n private Skin androidOverlaySkin;\n private TouchpadStyle touchpadStyle;\n private TextureAtlas touchControlsAtlas;\n private Touchpad moveTouchpad, rotateTouchpad;\n private ImageButton jumpButton, placeButton, breakButton;\n\n private boolean wireframe, debugText;\n\n private SceneTheme sceneTheme;\n\n public static RadixClient getInstance() {\n return theGame;\n }\n\n @Override\n public void create() {\n //GLProfiler.enable();\n\n EntityModel.init();\n theGame = this;\n settingsManager = new SettingsManager();\n\n this.android = Gdx.app.getType().equals(Application.ApplicationType.Android);\n\n try {\n RadixAPI.instance.getEventManager().register(this);\n } catch (InvalidListenerException e) {\n e.printStackTrace();\n }\n\n try {\n RadixAPI.instance.registerBuiltinBlockRenderers();\n RadixAPI.instance.getEventManager().push(new EventRegisterBlockRenderers());\n } catch (RadixAPI.DuplicateRendererException ex) {\n ex.printStackTrace();\n }\n\n try {\n RadixAPI.instance.registerBuiltinItems();\n if(!settingsManager.getVisualSettings().getFancyTrees().getValue()) {\n RadixAPI.instance.getBlock(BuiltInBlockIds.LEAVES_ID).setOccludeCovered(true);\n RadixAPI.instance.getBlock(BuiltInBlockIds.LEAVES_TWO_ID).setOccludeCovered(true);\n }\n\n RadixAPI.instance.getEventManager().push(new EventRegisterItems());\n } catch (RadixAPI.BlockRegistrationException e) {\n e.printStackTrace();\n }\n\n RadixAPI.instance.registerMinecraftBiomes();\n RadixAPI.instance.getEventManager().push(new EventRegisterBiomes());\n\n RadixAPI.instance.getEventManager().push(new EventEarlyInit());\n\n this.setupOGL();\n\n gameRenderer = new GameRenderer(this);\n hud = new IngameHUD();\n chatGUI = new ChatGUI();\n chatGUI.init();\n mainMenu = new MainMenu();\n setCurrentScreen(mainMenu);\n\n this.startHandlers();\n }\n\n private void setupTouchControls() {\n // Create touch control element atlas\n touchControlsAtlas = new TextureAtlas(Gdx.files.internal(\"textures/gui/touch/touch.atlas\"));\n // Create skin\n androidOverlaySkin = new Skin();\n for(TextureAtlas.AtlasRegion r : touchControlsAtlas.getRegions()) {\n androidOverlaySkin.add(r.name, r, TextureRegion.class);\n }\n\n // Create touchpad skin/style\n touchpadStyle = new TouchpadStyle();\n touchpadStyle.background = androidOverlaySkin.getDrawable(\"touchpadBackground\");\n touchpadStyle.knob = androidOverlaySkin.getDrawable(\"touchpadKnob\");\n\n moveTouchpad = new Touchpad(10, touchpadStyle);\n moveTouchpad.setBounds(15, 15, 200, 200);\n\n rotateTouchpad = new Touchpad(10, touchpadStyle);\n rotateTouchpad.setBounds(1280 - 200 - 15, 15, 200, 200);\n\n jumpButton = new ImageButton(androidOverlaySkin.getDrawable(\"jumpButtonIcon\"));\n jumpButton.addListener(new ClickListener() {\n @Override\n public void clicked(InputEvent event, float x, float y) {\n movementHandler.jump();\n }\n });\n placeButton = new ImageButton(androidOverlaySkin.getDrawable(\"placeButtonIcon\"));\n placeButton.addListener(new ClickListener() {\n @Override\n public void clicked(InputEvent event, float x, float y) {\n placeBlock();\n }\n });\n breakButton = new ImageButton(androidOverlaySkin.getDrawable(\"breakButtonIcon\"));\n breakButton.addListener(new ClickListener() {\n @Override\n public void clicked(InputEvent event, float x, float y) {\n breakBlock();\n }\n });\n ImageButton[] buttons = new ImageButton[]{\n jumpButton, placeButton, breakButton\n };\n int totalButtonWidth = 0;\n for(ImageButton button : buttons) {\n totalButtonWidth += button.getImage().getPrefWidth();\n }\n int btnX = 1280/2-totalButtonWidth/2;\n for(ImageButton button : buttons) {\n button.setBounds(btnX, 0, button.getImage().getPrefWidth(), button.getImage().getPrefHeight());\n btnX += button.getImage().getPrefWidth();\n }\n\n // Setup android stage\n androidStage = new Stage(new FitViewport(1280, 720));\n androidStage.addActor(moveTouchpad);\n androidStage.addActor(rotateTouchpad);\n for(ImageButton button : buttons) {\n androidStage.addActor(button);\n }\n }\n\n private void startHandlers() {\n for (RepeatedTask r : handlers) {\n new Thread(r, r.getIdentifier()).start();\n }\n }\n\n private void setupOGL() {\n camera = new PerspectiveCamera(90, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());\n camera.position.set(10f, 150f, 10f);\n camera.lookAt(0, 0, 0);\n camera.near = 0.1f;\n camera.far = 450f;\n camera.update();\n hudCamera = new OrthographicCamera(Gdx.graphics.getWidth(), Gdx.graphics.getHeight());\n\n guiBatch = new SpriteBatch();\n guiBatch.setProjectionMatrix(hudCamera.combined);\n\n if(android) {\n setupTouchControls();\n }\n\n Gdx.input.setInputProcessor(new RadixInputHandler(this));\n\n if(settingsManager.getVisualSettings().getNonContinuous().getValue()) {\n Gdx.graphics.setContinuousRendering(false);\n }\n\n sceneTheme = new SceneTheme();\n sceneTheme.init();\n }\n\n @Override\n public void dispose() {\n super.dispose();\n done = true;\n if (isRemote()) {\n if(mcClientConn != null)\n mcClientConn.getClient().getSession().disconnect(\"Closing game\");\n }\n\n if(android) {\n androidStage.dispose();\n androidOverlaySkin.dispose();\n touchControlsAtlas.dispose();\n }\n }\n\n @Override\n public void render() {\n try {\n if (done)\n Gdx.app.exit();\n\n prepareNewFrame();\n\n runQueuedOGL();\n\n if (renderer != null) {\n renderer.render();\n }\n\n guiBatch.begin();\n if (renderer != null) {\n renderer.draw2d(guiBatch);\n }\n\n if (currentScreen != null) {\n currentScreen.render(world != null, guiBatch);\n }\n\n if(transitionAnimation != null) {\n transitionAnimation.render(guiBatch);\n if(transitionAnimation.isFinished()) {\n transitionAnimation.finish();\n transitionAnimation = null;\n }\n }\n\n guiBatch.end();\n\n if(world != null && android) {\n updatePositionRotationAndroid();\n androidStage.act();\n androidStage.draw();\n }\n\n if(settingsManager.getVisualSettings().getFinishEachFrame().getValue())\n Gdx.gl.glFinish();\n } catch (Exception e) {\n done = true;\n e.printStackTrace();\n Gdx.input.setCursorCatched(false);\n Gdx.app.exit();\n }\n\n }\n\n private void runQueuedOGL() {\n Runnable currentRunnable;\n while ((currentRunnable = glQueue.poll()) != null) {\n currentRunnable.run();\n }\n\n }\n\n private void prepareNewFrame() {\n int clear = GL_DEPTH_BUFFER_BIT;\n if(world == null || getCurrentScreen() != hud || (transitionAnimation != null && !transitionAnimation.isFinished())) {\n /*\n Clear color buffer too when not in a world\n When in a world, since there is a skybox, clearing the color buffer would be pointless.\n */\n clear |= GL_COLOR_BUFFER_BIT;\n Gdx.gl.glClearColor(0.7f, 0.8f, 1f, 1f);\n }\n Gdx.gl.glClear(clear);\n }\n\n public void updateSelectedBlock() {\n PlotCell3f plotter = new PlotCell3f(0, 0, 0, 1, 1, 1);\n float x = player.getPosition().getX();\n float y = player.getPosition().getY() + player.getEyeHeight();\n float z = player.getPosition().getZ();\n float pitch = player.getRotation().getPitch();\n float yaw = player.getRotation().getYaw();\n float reach = player.getReach();\n\n float deltaX = (float) (Math.cos(Math.toRadians(pitch)) * Math.sin(Math.toRadians(yaw)));\n float deltaY = (float) (Math.sin(Math.toRadians(pitch)));\n float deltaZ = (float) (-Math.cos(Math.toRadians(pitch)) * Math.cos(Math.toRadians(yaw)));\n\n final Vec3i oldPos = selectedBlock;\n\n plotter.plot(new Vector3(x, y, z), new Vector3(deltaX, deltaY, deltaZ), MathUtils.ceil(reach * reach));\n Vec3i last = null;\n while (plotter.next()) {\n Vec3i v = plotter.get();\n Vec3i bp = new Vec3i(v.x, v.y, v.z);\n IChunk theChunk = world.getChunk(bp);\n if (theChunk != null) {\n if(bp.y >= world.getHeight())\n continue;\n try {\n Block b = theChunk.getBlock(bp.x & (world.getChunkSize() - 1), bp.y, bp.z & (world.getChunkSize() - 1));\n if (b != null && b.isSelectable()) {\n selectedBlock = bp;\n if (last != null) {\n Block lastBlock = theChunk.getBlock(last.x & (world.getChunkSize() - 1),\n last.y, last.z & (world.getChunkSize() - 1));\n if (lastBlock == null || !lastBlock.isSelectable()) {\n selectedNextPlace = last;\n }\n }\n\n plotter.end();\n if(!selectedBlock.equals(oldPos)) {\n player.resetBlockBreak();\n }\n return;\n }\n } catch(CoordinatesOutOfBoundsException ex) {\n ex.printStackTrace();\n plotter.end();\n player.resetBlockBreak();\n return;\n }\n\n last = bp;\n }\n\n }\n\n selectedNextPlace = null;\n selectedBlock = null;\n if(player != null) {\n player.resetBlockBreak();\n }\n }\n\n public void addToGLQueue(Runnable runnable) {\n glQueue.add(runnable);\n }\n\n public IWorld getWorld() {\n return world;\n }\n\n public Player getPlayer() {\n return player;\n }\n\n public boolean isDone() {\n return done;\n }\n\n public SettingsManager getSettingsManager() {\n return settingsManager;\n }\n\n public Vec3i getSelectedBlock() {\n return selectedBlock;\n }\n\n public Vec3i getNextPlacePos() {\n return selectedNextPlace;\n }\n\n public void startShutdown() {\n done = true;\n }\n\n private void setRenderer(Renderer renderer) {\n if (renderer == null) {\n if (this.renderer != null) {\n this.renderer.cleanup();\n this.renderer = null;\n }\n } else if (this.renderer == null) {\n this.renderer = renderer;\n this.renderer.init();\n } else {\n this.renderer.cleanup();\n this.renderer = renderer;\n this.renderer.init();\n }\n }\n\n public boolean isRemote() {\n return remote;\n }\n\n public MinecraftClientConnection getMinecraftConn() {\n return mcClientConn;\n }\n\n public void handleCriticalException(Exception ex) {\n ex.printStackTrace();\n this.done = true;\n Gdx.input.setCursorCatched(false);\n if(!android) {\n JOptionPane.showMessageDialog(null, GAME_TITLE + \" crashed. \" + String.valueOf(ex), GAME_TITLE + \" crashed\", JOptionPane.ERROR_MESSAGE);\n }\n }\n\n public GuiScreen getCurrentScreen() {\n return currentScreen;\n }\n\n public void setCurrentScreen(GuiScreen screen) {\n if (currentScreen == null) {\n currentScreen = screen;\n screen.init();\n } else if (!currentScreen.equals(screen)) {\n currentScreen.finish();\n currentScreen = screen;\n screen.init();\n }\n\n if (screen.equals(hud) && !android) {\n Gdx.input.setCursorCatched(true);\n } else {\n Gdx.input.setCursorCatched(false);\n }\n }\n\n public void enterRemoteWorld(final String hostname, final short port) {\n selectedBlock = null;\n selectedNextPlace = null;\n\n enterWorld(new World(true, false), true);\n (mcClientConn = new MinecraftClientConnection(RadixClient.this, hostname, port)).start();\n chatGUI.setup(mcClientConn);\n }\n\n public void enterLocalWorld(IWorld world) {\n enterWorld(world, false);\n }\n\n public void exitWorld() {\n addToGLQueue(() -> {\n setCurrentScreen(mainMenu);\n setRenderer(null);\n getWorld().cleanup();\n if (isRemote()) {\n mcClientConn.getClient().getSession().disconnect(\"Exiting world\");\n }\n\n world = null;\n remote = false;\n player = null;\n });\n\n if(android) {\n Gdx.input.setInputProcessor(new RadixInputHandler(this));\n }\n }\n\n private void enterWorld(final IWorld world, final boolean remote) {\n this.world = world;\n this.remote = remote;\n player = new Player(new EntityPosition(0, 256, 0), new EntityRotation(0, 0));\n addToGLQueue(() -> {\n setRenderer(getGameRenderer());\n getPlayer().init();\n// world.addEntity(getPlayer());\n transitionAnimation = new SlideUpAnimation(getCurrentScreen(), 1000);\n transitionAnimation.init();\n setCurrentScreen(getHud());\n\n if (!remote) {\n world.loadChunks(new EntityPosition(0, 0, 0), getSettingsManager().getVisualSettings().getViewDistance());\n }\n\n RadixAPI.instance.getEventManager().push(new EventWorldStart());\n // Delays are somewhere in this function. Above here.\n });\n\n if(android) {\n Gdx.input.setInputProcessor(androidStage);\n }\n }\n\n public Texture getBlockTextureAtlas() throws NotInitializedException {\n if (blockTextureAtlas == null) throw new NotInitializedException();\n return blockTextureAtlas;\n }\n\n @EventListener(Priority.FIRST)\n public void createBlockTextureMap(EventEarlyInit event) {\n // Create a texture atlas for all of the blocks\n addToGLQueue(() -> {\n Pixmap bi = new Pixmap(2048, 2048, Pixmap.Format.RGBA8888);\n bi.setColor(1, 1, 1, 1);\n final int BLOCK_TEX_SIZE = 32;\n int textureIndex = 0;\n for (Block b : RadixAPI.instance.getBlocks()) {\n if (b == null)\n continue;\n b.setTextureIndex(textureIndex);\n for (String texLoc : b.getTextureLocations()) {\n int x = textureIndex * BLOCK_TEX_SIZE % bi.getWidth();\n int y = BLOCK_TEX_SIZE * ((textureIndex * BLOCK_TEX_SIZE) / bi.getWidth());\n Pixmap tex = new Pixmap(Gdx.files.internal(texLoc));\n bi.drawPixmap(tex, x, y);\n tex.dispose();\n textureIndex++;\n }\n }\n\n blockTextureAtlas = new Texture(bi);\n bi.dispose();\n });\n }\n\n @Override\n public void resize(int width, int height) {\n Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());\n\n hudCamera.setToOrtho(false, width, height);\n hudCamera.update();\n guiBatch.setProjectionMatrix(hudCamera.combined);\n\n camera.viewportWidth = width;\n camera.viewportHeight = height;\n camera.update();\n\n if(android)\n androidStage.getViewport().update(width, height, true);\n }\n\n public void beginBreak() {\n if (this.getSelectedBlock() != null\n && this.currentScreen == this.hud) {\n IChunk chunk = world.getChunk(selectedBlock);\n if(chunk != null) {\n try {\n Block block = chunk.getBlock(selectedBlock.x & (world.getChunkSize() - 1), selectedBlock.y,\n selectedBlock.z & (world.getChunkSize() - 1));\n if (block != null && block.isSelectable()) {\n if (this.isRemote()) {\n mcClientConn.getClient().getSession().send(new ClientPlayerSwingArmPacket(Hand.MAIN_HAND));\n mcClientConn.getClient().getSession().send(\n new ClientPlayerActionPacket(PlayerAction.START_DIGGING,\n new Position(selectedBlock.x, selectedBlock.y, selectedBlock.z), BlockFace.UP));\n }\n }\n } catch (CoordinatesOutOfBoundsException ex) {\n ex.printStackTrace();\n }\n }\n }\n }\n\n public void cancelBreak() {\n if (this.getSelectedBlock() != null\n && this.currentScreen == this.hud) {\n IChunk chunk = world.getChunk(selectedBlock);\n if(chunk != null) {\n try {\n Block block = chunk.getBlock(selectedBlock.x & (world.getChunkSize() - 1), selectedBlock.y,\n selectedBlock.z & (world.getChunkSize() - 1));\n if (block != null && block.isSelectable()) {\n if (this.isRemote()) {\n mcClientConn.getClient().getSession().send(\n new ClientPlayerActionPacket(PlayerAction.CANCEL_DIGGING,\n new Position(selectedBlock.x, selectedBlock.y, selectedBlock.z), BlockFace.UP));\n }\n }\n player.resetBlockBreak();\n } catch (CoordinatesOutOfBoundsException ex) {\n ex.printStackTrace();\n }\n }\n }\n }\n\n public void breakBlock() {\n if (this.getSelectedBlock() != null\n && this.currentScreen == this.hud) {\n IChunk chunk = world.getChunk(selectedBlock);\n if(chunk != null) {\n try {\n Block block = chunk.getBlock(selectedBlock.x & (world.getChunkSize() - 1), selectedBlock.y,\n selectedBlock.z & (world.getChunkSize() - 1));\n if (block != null && block.isSelectable()) {\n if (this.isRemote()) {\n mcClientConn.getClient().getSession().send(new ClientPlayerSwingArmPacket(Hand.MAIN_HAND));\n mcClientConn.getClient().getSession().send(\n new ClientPlayerActionPacket(PlayerAction.FINISH_DIGGING,\n new Position(selectedBlock.x, selectedBlock.y, selectedBlock.z), BlockFace.UP));\n } else {\n this.getWorld().removeBlock(this.getSelectedBlock().x,\n this.getSelectedBlock().y, this.getSelectedBlock().z);\n }\n updateSelectedBlock();\n }\n } catch (CoordinatesOutOfBoundsException ex) {\n ex.printStackTrace();\n }\n }\n }\n }\n\n public void placeBlock() {\n if (this.getNextPlacePos() != null && this.currentScreen == this.hud) {\n if (this.isRemote() && this.mcClientConn != null) {\n this.mcClientConn.getClient().getSession().send(new ClientPlayerPlaceBlockPacket(\n new Position(this.getNextPlacePos().x, this.getNextPlacePos().y, this.getNextPlacePos().z),\n BlockFace.UP /* TODO MCPROTO send correct face */, Hand.MAIN_HAND, 0, 0, 0));\n } else {\n this.getWorld().addBlock(this.getPlayer().getItemInHand(), this.getNextPlacePos().x,\n this.getNextPlacePos().y, this.getNextPlacePos().z);\n }\n updateSelectedBlock();\n }\n }\n\n private void updatePositionRotationAndroid() {\n if(!MathUtils.isZero(rotateTouchpad.getKnobPercentX()) || !MathUtils.isZero(rotateTouchpad.getKnobPercentY())) {\n float rotMult = 200 * Gdx.graphics.getDeltaTime();\n\n player.getRotation().offset(rotateTouchpad.getKnobPercentY() * rotMult, rotateTouchpad.getKnobPercentX() * rotMult);\n updateSelectedBlock();\n gameRenderer.calculateFrustum();\n }\n\n if(!MathUtils.isZero(moveTouchpad.getKnobPercentX()) || !MathUtils.isZero(moveTouchpad.getKnobPercentY())) {\n float posMult = 4.5f * Gdx.graphics.getDeltaTime();\n\n float deltaX = 0;\n float deltaZ = 0;\n float yawSine = MathUtils.sinDeg(player.getRotation().getYaw());\n float yawCosine = MathUtils.cosDeg(player.getRotation().getYaw());\n deltaX += yawSine * moveTouchpad.getKnobPercentY() * posMult;\n deltaZ += -yawCosine * moveTouchpad.getKnobPercentY() * posMult;\n deltaX += yawCosine * moveTouchpad.getKnobPercentX() * posMult;\n deltaZ += yawSine * moveTouchpad.getKnobPercentX() * posMult;\n\n if(!movementHandler.checkDeltaCollision(player, deltaX, 0, deltaZ)\n && !movementHandler.checkDeltaCollision(player, deltaX, 0, deltaZ)) {\n player.getPosition().offset(deltaX, 0, deltaZ);\n gameRenderer.calculateFrustum();\n }\n }\n }\n\n public boolean onAndroid() { return android; }\n\n public PerspectiveCamera getCamera() { return camera; }\n\n public OrthographicCamera getHudCamera() { return hudCamera; }\n\n public MovementHandler getMovementHandler() { return movementHandler; }\n\n public IngameHUD getHud() { return this.hud; }\n\n public ChatGUI getChatGUI() { return this.chatGUI; }\n\n public GameRenderer getGameRenderer() { return this.gameRenderer; }\n\n public boolean isWireframe() { return wireframe; }\n public void setWireframe(boolean wireframe) { this.wireframe = wireframe; }\n\n // Debug text that shows in the ingame HUD\n public boolean debugInfoEnabled() { return debugText; }\n public void setDebugInfo(boolean debugText) { this.debugText = debugText; }\n\n public MainMenu getMainMenu() {\n return mainMenu;\n }\n\n public SceneTheme getSceneTheme() { return sceneTheme; }\n\n}",
"public final class BuiltInBlockIds {\n\n public static final int\n STONE_ID = 1,\n DIRT_ID = 3,\n GRASS_ID = 2,\n COBBLESTONE_ID = 4,\n BEDROCK_ID = 7,\n GRAVEL_ID = 13,\n IRON_ORE_ID = 15,\n COAL_ORE_ID = 16,\n REDSTONE_ORE_ID = 73,\n GOLD_ORE_ID = 14,\n DIAMOND_ORE_ID = 56,\n LAPIS_ORE_ID = 21,\n EMERALD_ORE_ID = 129,\n OBSIDIAN_ID = 49,\n STONE_MONSTER_EGG_ID = 97,\n SNOW_ID = 78,\n SAND_ID = 12,\n WATER_ID = 8,\n WATER_FLOW_ID = 9,\n LAVA_FLOW_ID = 10,\n LAVA_STILL_ID = 11,\n PLANKS_ID = 5,\n LOG_ID = 17,\n LOG_TWO_ID = 162,\n LEAVES_TWO_ID = 161,\n LEAVES_ID = 18,\n STONE_BRICK_ID = 98,\n TALL_GRASS_ID = 31,\n FLOWER_ID = 175,\n FLOWER_TWO_ID = 37,\n FLOWER_THREE_ID = 38,\n BROWN_MUSHROOM_BLOCK_ID = 99,\n RED_MUSHROOM_BLOCK_ID = 100,\n CLAY_ID = 82,\n SUGAR_CANE_ID = 83,\n MOSS_STONE_ID = 48,\n BROWN_MUSHROOM_ID = 39,\n RED_MUSHROOM_ID = 40,\n FENCE_ID = 85,\n UNKNOWN_ID = 1023;\n\n}",
"public class RadixAPI {\n\n public static final RadixAPI instance = new RadixAPI();\n private final EventManager eventManager;\n private final Block[] registeredBlocks = new Block[4096];\n private final Item[] registeredItems = new Item[4096];\n private final Map<String, BlockRenderer> registeredRenderers = new HashMap<>();\n private final Biome[] registeredBiomeArray = new Biome[256];\n private int highestID = 0;\n\n private RadixAPI() {\n this.eventManager = new IridiumEventManager();\n }\n\n /**\n * Gets the event manager that is used to fire and listen to API events\n */\n public EventManager getEventManager() {\n return this.eventManager;\n }\n\n /**\n * @return Whether the current game is a client\n */\n public boolean isClient() {\n return RadixClient.getInstance() != null;\n }\n\n /**\n * Registers the built in items and blocks\n *\n * If you're a mod, please don't call this\n *\n * Called before the item registration event is fired.\n */\n public void registerBuiltinItems() throws BlockRegistrationException {\n try {\n registerItems(\n new Tool(270, \"Wooden Pickaxe\", ToolMaterial.WOOD, ToolType.PICKAXE),\n new Tool(274, \"Stone Pickaxe\", ToolMaterial.STONE, ToolType.PICKAXE),\n new Tool(257, \"Iron Pickaxe\", ToolMaterial.IRON, ToolType.PICKAXE)\n );\n\n String builtinBlockJson = Gdx.files.internal(\"defaultRegistry/blocks.json\").readString();\n try {\n JsonBlock[] blocks = new Gson().fromJson(builtinBlockJson, JsonBlock[].class);\n for(JsonBlock block : blocks) {\n registerBlock(block.createBlock());\n }\n } catch (BlockBuilder.CustomClassException e) {\n System.err.println(e.getMessage());\n e.printStackTrace();\n }\n } catch (BlockBuilder.MissingElementException ex) {\n throw new BlockRegistrationException(ex.getMessage());\n }\n }\n\n /**\n * Register builtin block renderers.\n *\n * If you're a mod, please don't call this.\n *\n * Called before the BlockRenderer registration event is fired.\n *\n * @throws DuplicateRendererException Usually thrown if this is called twice or someone tried to register a block renderer that's already built in.\n */\n public void registerBuiltinBlockRenderers() throws DuplicateRendererException {\n registerBlockRenderers(\n new NormalBlockRenderer(),\n new ColoredFoliageRenderer(),\n new FlatFoliageRenderer(),\n new GrassRenderer(),\n new TallGrassRenderer(),\n new MetadataHeightRenderer(7), // used for snow\n new MetadataHeightRenderer(15, true), // used for liquids\n new FenceRenderer()\n\n );\n }\n\n public void registerMinecraftBiomes() {\n registerBiomes(\n new Gson().fromJson(Gdx.files.internal(\"defaultRegistry/biomes.json\").readString(), Biome[].class)\n );\n }\n\n public void registerBiomes(Biome... biomes) {\n for(Biome b : biomes) {\n registerBiome(b);\n }\n }\n\n public void registerBiome(Biome biome) {\n registeredBiomeArray[biome.getID()] = biome;\n }\n\n public void registerBlockRenderers(BlockRenderer ... renderers) throws DuplicateRendererException {\n for(BlockRenderer br : renderers) {\n registerBlockRenderer(br);\n }\n }\n\n public void registerBlockRenderer(BlockRenderer renderer) throws DuplicateRendererException {\n String id = renderer.getUniqueID();\n if(registeredRenderers.containsKey(id)) {\n throw new DuplicateRendererException(id);\n }\n this.registeredRenderers.put(renderer.getUniqueID(), renderer);\n }\n\n /**\n * Gets the biome with the specific ID\n *\n * If using Minecraft IDs, try the id-128 as variations are usually just parent+128\n */\n public Biome getBiomeByID(int id) {\n if(id >= registeredBiomeArray.length || id < 0)\n return null;\n return registeredBiomeArray[id];\n }\n\n private void registerItems(Item... items) throws BlockRegistrationException {\n for (Item i : items) {\n registerItem(i);\n }\n }\n\n private void registerItem(Item i) throws BlockRegistrationException {\n if (i.getID() == -1) {\n i.setID(highestID);\n System.err.printf(\"Item ID not defined for %s. Using auto generated ID. IF YOU\\'RE THE MOD DEVELOPER, FIX THIS!!!\\n\", i.toString());\n }\n\n if(registeredItems[i.getID()] != null) {\n throw new BlockRegistrationException(\"ID already in use by \" + registeredItems[i.getID()].getHumanName());\n }\n\n this.registeredItems[i.getID()] = i;\n highestID = Math.max(highestID, i.getID());\n }\n\n private void registerBlocks(Block... blocks) throws BlockRegistrationException {\n for (Block b : blocks) {\n registerBlock(b);\n }\n }\n\n private void registerBlock(Block b) throws BlockRegistrationException {\n if (b.getID() == -1) {\n b.setID(highestID);\n System.err.println(\"Block ID not defined for \" + String.valueOf(b) + \". Using auto generated ID. IF YOU\\'RE THE MOD DEVELOPER, FIX THIS!!!\");\n }\n\n if(registeredBlocks[b.getID()] != null) {\n throw new BlockRegistrationException(\"ID already in use by \" + registeredBlocks[b.getID()]);\n }\n\n this.registeredBlocks[b.getID()] = b;\n highestID = Math.max(highestID, b.getID());\n\n registerItem(b);\n }\n\n public Block[] getBlocks() {\n return registeredBlocks;\n }\n\n /**\n * Get block by its ID.\n * Should only be used with static IDs for builtin blocks since mods will often (and should) have configurable IDs.\n *\n * @param id ID that the block has in the registry.\n * @return null (should be treated as air) if id is 0 or below, is greater than the maximum allowed id, or is not registered.\n */\n public Block getBlock(int id) {\n if(id <= 0)\n return null;\n if(id >= registeredBlocks.length)\n return null;\n\n return registeredBlocks[id];\n }\n\n /**\n * Get item by its ID.\n * Should only be used with static IDs for builtin items since mods will often (and should) have configurable IDs.\n *\n * @param id ID that the item has in the registry.\n * @return null if id is 0 or below, is greater than the maximum allowed id, or is not registered.\n */\n public Item getItem(int id) {\n if(id <= 0)\n return null;\n if(id >= registeredItems.length)\n return null;\n\n return registeredItems[id];\n }\n\n /**\n * Get the BlockRenderer registered with the specified unique ID\n *\n * @param uid Unique ID of the renderer to get. Returned by BlockRenderer.getUniqueID().\n * @throws sx.lambda.voxel.api.RadixAPI.NoSuchRendererException No renderer existed with the specified UID.\n */\n public BlockRenderer getBlockRenderer(String uid) throws NoSuchRendererException {\n BlockRenderer renderer = registeredRenderers.get(uid);\n if(renderer != null) {\n return renderer;\n } else {\n throw new NoSuchRendererException(uid);\n }\n }\n\n public class BlockRegistrationException extends Exception {\n public BlockRegistrationException(String reason) {\n super(reason);\n }\n }\n\n public class NoSuchRendererException extends BlockRegistrationException {\n public NoSuchRendererException(String renderer) {\n super(String.format(\n \"Renderer \\\"%s\\\" does not exist. \" +\n \"Make sure you registered it before the block load phase. Also check for typos.\",\n renderer\n ));\n }\n\n public NoSuchRendererException(String blockName, String renderer) {\n super(String.format(\n \"Renderer \\\"%s\\\" does not exist for block \\\"%s\\\". \" +\n \"Make sure you registered it before the block load phase. Also check for typos.\",\n renderer, blockName\n ));\n }\n }\n\n public class DuplicateRendererException extends BlockRegistrationException {\n public DuplicateRendererException(String renderer) {\n super(String.format(\n \"Renderer with id \\\"%s\\\" already exists and is cannot be redifined. \" +\n \"Make sure you are using a unique ID and are not registering twice.\",\n renderer\n ));\n }\n }\n\n}",
"public class Vec3i implements Serializable {\n public int x, y, z;\n\n /**\n * Constructs a new Vec3i with this value: (0, 0, 0)\n */\n public Vec3i() {\n this(0, 0, 0);\n }\n\n public Vec3i(int x, int y, int z) {\n super();\n set(x, y, z);\n }\n\n /**\n * Constructs a new Vec3i and copies the values of the passed vector.\n * @param v the vector to be copied\n */\n public Vec3i(Vec3i v) {\n this(v.x, v.y, v.z);\n }\n\n public void set(int x, int y, int z) {\n this.x = x;\n this.y = y;\n this.z = z;\n }\n\n /**\n * Subtracts this vector with the passed vector.\n *\n * @param v\n * the vector to subtract from this\n * @return {@code this}\n */\n public Vec3i sub(Vec3i v) {\n set(x - v.x, y - v.y, z - v.z);\n return this;\n }\n\n /**\n * Adds the passed vector to this vector\n *\n * @param v\n * the vector to add\n * @return {@code this}\n */\n public Vec3i add(Vec3i v) {\n set(x + v.x, y + v.y, z + v.z);\n return this;\n }\n\n\n /**\n * Performs a scalar product on this vector\n * @param f Scale factor\n * @return {@code this}\n */\n public Vec3i scale(float f) {\n set(MathUtils.floor(x * f), MathUtils.floor(y * f), MathUtils.floor(z * f));\n return this;\n }\n\n /**\n * Uses cache.\n *\n * @return the squared length of this vector\n */\n public float lengthSquared() {\n return x * x + y * y + z * z;\n }\n\n /**\n * Uses cache.\n *\n * @return the length of this vector\n */\n public float length() {\n return (float) Math.sqrt(lengthSquared());\n }\n\n /**\n * This vector will be the result of the cross product, performed on the two\n * vectors passed. Returns {@code this} vector.\n *\n * @param a Vector 1\n * @param b Vector 2\n * @return {@code this}\n */\n public Vec3i cross(Vec3i a, Vec3i b) {\n set(a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x);\n return this;\n }\n\n /**\n * Performs a dot product on the two specified vectors.\n * @param a Vector 1\n * @param b Vector 2\n * @return the result of the dot product.\n */\n public static int dot(Vec3i a, Vec3i b) {\n return a.x * b.x + a.y * b.y + a.z * b.z;\n }\n\n public void set(Vec3i vec) {\n set(vec.x, vec.y, vec.z);\n }\n\n @Override\n public int hashCode() {\n final int prime = 31;\n int result = 1;\n result = prime * result + x;\n result = prime * result + y;\n result = prime * result + z;\n return result;\n }\n\n @Override\n public boolean equals(Object obj) {\n if (this == obj)\n return true;\n if (obj == null)\n return false;\n if (getClass() != obj.getClass())\n return false;\n Vec3i other = (Vec3i) obj;\n if (x != other.x)\n return false;\n if (y != other.y)\n return false;\n\n return z == other.z;\n }\n\n public Vec3i translate(int x, int y, int z) {\n return new Vec3i(this.x + x, this.y + y, this.z + z);\n }\n\n\n @Override\n public String toString() {\n return \"Vec3i [x=\" + x + \", y=\" + y + \", z=\" + z + \"]\";\n }\n\n public boolean equals(int x, int y, int z) {\n return this.x == x && this.y == y && this.z == z;\n }\n}",
"public class Biome {\n // Biome color math from https://github.com/erich666/Mineways/blob/master/Win/biomes.cpp\n\n private static final int[][] grassColors =\n {\n { 191, 183, 85 },\t// lower left, temperature starts at 1.0 on left\n { 128, 180, 151 },\t// lower right\n { 71, 205, 51 }\t// upper left\n };\n\n private static final int[][] foliageCorners =\n {\n { 174, 164, 42 },\t// lower left, temperature starts at 1.0 on left\n { 96, 161, 123 },\t// lower right\n { 26, 191, 0 }\t// upper left\n };\n\n private final String humanName;\n private final float temperature, rainfall;\n private final int id;\n\n public Biome(int id, String humanName, float temperature, float rainfall) {\n this.humanName = humanName;\n this.temperature = temperature;\n this.rainfall = rainfall;\n this.id = id;\n }\n\n public float getTemperature() {\n return this.temperature;\n }\n\n public float getRainfall() {\n return this.rainfall;\n }\n\n public int getID() {\n return id;\n }\n\n public int[] getGrassColor(int elevation) {\n return getColor(elevation, grassColors);\n }\n\n public int[] getFoliageColor(int elevation) {\n return getColor(elevation, foliageCorners);\n }\n\n private static final float getColTmp[] = new float[3];\n private int[] getColor(int elevation, int[][] corners) {\n float adjTemp = MathUtils.clamp(temperature - elevation*0.00166667f, 0, 1);\n float adjRainfall = MathUtils.clamp(rainfall, 0, 1) * adjTemp;\n\n getColTmp[0] = adjTemp - adjRainfall;\n getColTmp[1] = 1 - temperature;\n getColTmp[2] = rainfall;\n\n float red = 0, green = 0, blue = 0;\n for(int i = 0; i < 3; i++) {\n red += getColTmp[i] * corners[i][0/*red*/];\n green += getColTmp[i] * corners[i][1/*green*/];\n blue += getColTmp[i] * corners[i][2/*blue*/];\n }\n\n return new int[]{\n (int)MathUtils.clamp(red, 0, 255),\n (int)MathUtils.clamp(green, 0, 255),\n (int)MathUtils.clamp(blue, 0, 255)\n };\n }\n\n}",
"public interface BlockStorage {\n\n void setId(int x, int y, int z, int id) throws CoordinatesOutOfBoundsException;\n short getId(int x, int y, int z) throws CoordinatesOutOfBoundsException;\n void setMeta(int x, int y, int z, int meta) throws CoordinatesOutOfBoundsException;\n short getMeta(int x, int y, int z) throws CoordinatesOutOfBoundsException;\n void setBlock(int x, int y, int z, Block block) throws CoordinatesOutOfBoundsException;\n Block getBlock(int x, int y, int z) throws CoordinatesOutOfBoundsException;\n void setSunlight(int x, int y, int z, int sunlight) throws CoordinatesOutOfBoundsException;\n byte getSunlight(int x, int y, int z) throws CoordinatesOutOfBoundsException;\n void setBlocklight(int x, int y, int z, int blocklight) throws CoordinatesOutOfBoundsException;\n byte getBlocklight(int x, int y, int z) throws CoordinatesOutOfBoundsException;\n\n int getWidth();\n int getHeight();\n int getDepth();\n\n class CoordinatesOutOfBoundsException extends Exception {}\n\n}",
"public class FlatBlockStorage implements BlockStorage {\n\n private final int width, depth, height, size;\n private short[] blocks; // last nibble is metadata, everything up to that is block id\n private NibbleArray3d sunlight;\n private NibbleArray3d blocklight;\n\n public FlatBlockStorage(int width, int height, int depth) {\n this.width = width;\n this.height = height;\n this.depth = depth;\n this.size = width*height*depth;\n\n blocks = new short[size];\n sunlight = new NibbleArray3d(size);\n blocklight = new NibbleArray3d(size);\n }\n\n /**\n * ONLY USE THIS CONSTRUCTOR WITH ALLOCATE SET TO FALSE IF YOU'RE GOING TO IMMEDIATELY FILL IN BLOCKS, SUNLIGHT, AND BLOCKLIGHT\n * @param allocate Whether to default the arrays. Set to false if you're going to manually set them immediately after construction.\n */\n public FlatBlockStorage(int width, int height, int depth, boolean allocate) {\n this.width = width;\n this.height = height;\n this.depth = depth;\n this.size = width*height*depth;\n\n if(allocate) {\n blocks = new short[size];\n sunlight = new NibbleArray3d(size);\n blocklight = new NibbleArray3d(size);\n }\n }\n\n @Override\n public void setId(int x, int y, int z, int id) throws CoordinatesOutOfBoundsException {\n if(x < 0 || x >= width || z < 0 || z >= depth || y < 0 || y >= height)\n throw new CoordinatesOutOfBoundsException();\n\n int index = getIndex(x, y, z);\n blocks[index] = (short)(id << 4 | (blocks[index] & 0xF));\n }\n\n @Override\n public short getId(int x, int y, int z) throws CoordinatesOutOfBoundsException {\n if(x < 0 || x >= width || z < 0 || z >= depth || y < 0 || y >= height)\n throw new CoordinatesOutOfBoundsException();\n\n return (short)(blocks[getIndex(x, y, z)] >> 4);\n }\n\n @Override\n public void setMeta(int x, int y, int z, int meta) throws CoordinatesOutOfBoundsException {\n if(x < 0 || x >= width || z < 0 || z >= depth || y < 0 || y >= height)\n throw new CoordinatesOutOfBoundsException();\n\n int index = getIndex(x, y, z);\n blocks[index] = (short)((blocks[index] >> 4 << 4) | meta);\n }\n\n @Override\n public short getMeta(int x, int y, int z) throws CoordinatesOutOfBoundsException {\n if(x < 0 || x >= width || z < 0 || z >= depth || y < 0 || y >= height)\n throw new CoordinatesOutOfBoundsException();\n\n return (short)(blocks[getIndex(x, y, z)] & 0xF);\n }\n\n @Override\n public void setBlock(int x, int y, int z, Block block) throws CoordinatesOutOfBoundsException {\n }\n\n @Override\n public Block getBlock(int x, int y, int z) throws CoordinatesOutOfBoundsException {\n return RadixAPI.instance.getBlock(getId(x, y, z));\n }\n\n @Override\n public void setSunlight(int x, int y, int z, int sunlight) throws CoordinatesOutOfBoundsException {\n if(x < 0 || x >= width || z < 0 || z >= depth || y < 0 || y >= height)\n throw new CoordinatesOutOfBoundsException();\n\n this.sunlight.set(x, y, z, sunlight);\n }\n\n @Override\n public byte getSunlight(int x, int y, int z) throws CoordinatesOutOfBoundsException {\n if(x < 0 || x >= width || z < 0 || z >= depth || y < 0 || y >= height)\n throw new CoordinatesOutOfBoundsException();\n\n return (byte)this.sunlight.get(x, y, z);\n }\n\n @Override\n public void setBlocklight(int x, int y, int z, int blocklight) throws CoordinatesOutOfBoundsException {\n if(x < 0 || x >= width || z < 0 || z >= depth || y < 0 || y >= height)\n throw new CoordinatesOutOfBoundsException();\n\n this.blocklight.set(x, y, z, blocklight);\n }\n\n @Override\n public byte getBlocklight(int x, int y, int z) throws CoordinatesOutOfBoundsException {\n if(x < 0 || x >= width || z < 0 || z >= depth || y < 0 || y >= height)\n throw new CoordinatesOutOfBoundsException();\n\n return (byte)this.blocklight.get(x, y, z);\n }\n\n @Override\n public int getWidth() {\n return width;\n }\n\n @Override\n public int getHeight() {\n return height;\n }\n\n @Override\n public int getDepth() {\n return depth;\n }\n\n /**\n * Set underlying sunlight array\n */\n public void setSunlight(NibbleArray3d nibbleArray) {\n this.sunlight = nibbleArray;\n }\n\n /**\n * Set underlying blocklight array\n */\n public void setBlocklight(NibbleArray3d nibbleArray) {\n this.blocklight = nibbleArray;\n }\n\n /**\n * Set underlying block array.\n * Should probably only call this if you know what you're doing.\n * @param blocks Array of shorts with the last nibble as the metadata and everything before it as tbe block id\n */\n public void setBlocks(short[] blocks) {\n this.blocks = blocks;\n }\n\n private int getIndex(int x, int y, int z) throws CoordinatesOutOfBoundsException {\n if(x < 0 || x > width || y < 0 || y > height || z < 0 || z > depth)\n throw new CoordinatesOutOfBoundsException();\n\n return x + z*width + y*width*depth;\n }\n\n}"
] | import com.badlogic.gdx.Gdx;
import org.spacehq.mc.protocol.data.game.chunk.Chunk;
import org.spacehq.mc.protocol.data.game.world.block.BlockState;
import org.spacehq.mc.protocol.packet.ingame.server.world.ServerChunkDataPacket;
import sx.lambda.voxel.RadixClient;
import sx.lambda.voxel.api.BuiltInBlockIds;
import sx.lambda.voxel.api.RadixAPI;
import sx.lambda.voxel.util.Vec3i;
import sx.lambda.voxel.world.biome.Biome;
import sx.lambda.voxel.world.chunk.BlockStorage;
import sx.lambda.voxel.world.chunk.FlatBlockStorage; | package sx.lambda.voxel.net.mc.client.handlers;
public class ChunkDataHandler implements PacketHandler<ServerChunkDataPacket> {
private final RadixClient game;
public ChunkDataHandler(RadixClient game) {
this.game = game;
}
@Override
public void handle(ServerChunkDataPacket scdp) {
if(scdp.getColumn().getChunks().length == 0) {
RadixClient.getInstance().getWorld().rmChunk(RadixClient.getInstance().getWorld().getChunk(scdp.getColumn().getX(), scdp.getColumn().getZ()));
}
int biomeID = 0;
if(scdp.getColumn().getBiomeData() != null) {
biomeID = scdp.getColumn().getBiomeData()[0];
}
Biome biome = RadixAPI.instance.getBiomeByID(biomeID);
if(biome == null)
biome = RadixAPI.instance.getBiomeByID(biomeID-128);
if(biome == null)
biome = RadixAPI.instance.getBiomeByID(0);
int cx = scdp.getColumn().getX()*16;
int cz = scdp.getColumn().getZ()*16;
sx.lambda.voxel.world.chunk.Chunk ck = (sx.lambda.voxel.world.chunk.Chunk)game.getWorld().getChunk(cx, cz);
boolean hadChunk = ck != null;
if(!hadChunk) {
ck = new sx.lambda.voxel.world.chunk.Chunk(game.getWorld(), new Vec3i(cx, 0, cz), biome, false);
}
FlatBlockStorage[] blockStorages = ck.getBlockStorage();
int yIndex = 0;
int highestPoint = 0;
for(Chunk c : scdp.getColumn().getChunks()) {
if(c == null) {
yIndex++;
continue;
}
FlatBlockStorage storage = blockStorages[yIndex];
if(storage == null) {
storage = blockStorages[yIndex] = new FlatBlockStorage(16, 16, 16);
}
for(int y = 0; y < 16; y++) {
for(int z = 0; z < 16; z++) {
for(int x = 0; x < 16; x++) {
BlockState blk = c.getBlocks().get(x, y, z);
int id = blk.getId();
if(id == 0)
continue;
int meta = blk.getData();
boolean exists = RadixAPI.instance.getBlock(id) != null;
if(!exists) {
try { | storage.setId(x, y, z, BuiltInBlockIds.UNKNOWN_ID); | 1 |
synapticloop/routemaster | src/main/java/synapticloop/nanohttpd/example/servant/HandlerServant.java | [
"public abstract class Handler {\n\t/**\n\t * Return whether this handler can serve the requested URI\n\t * \n\t * @param uri the URI to check\n\t * \n\t * @return whether this handler can serve the requested URI\n\t */\n\tpublic abstract boolean canServeUri(String uri);\n\t\n\t/**\n\t * If the handler can serve this URI, then it will be requested to serve up \n\t * the content\n\t * \n\t * @param rootDir The root directory where the routemaster was started from\n\t * @param uri The URI that is requested to be served\n\t * @param headers The headers that are passed through\n\t * @param session The session object\n\t * \n\t * @return The response that will be sent back to the clien\n\t */\n\tpublic abstract Response serveFile(File rootDir, String uri, Map<String, String> headers, IHTTPSession session);\n\n\t/**\n\t * Get the name of the handler\n\t * \n\t * @return the name of the handler (by default the canonical name of this class)\n\t */\n\tpublic String getName() {\n\t\treturn(this.getClass().getCanonicalName());\n\t}\n\n\t/**\n\t * Get the mimetype for the handler file. This will return the mimetype from \n\t * the file that is requested, by using the fileName.mimeType.handlerExtension.\n\t * \n\t * For example - index.html.templar will look up the mime type mappings for \n\t * 'html', and return the mimetype (if one exists). Else it will return null\n\t * \n\t * @param uri the URI to lookup\n\t * \n\t * @return the mime type if found in the lookup table, else null\n\t */\n\tprotected String getMimeType(String uri) {\n\t\tString[] split = uri.split(\"\\\\.\");\n\t\tint length = split.length;\n\n\t\tif(length > 2) {\n\t\t\t// the last one is .templar\n\t\t\t// the second last one is the mime type we need to lookup\n\t\t\treturn(MimeTypeMapper.getMimeTypes().get(split[length -2]));\n\t\t}\n\t\treturn(null);\n\t}\n\n}",
"public abstract class Routable {\n\t// the route that this routable is bound to\n\tprotected String routeContext = null;\n\t// the map of option key values\n\tprotected Map<String, String> options = new HashMap<String, String>();\n\n\t/**\n\t * Create a new routable class with the bound routing context\n\t *\n\t * @param routeContext the context to route to\n\t */\n\tpublic Routable(String routeContext) {\n\t\tthis.routeContext = routeContext;\n\t}\n\n\t/**\n\t * Serve the correctly routed file\n\t *\n\t * @param rootDir The root directory of the RouteMaster server\n\t * @param httpSession The session\n\t *\n\t * @return The response\n\t */\n\tpublic abstract Response serve(File rootDir, IHTTPSession httpSession);\n\t\n\t/**\n\t * Set an option for this routable into the options map.\n\t * \n\t * @param key The option key\n\t * @param value the value\n\t */\n\tpublic void setOption(String key, String value) {\n\t\toptions.put(key, value);\n\t}\n\n\t/**\n\t * Get an option from the map, or null if it does not exist\n\t * \n\t * @param key the key to search for\n\t * \n\t * @return the value of the option, or null if it doesn't exist\n\t */\n\tpublic String getOption(String key) {\n\t\treturn(options.get(key));\n\t}\n}",
"public class RouteMaster {\n\tprivate static final String ROUTEMASTER_PROPERTIES = \"routemaster.properties\";\n\tprivate static final String ROUTEMASTER_JSON = \"routemaster.json\";\n\tprivate static final String ROUTEMASTER_EXAMPLE_PROPERTIES = \"routemaster.example.properties\";\n\tprivate static final String ROUTEMASTER_EXAMPLE_JSON = \"routemaster.example.json\";\n\n\tprivate static final String PROPERTY_PREFIX_REST = \"rest.\";\n\tprivate static final String PROPERTY_PREFIX_ROUTE = \"route.\";\n\tprivate static final String PROPERTY_PREFIX_HANDLER = \"handler.\";\n\n\tprivate static Router router = null;\n\n\tprivate static Set<String> indexFiles = new HashSet<String>();\n\tprivate static Map<Integer, String> errorPageCache = new ConcurrentHashMap<Integer, String>();\n\tprivate static Map<String, Routable> routerCache = new ConcurrentHashMap<String, Routable>();\n\tprivate static Map<String, Handler> handlerCache = new ConcurrentHashMap<String, Handler>();\n\tprivate static Set<String> modules = new HashSet<String>();\n\n\tprivate static boolean initialised = false;\n\tprivate static File rootDir;\n\n\tprivate RouteMaster() {}\n\n\t/**\n\t * Initialise the RouteMaster by attempting to look for the routemaster.properties\n\t * in the classpath and on the file system.\n\t * \n\t * @param rootDir the root directory from which content should be sourced\n\t */\n\tpublic static void initialise(File rootDir) {\n\t\tRouteMaster.rootDir = rootDir;\n\n\t\tProperties properties = null;\n\t\tboolean allOk = true;\n\n\t\ttry {\n\t\t\tproperties = FileHelper.confirmPropertiesFileDefault(ROUTEMASTER_PROPERTIES, ROUTEMASTER_EXAMPLE_PROPERTIES);\n\t\t} catch (IOException ioex) {\n\t\t\ttry {\n\t\t\t\tlogNoRoutemasterProperties();\n\t\t\t} catch (IOException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t\tallOk = false;\n\t\t}\n\n\t\tif(null == properties) {\n\t\t\ttry {\n\t\t\t\tlogNoRoutemasterProperties();\n\t\t\t} catch (IOException e) {\n\t\t\t\t// TODO Auto-generated catch block\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t\tallOk = false;\n\t\t}\n\n\t\tif(allOk) {\n\t\t\t// at this point we want to load any modules that we find, and at them to the \n\t\t\t// properties file\n\t\t\tloadModules(properties);\n\n\t\t\tparseOptionsAndRoutes(properties);\n\t\t\tinitialised = true;\n\t\t} else {\n\t\t\tStringTokenizer stringTokenizer = new StringTokenizer(\"/*\", \"/\", false);\n\t\t\trouter = new Router(\"/*\", stringTokenizer, UninitialisedServant.class.getCanonicalName());\n\t\t}\n\t}\n\n\t/**\n\t * Dynamically load any modules that exist within the 'modules' directory\n\t * \n\t * @param properties the properties from the default routemaster.properties\n\t */\n\tprivate static void loadModules(Properties properties) {\n\t\t// look in the modules directory\n\t\tFile modulesDirectory = new File(rootDir.getAbsolutePath() + \"/modules/\");\n\t\tif(modulesDirectory.exists() && modulesDirectory.isDirectory() && modulesDirectory.canRead()) {\n\t\t\tString[] moduleList = modulesDirectory.list(new FilenameFilter() {\n\n\t\t\t\t@Override\n\t\t\t\tpublic boolean accept(File dir, String name) {\n\t\t\t\t\treturn(name.endsWith(\".jar\"));\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tint length = moduleList.length;\n\n\t\t\tif(length == 0) {\n\t\t\t\tlogInfo(\"No modules found, continuing...\");\n\t\t\t} else {\n\t\t\t\tlogInfo(\"Scanning '\" + length + \"' jar files for modules\");\n\t\t\t\tURLClassLoader classLoader = (URLClassLoader)ClassLoader.getSystemClassLoader();\n\t\t\t\tMethod method = null;\n\t\t\t\ttry {\n\t\t\t\t\tmethod = URLClassLoader.class.getDeclaredMethod(\"addURL\", URL.class);\n\t\t\t\t} catch (Exception ex) {\n\t\t\t\t\tlogFatal(\"Could not load any modules, exception message was: \" + ex.getMessage());\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tmethod.setAccessible(true);\n\t\t\t\tfor (String module : moduleList) {\n\t\t\t\t\tlogInfo(\"Found potential module in file '\" + module + \"'.\");\n\n\t\t\t\t\tFile file = new File(rootDir + \"/modules/\" + module);\n\n\t\t\t\t\t// try and find the <module>-<version>.jar.properties file which will\n\t\t\t\t\t// over-ride the routemaster.properties entry in the jar file\n\n\t\t\t\t\tboolean loadedOverrideProperties = false;\n\n\t\t\t\t\tString moduleName = getModuleName(module);\n\t\t\t\t\tFile overridePropertiesFile = new File(rootDir + \"/modules/\" + moduleName + \".properties\");\n\t\t\t\t\tif(overridePropertiesFile.exists() && overridePropertiesFile.canRead()) {\n\t\t\t\t\t\tlogInfo(\"[ \" + module + \" ] Found an over-ride .properties file '\" + moduleName + \".properties'.\");\n\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\tProperties mergeProperties = new Properties();\n\t\t\t\t\t\t\tmergeProperties.load(new FileReader(overridePropertiesFile));\n\t\t\t\t\t\t\tIterator<Object> iterator = mergeProperties.keySet().iterator();\n\t\t\t\t\t\t\twhile (iterator.hasNext()) {\n\t\t\t\t\t\t\t\tString key = (String) iterator.next();\n\t\t\t\t\t\t\t\tif(properties.containsKey(key)) {\n\t\t\t\t\t\t\t\t\tlogWarn(\"[ \" + module + \" ] Routemaster already has a property with key '\" + key + \"', over-writing...\");\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tString value = mergeProperties.getProperty(key);\n\t\t\t\t\t\t\t\tproperties.setProperty(key, value);\n\n\t\t\t\t\t\t\t\tlogInfo(\"[ \" + module + \" ] Adding property key '\" + key + \"', value '\" + value + \"'\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tloadedOverrideProperties = true;\n\t\t\t\t\t\t} catch (IOException ex) {\n\t\t\t\t\t\t\tlogFatal(\"Could not load modules message was: \" + ex.getMessage());\n\t\t\t\t\t\t}\n\t\t\t\t\t} \n\n\t\t\t\t\ttry {\n\t\t\t\t\t\t\tJarFile jarFile = new JarFile(file);\n\t\t\t\t\t\t\tZipEntry zipEntry = jarFile.getEntry(moduleName + \".properties\");\n\t\t\t\t\t\t\tif(null != zipEntry) {\n\t\t\t\t\t\t\t\tURL url = file.toURI().toURL();\n\t\t\t\t\t\t\t\tmethod.invoke(classLoader, url);\n\n\t\t\t\t\t\t\t\tif(!loadedOverrideProperties) { \n\t\t\t\t\t\t\t\t\t// assuming that the above works - read the properties from the \n\t\t\t\t\t\t\t\t\t// jar file\n\t\t\t\t\t\t\t\t\treadProperties(module, properties, jarFile, zipEntry);\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\tif(!modules.contains(module)) {\n\t\t\t\t\t\t\t\t\tmodules.add(module);\n\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tlogWarn(\"[ \" + module + \" ] Could not find '/\" + moduleName + \".properties' in file '\" + module + \"'.\");\n\t\t\t\t\t\t\t}\n\t\n\t\t\t\t\t\t\tjarFile.close();\n\t\t\t\t\t\t} catch (Exception ex) {\n\t\t\t\t\t\t\tlogFatal(\"Could not load modules message was: \" + ex.getMessage());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate static void readProperties(String module, Properties properties, JarFile jarFile, ZipEntry zipEntry) throws IOException {\n\t\tInputStream input = jarFile.getInputStream(zipEntry);\n\t\tInputStreamReader isr = new InputStreamReader(input);\n\t\tBufferedReader reader = new BufferedReader(isr);\n\t\tString line;\n\t\twhile ((line = reader.readLine()) != null) {\n\t\t\tString trimmed = line.trim();\n\n\t\t\tif(trimmed.length() != 0) {\n\t\t\t\tif(trimmed.startsWith(\"#\")) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tString[] split = line.split(\"=\", 2);\n\t\t\t\tif(split.length == 2) {\n\t\t\t\t\tString key = split[0].trim();\n\t\t\t\t\tString value = split[1].trim();\n\t\t\t\t\tif(properties.containsKey(key)) {\n\t\t\t\t\t\tlogWarn(\"[ \" + module + \" ] Routemaster already has a property with key '\" + key + \"', over-writing...\");\n\t\t\t\t\t}\n\n\t\t\t\t\tproperties.setProperty(key, value);\n\t\t\t\t\tlogInfo(\"[ \" + module + \" ] Adding property key '\" + key + \"', value '\" + value + \"'\");\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treader.close();\n\t}\n\n\tprivate static String getModuleName(String module) {\n\t\tPattern r = Pattern.compile(\"(.*)-\\\\d+\\\\.\\\\d+.*\\\\.jar\");\n\t\tMatcher m = r.matcher(module);\n\t\tif(m.matches()) {\n\t\t\treturn(m.group(1));\n\t\t}\n\n\t\tint lastIndexOf = module.lastIndexOf(\".\");\n\t\treturn(module.substring(0, lastIndexOf));\n\t}\n\n\tprivate static void parseOptionsAndRoutes(Properties properties) {\n\t\t// now parse the properties\n\t\tparseOptions(properties);\n\t\tEnumeration<Object> keys = properties.keys();\n\n\t\twhile (keys.hasMoreElements()) {\n\t\t\tString key = (String) keys.nextElement();\n\t\t\tString routerClass = (String)properties.get(key);\n\t\t\tif(key.startsWith(PROPERTY_PREFIX_ROUTE)) {\n\t\t\t\t// time to bind a route\n\t\t\t\tString subKey = key.substring(PROPERTY_PREFIX_ROUTE.length());\n\t\t\t\tStringTokenizer stringTokenizer = new StringTokenizer(subKey, \"/\", false);\n\t\t\t\tif(null == router) {\n\t\t\t\t\trouter = new Router(subKey, stringTokenizer, routerClass);\n\t\t\t\t} else {\n\t\t\t\t\trouter.addRoute(subKey, stringTokenizer, routerClass);\n\t\t\t\t}\n\t\t\t} else if(key.startsWith(PROPERTY_PREFIX_REST)) {\n\t\t\t\t// time to bind a rest route\n\t\t\t\tString subKey = key.substring(PROPERTY_PREFIX_REST.length());\n\t\t\t\t// now we need to get the parameters\n\t\t\t\tString[] splits = subKey.split(\"/\");\n\t\t\t\tStringBuilder stringBuilder = new StringBuilder();\n\n\t\t\t\tList<String> params = new ArrayList<String>();\n\t\t\t\tif(subKey.startsWith(\"/\")) { stringBuilder.append(\"/\"); }\n\n\t\t\t\tfor (int i = 0; i < splits.length; i++) {\n\t\t\t\t\tString split = splits[i];\n\t\t\t\t\tif(split.length() == 0) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif(split.startsWith(\"%\") && split.endsWith(\"%\")) {\n\t\t\t\t\t\t// have a parameter\n\t\t\t\t\t\tparams.add(split.substring(1, split.length() -1));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tstringBuilder.append(split);\n\t\t\t\t\t\t// keep adding a slash for those that are missing - but not\n\t\t\t\t\t\t// if it the last\n\t\t\t\t\t\tif(i != splits.length -1) { stringBuilder.append(\"/\"); }\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// now clean up the route\n\t\t\t\tString temp = stringBuilder.toString();\n\t\t\t\tif(!temp.endsWith(\"/\")) { stringBuilder.append(\"/\"); }\n\t\t\t\t// need to make sure that the rest router always picks up wildcards\n\t\t\t\tif(!subKey.endsWith(\"*\")) { stringBuilder.append(\"*\"); }\n\n\t\t\t\tsubKey = stringBuilder.toString();\n\t\t\t\tStringTokenizer stringTokenizer = new StringTokenizer(subKey, \"/\", false);\n\t\t\t\tif(null == router) {\n\t\t\t\t\trouter = new Router(subKey, stringTokenizer, routerClass, params);\n\t\t\t\t} else {\n\t\t\t\t\trouter.addRestRoute(subKey, stringTokenizer, routerClass, params);\n\t\t\t\t}\n\n\t\t\t} else if(key.startsWith(PROPERTY_PREFIX_HANDLER)) {\n\t\t\t\t// we are going to add in a plugin\n\t\t\t\tString subKey = key.substring(PROPERTY_PREFIX_HANDLER.length());\n\t\t\t\tString pluginProperty = properties.getProperty(key);\n\n\t\t\t\ttry {\n\t\t\t\t\tObject pluginClass = Class.forName(pluginProperty).newInstance();\n\t\t\t\t\tif(pluginClass instanceof Handler) {\n\t\t\t\t\t\thandlerCache.put(subKey, (Handler)pluginClass);\n\t\t\t\t\t\tlogInfo(\"Handler '\" + pluginClass + \"', registered for '*.\" + subKey + \"'.\");\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlogFatal(\"Plugin class '\" + pluginProperty + \"' is not of instance Plugin.\");\n\t\t\t\t\t}\n\t\t\t\t} catch (ClassNotFoundException cnfex) {\n\t\t\t\t\tlogFatal(\"Could not find the class for '\" + pluginProperty + \"'.\", cnfex);\n\t\t\t\t} catch (InstantiationException iex) {\n\t\t\t\t\tlogFatal(\"Could not instantiate the class for '\" + pluginProperty + \"'.\", iex);\n\t\t\t\t} catch (IllegalAccessException iaex) {\n\t\t\t\t\tlogFatal(\"Illegal acces for class '\" + pluginProperty + \"'.\", iaex);\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\tlogWarn(\"Unknown property prefix for key '\" + key + \"'.\");\n\t\t\t}\n\t\t}\n\n\t\tif(null != router) {\n\t\t\tlogTable(router.getRouters(), \"registered routes\", \"route\", \"routable class\");\n\t\t}\n\n\t\tlogTable(new ArrayList<String>(modules), \"loaded modules\");\n\n\t\tif(indexFiles.isEmpty()) {\n\t\t\t// default welcomeFiles\n\t\t\tindexFiles.add(\"index.html\");\n\t\t\tindexFiles.add(\"index.htm\");\n\t\t}\n\n\t\tlogTable(new ArrayList<String>(indexFiles), \"index files\");\n\n\t\tlogTable(errorPageCache, \"error pages\", \"status\", \"page\");\n\n\t\tlogTable(handlerCache, \"Handlers\", \"extension\", \"handler class\");\n\n\t\tMimeTypeMapper.logMimeTypes();\n\n\t\tlogInfo(RouteMaster.class.getSimpleName() + \" initialised.\");\n\t}\n\n\tprivate static void logNoRoutemasterProperties() throws IOException {\n//\t\tlogFatal(\"Could not load the '\" + ROUTEMASTER_JSON + \"' file, ignoring...\");\n//\t\tlogFatal(\"(Consequently this is going to be a pretty boring experience!\");\n//\t\tlogFatal(\"but we did write out an example file for you - '\" + ROUTEMASTER_EXAMPLE_JSON + \"')\");\n//\t\tlogFatal(\"NOTE: the '\" + ROUTEMASTER_EXAMPLE_JSON + \"' takes precedence)\");\n//\t\tInputStream inputStream = RouteMaster.class.getResourceAsStream(\"/\" + ROUTEMASTER_EXAMPLE_JSON);\n//\n//\t\tFileHelper.writeFile(new File(ROUTEMASTER_EXAMPLE_JSON), inputStream, true);\n//\t\tinputStream.close();\n\n\t\tlogFatal(\"Could not load the '\" + ROUTEMASTER_PROPERTIES + \"' file, ignoring...\");\n\t\tlogFatal(\"(Consequently this is going to be a pretty boring experience!\");\n\t\tlogFatal(\"but we did write out an example file for you - '\" + ROUTEMASTER_EXAMPLE_PROPERTIES + \"')\");\n\n\t\tInputStream inputStream = RouteMaster.class.getResourceAsStream(\"/\" + ROUTEMASTER_EXAMPLE_PROPERTIES);\n\t\tFileHelper.writeFile(new File(ROUTEMASTER_EXAMPLE_PROPERTIES), inputStream, true);\n\t\tinputStream.close();\n\n\t}\n\n\t/**\n\t * Parse the options file\n\t *\n\t * @param properties The properties object\n\t * @param key the option key we are looking at\n\t */\n\tprivate static void parseOption(Properties properties, String key) {\n\t\tif(\"option.indexfiles\".equals(key)) {\n\t\t\tString property = properties.getProperty(key);\n\t\t\tString[] splits = property.split(\",\");\n\t\t\tfor (int i = 0; i < splits.length; i++) {\n\t\t\t\tString split = splits[i].trim();\n\t\t\t\tindexFiles.add(split);\n\t\t\t}\n\t\t} else if(key.startsWith(\"option.error.\")) {\n\t\t\tString subKey = key.substring(\"option.error.\".length());\n\t\t\ttry {\n\t\t\t\tint parseInt = Integer.parseInt(subKey);\n\t\t\t\terrorPageCache.put(parseInt, properties.getProperty(key));\n\t\t\t} catch(NumberFormatException nfex) {\n\t\t\t\tlogFatal(\"Could not parse error key '\" + subKey + \"'.\", nfex);\n\t\t\t}\n\t\t} else if(\"option.log\".equals(key)) {\n\t\t\t//\t\t\tlogRequests = properties.getProperty(\"option.log\").equalsIgnoreCase(\"true\");\n\t\t}\n\t}\n\n\tprivate static void parseOptions(Properties properties) {\n\t\tEnumeration<Object> keys = properties.keys();\n\n\t\twhile (keys.hasMoreElements()) {\n\t\t\tString key = (String) keys.nextElement();\n\t\t\tif(key.startsWith(\"option.\")) {\n\t\t\t\tparseOption(properties, key);\n\t\t\t\tproperties.remove(key);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Serve the correctly routed file\n\t *\n\t * @param rootDir The root directory of the RouteMaster server\n\t * @param httpSession The session\n\t *\n\t * @return The response\n\t */\n\tpublic static Response route(File rootDir, IHTTPSession httpSession) {\n\t\tif(!initialised) {\n\t\t\tHttpUtils.notFoundResponse();\n\t\t}\n\n\t\tResponse routeInternalResponse = routeInternal(rootDir, httpSession);\n\t\tif(null != routeInternalResponse) {\n\t\t\treturn(routeInternalResponse);\n\t\t}\n\n\t\treturn(get500Response(rootDir, httpSession));\n\t}\n\n\tprivate static Response routeInternal(File rootDir, IHTTPSession httpSession) {\n\t\tif(null != router) {\n\t\t\t// try and find the route\n\t\t\tString uri = httpSession.getUri();\n\n\t\t\t// do we have a cached version of this?\n\t\t\tif(routerCache.containsKey(uri)) {\n\t\t\t\tResponse serve = routerCache.get(uri).serve(rootDir, httpSession);\n\t\t\t\tif(serve == null) {\n\t\t\t\t\treturn(get404Response(rootDir, httpSession));\n\t\t\t\t} else {\n\t\t\t\t\treturn(serve);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tStringTokenizer stringTokenizer = new StringTokenizer(uri, \"/\", false);\n\t\t\t\tRoutable routable = router.route(httpSession, stringTokenizer);\n\t\t\t\tif(null != routable) {\n\t\t\t\t\trouterCache.put(uri, routable);\n\t\t\t\t\tResponse serve = routable.serve(rootDir, httpSession);\n\t\t\t\t\tif(null != serve) {\n\t\t\t\t\t\treturn(serve);\n\t\t\t\t\t} else {\n\t\t\t\t\t\treturn(get404Response(rootDir, httpSession));\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// have a null route-able return 404 perhaps\n\t\t\t\t\treturn(get404Response(rootDir, httpSession));\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\treturn(get404Response(rootDir, httpSession));\n\t\t}\n\t}\n\n\tprivate static Response getErrorResponse(File rootDir, IHTTPSession httpSession, Status status, String message) {\n\t\tint requestStatus = status.getRequestStatus();\n\t\tString uri = errorPageCache.get(requestStatus);\n\t\tif(errorPageCache.containsKey(requestStatus)) {\n\t\t\tModifiableSession modifiedSession = new ModifiableSession(httpSession);\n\t\t\tmodifiedSession.setUri(uri);\n\t\t\t// if not valid - we have already tried this - and we are going to get a\n\t\t\t// stack overflow, so just drop through\n\t\t\tif(modifiedSession.isValidRequest()) {\n\t\t\t\tResponse response = route(rootDir, modifiedSession);\n\t\t\t\tresponse.setStatus(status);\n\t\t\t\tif(null != response) {\n\t\t\t\t\treturn(response);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn(HttpUtils.notFoundResponse(AsciiArt.ROUTEMASTER + \n\t\t\t\t\" \" + \n\t\t\t\tmessage + \n\t\t\t\t\";\\n\\n additionally, an over-ride \" + \n\t\t\t\tstatus.toString() + \n\t\t\t\t\" error page was not defined\\n\\n in the configuration file, key 'option.error.404'.\"));\n\t}\n\n\tpublic static Response get404Response(File rootDir, IHTTPSession httpSession) { return(getErrorResponse(rootDir, httpSession, Response.Status.NOT_FOUND, \"not found\")); }\n\tpublic static Response get500Response(File rootDir, IHTTPSession httpSession) { return(getErrorResponse(rootDir, httpSession, Response.Status.INTERNAL_ERROR, \"internal server error\")); }\n\n\t/**\n\t * Get the root Router\n\t *\n\t * @return The Router assigned to the root of the site\n\t */\n\tpublic static Router getRouter() { return(router); }\n\n\t/**\n\t * Get the cache of all of the Routables which contains a Map of the Routables\n\t * per path - which saves on going through the Router and determining the\n\t * Routable on every access\n\t *\n\t * @return The Routable cache\n\t */\n\tpublic static Map<String, Routable> getRouterCache() { return (routerCache); }\n\n\t/**\n\t * Get the index/welcome files that are registered.\n\t *\n\t * @return The index files\n\t */\n\tpublic static Set<String> getIndexFiles() { return indexFiles; }\n\n\t/**\n\t * Get the handler cache\n\t * \n\t * @return the handler cache\n\t */\n\tpublic static Map<String, Handler> getHandlerCache() { return (handlerCache); }\n\t\n\t/**\n\t * Get the set of modules that have been registered with the routemaster\n\t * \n\t * @return the set of modules that have been registered\n\t */\n\tpublic static Set<String> getModules() { return(modules); }\n}",
"public class HttpUtils {\n\n\tprivate static final Logger LOGGER = Logger.getLogger(HttpUtils.class.getName());\n\n\tpublic static String cleanUri(String uri) {\n\t\tif(null == uri) {\n\t\t\treturn(null);\n\t\t}\n\n\t\treturn(uri.replaceAll(\"/\\\\.\\\\./\", \"/\").replaceAll(\"//\", \"/\"));\n\t}\n\n\tprivate static Response defaultTextResponse(IStatus status) { return(newFixedLengthResponse(status, NanoHTTPD.MIME_PLAINTEXT, status.getDescription())); }\n\tprivate static Response defaultTextResponse(IStatus status, String content) { return(newFixedLengthResponse(status, NanoHTTPD.MIME_PLAINTEXT, content)); }\n\n\tpublic static Response okResponse() { return(defaultTextResponse(Response.Status.OK)); }\n\tpublic static Response okResponse(String content) { return(defaultTextResponse(Response.Status.OK, content)); }\n\tpublic static Response okResponse(String mimeType, String content) { return(newFixedLengthResponse(Response.Status.OK, mimeType, content)); }\n\tpublic static Response okResponse(String mimeType, InputStream content, long totalBytes) { return(newFixedLengthResponse(Response.Status.OK, mimeType, content, totalBytes)); }\n\n\tpublic static Response notFoundResponse() { return(defaultTextResponse(Response.Status.NOT_FOUND)); }\n\tpublic static Response notFoundResponse(String content) { return(defaultTextResponse(Response.Status.NOT_FOUND, content)); }\n\tpublic static Response notFoundResponse(String mimeType, String content) { return(newFixedLengthResponse(Response.Status.NOT_FOUND, mimeType, content)); }\n\tpublic static Response notFoundResponse(String mimeType, InputStream content, long totalBytes) { return(newFixedLengthResponse(Response.Status.NOT_FOUND, mimeType, content, totalBytes)); }\n\n\tpublic static Response rangeNotSatisfiableResponse() { return(defaultTextResponse(Response.Status.RANGE_NOT_SATISFIABLE)); }\n\tpublic static Response rangeNotSatisfiableResponse(String content) { return(defaultTextResponse(Response.Status.RANGE_NOT_SATISFIABLE, content)); }\n\tpublic static Response rangeNotSatisfiableResponse(String mimeType, String content) { return(newFixedLengthResponse(Response.Status.RANGE_NOT_SATISFIABLE, mimeType, content)); }\n\tpublic static Response rangeNotSatisfiableResponse(String mimeType, InputStream content, long totalBytes) { return(newFixedLengthResponse(Response.Status.RANGE_NOT_SATISFIABLE, mimeType, content, totalBytes)); }\n\n\tpublic static Response methodNotAllowedResponse() { return(defaultTextResponse(Response.Status.METHOD_NOT_ALLOWED)); }\n\tpublic static Response methodNotAllowedResponse(String content) { return(defaultTextResponse(Response.Status.METHOD_NOT_ALLOWED, content)); }\n\tpublic static Response methodNotAllowedResponse(String mimeType, String content) { return(newFixedLengthResponse(Response.Status.METHOD_NOT_ALLOWED, mimeType, content)); }\n\tpublic static Response methodNotAllowedResponse(String mimeType, InputStream content, long totalBytes) { return(newFixedLengthResponse(Response.Status.METHOD_NOT_ALLOWED, mimeType, content, totalBytes)); }\n\n\tpublic static Response internalServerErrorResponse() { return(defaultTextResponse(Response.Status.INTERNAL_ERROR)); }\n\tpublic static Response internalServerErrorResponse(String content) { return(defaultTextResponse(Response.Status.INTERNAL_ERROR, content)); }\n\tpublic static Response internalServerErrorResponse(String mimeType, String content) { return(newFixedLengthResponse(Response.Status.INTERNAL_ERROR, mimeType, content)); }\n\tpublic static Response internalServerErrorResponse(String mimeType, InputStream content, long totalBytes) { return(newFixedLengthResponse(Response.Status.INTERNAL_ERROR, mimeType, content, totalBytes)); }\n\n\tpublic static Response forbiddenResponse() { return(defaultTextResponse(Response.Status.FORBIDDEN)); }\n\tpublic static Response forbiddenResponse(String content) { return(defaultTextResponse(Response.Status.FORBIDDEN, content)); }\n\tpublic static Response forbiddenResponse(String mimeType, String content) { return(newFixedLengthResponse(Response.Status.FORBIDDEN, mimeType, content)); }\n\tpublic static Response forbiddenResponse(String mimeType, InputStream content, long totalBytes) { return(newFixedLengthResponse(Response.Status.FORBIDDEN, mimeType, content, totalBytes)); }\n\n\tpublic static Response badRequestResponse() { return(defaultTextResponse(Response.Status.BAD_REQUEST)); }\n\tpublic static Response badRequestResponse(String content) { return(defaultTextResponse(Response.Status.BAD_REQUEST, content)); }\n\tpublic static Response badRequestResponse(String mimeType, String content) { return(newFixedLengthResponse(Response.Status.BAD_REQUEST, mimeType, content)); }\n\tpublic static Response badRequestResponse(String mimeType, InputStream content, long totalBytes) { return(newFixedLengthResponse(Response.Status.BAD_REQUEST, mimeType, content, totalBytes)); }\n\n\tpublic static Response notModifiedResponse() { return(defaultTextResponse(Response.Status.NOT_MODIFIED)); }\n\tpublic static Response notModifiedResponse(String content) { return(defaultTextResponse(Response.Status.NOT_MODIFIED, content)); }\n\tpublic static Response notModifiedResponse(String mimeType, String content) { return(newFixedLengthResponse(Response.Status.NOT_MODIFIED, mimeType, content)); }\n\tpublic static Response notModifiedResponse(String mimeType, InputStream content, long totalBytes) { return(newFixedLengthResponse(Response.Status.NOT_MODIFIED, mimeType, content, totalBytes)); }\n\n\tpublic static Response partialContentResponse() { return(defaultTextResponse(Response.Status.PARTIAL_CONTENT)); }\n\tpublic static Response partialContentResponse(String content) { return(defaultTextResponse(Response.Status.PARTIAL_CONTENT, content)); }\n\tpublic static Response partialContentResponse(String mimeType, String content) { return(newFixedLengthResponse(Response.Status.PARTIAL_CONTENT, mimeType, content)); }\n\tpublic static Response partialContentResponse(String mimeType, InputStream content, long totalBytes) { return(newFixedLengthResponse(Response.Status.PARTIAL_CONTENT, mimeType, content, totalBytes)); }\n\n\tpublic static Response redirectResponse(String uri) { return(redirectResponse(uri, \"<html><body>Redirected: <a href=\\\"\" + uri + \"\\\">\" + uri + \"</a></body></html>\")); }\n\tpublic static Response redirectResponse(String uri, String message) {\n\t\tResponse res = newFixedLengthResponse(Response.Status.REDIRECT, NanoHTTPD.MIME_HTML, message);\n\t\tres.addHeader(\"Location\", uri);\n\t\treturn(res);\n\t}\n\n\tpublic static Response newFixedLengthResponse(IStatus status, String mimeType, InputStream data, long totalBytes) {\n\t\treturn new Response(status, mimeType, data, totalBytes);\n\t}\n\n\t/**\n\t * Create a text response with known length.\n\t * \n\t * @param status the HTTP status\n\t * @param mimeType the mime type of the response\n\t * @param response the response message \n\t * \n\t * @return The fixed length response object\n\t */\n\tpublic static Response newFixedLengthResponse(IStatus status, String mimeType, String response) {\n\t\tif (response == null) {\n\t\t\treturn newFixedLengthResponse(status, mimeType, new ByteArrayInputStream(new byte[0]), 0);\n\t\t} else {\n\t\t\tbyte[] bytes;\n\t\t\ttry {\n\t\t\t\tbytes = response.getBytes(\"UTF-8\");\n\t\t\t} catch (UnsupportedEncodingException ueex) {\n\t\t\t\tLOGGER.log(Level.SEVERE, \"Encoding problem, responding nothing\", ueex);\n\t\t\t\tbytes = new byte[0];\n\t\t\t}\n\t\t\treturn newFixedLengthResponse(status, mimeType, new ByteArrayInputStream(bytes), bytes.length);\n\t\t}\n\t}\n\n\tpublic static String getMimeType(String uri) {\n\t\tint lastIndexOf = uri.lastIndexOf(\".\");\n\t\tString extension = uri.substring(lastIndexOf + 1);\n\n\t\tString mimeType = NanoHTTPD.MIME_HTML;\n\n\t\tif(MimeTypeMapper.getMimeTypes().containsKey(extension)) {\n\t\t\tmimeType = MimeTypeMapper.getMimeTypes().get(extension);\n\t\t}\n\t\treturn(mimeType);\n\t}\n}",
"public interface IHTTPSession {\n\n\tvoid execute() throws IOException;\n\n\tCookieHandler getCookies();\n\n\tMap<String, String> getHeaders();\n\n\tInputStream getInputStream();\n\n\tMethod getMethod();\n\n\t/**\n\t * This method will only return the first value for a given parameter.\n\t * You will want to use getParameters if you expect multiple values for\n\t * a given key.\n\t * \n\t * @deprecated use {@link #getParameters()} instead.\n\t */\n\t@Deprecated\n\tMap<String, String> getParms();\n\n\tMap<String, List<String>> getParameters();\n\n\tString getQueryParameterString();\n\n\t/**\n\t * @return the path part of the URL.\n\t */\n\tString getUri();\n\n\t/**\n\t * Adds the files in the request body to the files map.\n\t * \n\t * @param files\n\t * map to modify\n\t */\n\tvoid parseBody(Map<String, String> files) throws IOException, ResponseException;\n\n\t/**\n\t * Get the remote ip address of the requester.\n\t * \n\t * @return the IP address.\n\t */\n\tString getRemoteIpAddress();\n\n\t/**\n\t * Get the remote hostname of the requester.\n\t * \n\t * @return the hostname.\n\t */\n\tString getRemoteHostName();\n}",
"public static class Response implements Closeable {\n\n\tpublic interface IStatus {\n\n\t\tString getDescription();\n\n\t\tint getRequestStatus();\n\t}\n\n\t/**\n\t * Some HTTP response status codes\n\t */\n\tpublic enum Status implements IStatus {\n\t\tSWITCH_PROTOCOL(101, \"Switching Protocols\"),\n\n\t\tOK(200, \"OK\"),\n\t\tCREATED(201, \"Created\"),\n\t\tACCEPTED(202, \"Accepted\"),\n\t\tNO_CONTENT(204, \"No Content\"),\n\t\tPARTIAL_CONTENT(206, \"Partial Content\"),\n\t\tMULTI_STATUS(207, \"Multi-Status\"),\n\n\t\tREDIRECT(301, \"Moved Permanently\"),\n\t\t/**\n\t\t * Many user agents mishandle 302 in ways that violate the RFC1945\n\t\t * spec (i.e., redirect a POST to a GET). 303 and 307 were added in\n\t\t * RFC2616 to address this. You should prefer 303 and 307 unless the\n\t\t * calling user agent does not support 303 and 307 functionality\n\t\t */\n\t\t@Deprecated\n\t\tFOUND(302, \"Found\"),\n\t\tREDIRECT_SEE_OTHER(303, \"See Other\"),\n\t\tNOT_MODIFIED(304, \"Not Modified\"),\n\t\tTEMPORARY_REDIRECT(307, \"Temporary Redirect\"),\n\n\t\tBAD_REQUEST(400, \"Bad Request\"),\n\t\tUNAUTHORIZED(401, \"Unauthorized\"),\n\t\tFORBIDDEN(403, \"Forbidden\"),\n\t\tNOT_FOUND(404, \"Not Found\"),\n\t\tMETHOD_NOT_ALLOWED(405, \"Method Not Allowed\"),\n\t\tNOT_ACCEPTABLE(406, \"Not Acceptable\"),\n\t\tREQUEST_TIMEOUT(408, \"Request Timeout\"),\n\t\tCONFLICT(409, \"Conflict\"),\n\t\tGONE(410, \"Gone\"),\n\t\tLENGTH_REQUIRED(411, \"Length Required\"),\n\t\tPRECONDITION_FAILED(412, \"Precondition Failed\"),\n\t\tPAYLOAD_TOO_LARGE(413, \"Payload Too Large\"),\n\t\tUNSUPPORTED_MEDIA_TYPE(415, \"Unsupported Media Type\"),\n\t\tRANGE_NOT_SATISFIABLE(416, \"Requested Range Not Satisfiable\"),\n\t\tEXPECTATION_FAILED(417, \"Expectation Failed\"),\n\t\tTOO_MANY_REQUESTS(429, \"Too Many Requests\"),\n\n\t\tINTERNAL_ERROR(500, \"Internal Server Error\"),\n\t\tNOT_IMPLEMENTED(501, \"Not Implemented\"),\n\t\tSERVICE_UNAVAILABLE(503, \"Service Unavailable\"),\n\t\tUNSUPPORTED_HTTP_VERSION(505, \"HTTP Version Not Supported\");\n\n\t\tprivate final int requestStatus;\n\n\t\tprivate final String description;\n\n\t\tStatus(int requestStatus, String description) {\n\t\t\tthis.requestStatus = requestStatus;\n\t\t\tthis.description = description;\n\t\t}\n\n\t\tpublic static Status lookup(int requestStatus) {\n\t\t\tfor (Status status : Status.values()) {\n\t\t\t\tif (status.getRequestStatus() == requestStatus) {\n\t\t\t\t\treturn status;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn null;\n\t\t}\n\n\t\t@Override\n\t\tpublic String getDescription() {\n\t\t\treturn \"\" + this.requestStatus + \" \" + this.description;\n\t\t}\n\n\t\t@Override\n\t\tpublic int getRequestStatus() {\n\t\t\treturn this.requestStatus;\n\t\t}\n\n\t}\n\n\t/**\n\t * Output stream that will automatically send every write to the wrapped\n\t * OutputStream according to chunked transfer:\n\t * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.6.1\n\t */\n\tprivate static class ChunkedOutputStream extends FilterOutputStream {\n\n\t\tpublic ChunkedOutputStream(OutputStream out) {\n\t\t\tsuper(out);\n\t\t}\n\n\t\t@Override\n\t\tpublic void write(int b) throws IOException {\n\t\t\tbyte[] data = {\n\t\t\t\t\t(byte) b\n\t\t\t};\n\t\t\twrite(data, 0, 1);\n\t\t}\n\n\t\t@Override\n\t\tpublic void write(byte[] b) throws IOException {\n\t\t\twrite(b, 0, b.length);\n\t\t}\n\n\t\t@Override\n\t\tpublic void write(byte[] b, int off, int len) throws IOException {\n\t\t\tif (len == 0)\n\t\t\t\treturn;\n\t\t\tout.write(String.format(\"%x\\r\\n\", len).getBytes());\n\t\t\tout.write(b, off, len);\n\t\t\tout.write(\"\\r\\n\".getBytes());\n\t\t}\n\n\t\tpublic void finish() throws IOException {\n\t\t\tout.write(\"0\\r\\n\\r\\n\".getBytes());\n\t\t}\n\n\t}\n\n\t/**\n\t * HTTP status code after processing, e.g. \"200 OK\", Status.OK\n\t */\n\tprivate IStatus status;\n\n\t/**\n\t * MIME type of content, e.g. \"text/html\"\n\t */\n\tprivate String mimeType;\n\n\t/**\n\t * Data of the response, may be null.\n\t */\n\tprivate InputStream data;\n\n\tprivate long contentLength;\n\n\t/**\n\t * Headers for the HTTP response. Use addHeader() to add lines. the\n\t * lowercase map is automatically kept up to date.\n\t */\n\t@SuppressWarnings(\"serial\")\n\tprivate final Map<String, String> header = new HashMap<String, String>() {\n\n\t\tpublic String put(String key, String value) {\n\t\t\tlowerCaseHeader.put(key == null ? key : key.toLowerCase(), value);\n\t\t\treturn super.put(key, value);\n\t\t};\n\t};\n\n\t/**\n\t * copy of the header map with all the keys lowercase for faster\n\t * searching.\n\t */\n\tprivate final Map<String, String> lowerCaseHeader = new HashMap<String, String>();\n\n\t/**\n\t * The request method that spawned this response.\n\t */\n\tprivate Method requestMethod;\n\n\t/**\n\t * Use chunkedTransfer\n\t */\n\tprivate boolean chunkedTransfer;\n\n\tprivate boolean encodeAsGzip;\n\n\tprivate boolean keepAlive;\n\n\t/**\n\t * Creates a fixed length response if totalBytes>=0, otherwise chunked.\n\t */\n\tprotected Response(IStatus status, String mimeType, InputStream data, long totalBytes) {\n\t\tthis.status = status;\n\t\tthis.mimeType = mimeType;\n\t\tif (data == null) {\n\t\t\tthis.data = new ByteArrayInputStream(new byte[0]);\n\t\t\tthis.contentLength = 0L;\n\t\t} else {\n\t\t\tthis.data = data;\n\t\t\tthis.contentLength = totalBytes;\n\t\t}\n\t\tthis.chunkedTransfer = this.contentLength < 0;\n\t\tkeepAlive = true;\n\t}\n\n\t@Override\n\tpublic void close() throws IOException {\n\t\tif (this.data != null) {\n\t\t\tthis.data.close();\n\t\t}\n\t}\n\n\t/**\n\t * Adds given line to the header.\n\t */\n\tpublic void addHeader(String name, String value) {\n\t\tthis.header.put(name, value);\n\t}\n\n\t/**\n\t * Indicate to close the connection after the Response has been sent.\n\t * \n\t * @param close\n\t * {@code true} to hint connection closing, {@code false} to\n\t * let connection be closed by client.\n\t */\n\tpublic void closeConnection(boolean close) {\n\t\tif (close)\n\t\t\tthis.header.put(\"connection\", \"close\");\n\t\telse\n\t\t\tthis.header.remove(\"connection\");\n\t}\n\n\t/**\n\t * @return {@code true} if connection is to be closed after this\n\t * Response has been sent.\n\t */\n\tpublic boolean isCloseConnection() {\n\t\treturn \"close\".equals(getHeader(\"connection\"));\n\t}\n\n\tpublic InputStream getData() {\n\t\treturn this.data;\n\t}\n\n\tpublic String getHeader(String name) {\n\t\treturn this.lowerCaseHeader.get(name.toLowerCase());\n\t}\n\n\tpublic String getMimeType() {\n\t\treturn this.mimeType;\n\t}\n\n\tpublic Method getRequestMethod() {\n\t\treturn this.requestMethod;\n\t}\n\n\tpublic IStatus getStatus() {\n\t\treturn this.status;\n\t}\n\n\tpublic void setGzipEncoding(boolean encodeAsGzip) {\n\t\tthis.encodeAsGzip = encodeAsGzip;\n\t}\n\n\tpublic void setKeepAlive(boolean useKeepAlive) {\n\t\tthis.keepAlive = useKeepAlive;\n\t}\n\n\t/**\n\t * Sends given response to the socket.\n\t */\n\tprotected void send(OutputStream outputStream) {\n\t\tSimpleDateFormat gmtFrmt = new SimpleDateFormat(\"E, d MMM yyyy HH:mm:ss 'GMT'\", Locale.US);\n\t\tgmtFrmt.setTimeZone(TimeZone.getTimeZone(\"GMT\"));\n\n\t\ttry {\n\t\t\tif (this.status == null) {\n\t\t\t\tthrow new Error(\"sendResponse(): Status can't be null.\");\n\t\t\t}\n\t\t\tPrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream, new ContentType(this.mimeType).getEncoding())), false);\n\t\t\tpw.append(\"HTTP/1.1 \").append(this.status.getDescription()).append(\" \\r\\n\");\n\t\t\tif (this.mimeType != null) {\n\t\t\t\tprintHeader(pw, \"Content-Type\", this.mimeType);\n\t\t\t}\n\t\t\tif (getHeader(\"date\") == null) {\n\t\t\t\tprintHeader(pw, \"Date\", gmtFrmt.format(new Date()));\n\t\t\t}\n\t\t\tfor (Entry<String, String> entry : this.header.entrySet()) {\n\t\t\t\tprintHeader(pw, entry.getKey(), entry.getValue());\n\t\t\t}\n\t\t\tif (getHeader(\"connection\") == null) {\n\t\t\t\tprintHeader(pw, \"Connection\", (this.keepAlive ? \"keep-alive\" : \"close\"));\n\t\t\t}\n\t\t\tif (getHeader(\"content-length\") != null) {\n\t\t\t\tencodeAsGzip = false;\n\t\t\t}\n\t\t\tif (encodeAsGzip) {\n\t\t\t\tprintHeader(pw, \"Content-Encoding\", \"gzip\");\n\t\t\t\tsetChunkedTransfer(true);\n\t\t\t}\n\t\t\tlong pending = this.data != null ? this.contentLength : 0;\n\t\t\tif (this.requestMethod != Method.HEAD && this.chunkedTransfer) {\n\t\t\t\tprintHeader(pw, \"Transfer-Encoding\", \"chunked\");\n\t\t\t} else if (!encodeAsGzip) {\n\t\t\t\tpending = sendContentLengthHeaderIfNotAlreadyPresent(pw, pending);\n\t\t\t}\n\t\t\tpw.append(\"\\r\\n\");\n\t\t\tpw.flush();\n\t\t\tsendBodyWithCorrectTransferAndEncoding(outputStream, pending);\n\t\t\toutputStream.flush();\n\t\t\tsafeClose(this.data);\n\t\t} catch (IOException ioe) {\n\t\t\tNanoHTTPD.LOG.log(Level.SEVERE, \"Could not send response to the client\", ioe);\n\t\t}\n\t}\n\n\t@SuppressWarnings(\"static-method\")\n\tprotected void printHeader(PrintWriter pw, String key, String value) {\n\t\tpw.append(key).append(\": \").append(value).append(\"\\r\\n\");\n\t}\n\n\tprotected long sendContentLengthHeaderIfNotAlreadyPresent(PrintWriter pw, long defaultSize) {\n\t\tString contentLengthString = getHeader(\"content-length\");\n\t\tlong size = defaultSize;\n\t\tif (contentLengthString != null) {\n\t\t\ttry {\n\t\t\t\tsize = Long.parseLong(contentLengthString);\n\t\t\t} catch (NumberFormatException ex) {\n\t\t\t\tLOG.severe(\"content-length was no number \" + contentLengthString);\n\t\t\t}\n\t\t}\n\t\tpw.print(\"Content-Length: \" + size + \"\\r\\n\");\n\t\treturn size;\n\t}\n\n\tprivate void sendBodyWithCorrectTransferAndEncoding(OutputStream outputStream, long pending) throws IOException {\n\t\tif (this.requestMethod != Method.HEAD && this.chunkedTransfer) {\n\t\t\tChunkedOutputStream chunkedOutputStream = new ChunkedOutputStream(outputStream);\n\t\t\tsendBodyWithCorrectEncoding(chunkedOutputStream, -1);\n\t\t\tchunkedOutputStream.finish();\n\t\t} else {\n\t\t\tsendBodyWithCorrectEncoding(outputStream, pending);\n\t\t}\n\t}\n\n\tprivate void sendBodyWithCorrectEncoding(OutputStream outputStream, long pending) throws IOException {\n\t\tif (encodeAsGzip) {\n\t\t\tGZIPOutputStream gzipOutputStream = new GZIPOutputStream(outputStream);\n\t\t\tsendBody(gzipOutputStream, -1);\n\t\t\tgzipOutputStream.finish();\n\t\t} else {\n\t\t\tsendBody(outputStream, pending);\n\t\t}\n\t}\n\n\t/**\n\t * Sends the body to the specified OutputStream. The pending parameter\n\t * limits the maximum amounts of bytes sent unless it is -1, in which\n\t * case everything is sent.\n\t * \n\t * @param outputStream\n\t * the OutputStream to send data to\n\t * @param pending\n\t * -1 to send everything, otherwise sets a max limit to the\n\t * number of bytes sent\n\t * @throws IOException\n\t * if something goes wrong while sending the data.\n\t */\n\tprivate void sendBody(OutputStream outputStream, long pending) throws IOException {\n\t\tlong BUFFER_SIZE = 16 * 1024;\n\t\tbyte[] buff = new byte[(int) BUFFER_SIZE];\n\t\tboolean sendEverything = pending == -1;\n\t\twhile (pending > 0 || sendEverything) {\n\t\t\tlong bytesToRead = sendEverything ? BUFFER_SIZE : Math.min(pending, BUFFER_SIZE);\n\t\t\tint read = this.data.read(buff, 0, (int) bytesToRead);\n\t\t\tif (read <= 0) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\toutputStream.write(buff, 0, read);\n\t\t\tif (!sendEverything) {\n\t\t\t\tpending -= read;\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic void setChunkedTransfer(boolean chunkedTransfer) {\n\t\tthis.chunkedTransfer = chunkedTransfer;\n\t}\n\n\tpublic void setData(InputStream data) {\n\t\tthis.data = data;\n\t}\n\n\tpublic void setMimeType(String mimeType) {\n\t\tthis.mimeType = mimeType;\n\t}\n\n\tpublic void setRequestMethod(Method requestMethod) {\n\t\tthis.requestMethod = requestMethod;\n\t}\n\n\tpublic void setStatus(IStatus status) {\n\t\tthis.status = status;\n\t}\n}"
] | import java.io.File;
import java.util.Iterator;
import java.util.Map;
import synapticloop.nanohttpd.handler.Handler;
import synapticloop.nanohttpd.router.Routable;
import synapticloop.nanohttpd.router.RouteMaster;
import synapticloop.nanohttpd.utils.HttpUtils;
import fi.iki.elonen.NanoHTTPD.IHTTPSession;
import fi.iki.elonen.NanoHTTPD.Response; | package synapticloop.nanohttpd.example.servant;
/*
* Copyright (c) 2013-2020 synapticloop.
*
* All rights reserved.
*
* This source code and any derived binaries are covered by the terms and
* conditions of the Licence agreement ("the Licence"). You may not use this
* source code or any derived binaries except in compliance with the Licence.
* A copy of the Licence is available in the file named LICENCE shipped with
* this source code or binaries.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* Licence for the specific language governing permissions and limitations
* under the Licence.
*/
public class HandlerServant extends Routable {
public HandlerServant(String routeContext) {
super(routeContext);
}
@Override | public Response serve(File rootDir, IHTTPSession httpSession) { | 4 |
samtingleff/jchronic | src/test/java/com/mdimension/jchronic/RepeaterFortnightTest.java | [
"public class RepeaterFortnight extends RepeaterUnit {\n public static final int FORTNIGHT_SECONDS = 1209600; // (14 * 24 * 60 * 60)\n\n private Calendar _currentFortnightStart;\n\n @Override\n protected Span _nextSpan(PointerType pointer) {\n if (_currentFortnightStart == null) {\n if (pointer == PointerType.FUTURE) {\n RepeaterDayName sundayRepeater = new RepeaterDayName(RepeaterDayName.DayName.SUNDAY);\n sundayRepeater.setStart(getNow());\n Span nextSundaySpan = sundayRepeater.nextSpan(PointerType.FUTURE);\n _currentFortnightStart = nextSundaySpan.getBeginCalendar();\n }\n else if (pointer == PointerType.PAST) {\n RepeaterDayName sundayRepeater = new RepeaterDayName(RepeaterDayName.DayName.SUNDAY);\n sundayRepeater.setStart(Time.cloneAndAdd(getNow(), Calendar.SECOND, RepeaterDay.DAY_SECONDS));\n sundayRepeater.nextSpan(PointerType.PAST);\n sundayRepeater.nextSpan(PointerType.PAST);\n Span lastSundaySpan = sundayRepeater.nextSpan(PointerType.PAST);\n _currentFortnightStart = lastSundaySpan.getBeginCalendar();\n }\n else {\n throw new IllegalArgumentException(\"Unable to handle pointer \" + pointer + \".\");\n }\n }\n else {\n int direction = (pointer == PointerType.FUTURE) ? 1 : -1;\n _currentFortnightStart.add(Calendar.SECOND, direction * RepeaterFortnight.FORTNIGHT_SECONDS);\n }\n\n return new Span(_currentFortnightStart, Calendar.SECOND, RepeaterFortnight.FORTNIGHT_SECONDS);\n }\n\n @Override\n protected Span _thisSpan(PointerType pointer) {\n if (pointer == null) {\n pointer = PointerType.FUTURE;\n }\n\n Span span;\n if (pointer == PointerType.FUTURE) {\n Calendar thisFortnightStart = Time.cloneAndAdd(Time.ymdh(getNow()), Calendar.SECOND, RepeaterHour.HOUR_SECONDS);\n RepeaterDayName sundayRepeater = new RepeaterDayName(RepeaterDayName.DayName.SUNDAY);\n sundayRepeater.setStart(getNow());\n sundayRepeater.thisSpan(PointerType.FUTURE);\n Span thisSundaySpan = sundayRepeater.thisSpan(PointerType.FUTURE);\n Calendar thisFortnightEnd = thisSundaySpan.getBeginCalendar();\n span = new Span(thisFortnightStart, thisFortnightEnd);\n }\n else if (pointer == PointerType.PAST) {\n Calendar thisFortnightEnd = Time.ymdh(getNow());\n RepeaterDayName sundayRepeater = new RepeaterDayName(RepeaterDayName.DayName.SUNDAY);\n sundayRepeater.setStart(getNow());\n Span lastSundaySpan = sundayRepeater.nextSpan(PointerType.PAST);\n Calendar thisFortnightStart = lastSundaySpan.getBeginCalendar();\n span = new Span(thisFortnightStart, thisFortnightEnd);\n }\n else {\n throw new IllegalArgumentException(\"Unable to handle pointer \" + pointer + \".\");\n }\n\n return span;\n }\n\n @Override\n public Span getOffset(Span span, int amount, PointerType pointer) {\n int direction = (pointer == PointerType.FUTURE) ? 1 : -1;\n Span offsetSpan = span.add(direction * amount * RepeaterFortnight.FORTNIGHT_SECONDS);\n return offsetSpan;\n }\n\n @Override\n public int getWidth() {\n return RepeaterFortnight.FORTNIGHT_SECONDS;\n }\n\n @Override\n public String toString() {\n return super.toString() + \"-fortnight\";\n }\n\n}",
"public class RepeaterWeek extends RepeaterUnit {\n public static final int WEEK_SECONDS = 604800; // (7 * 24 * 60 * 60);\n public static final int WEEK_DAYS = 7;\n\n private Calendar _currentWeekStart;\n\n @Override\n protected Span _nextSpan(PointerType pointer) {\n if (_currentWeekStart == null) {\n if (pointer == PointerType.FUTURE) {\n RepeaterDayName sundayRepeater = new RepeaterDayName(RepeaterDayName.DayName.SUNDAY);\n sundayRepeater.setStart((Calendar) getNow().clone());\n Span nextSundaySpan = sundayRepeater.nextSpan(Pointer.PointerType.FUTURE);\n _currentWeekStart = nextSundaySpan.getBeginCalendar();\n }\n else if (pointer == PointerType.PAST) {\n RepeaterDayName sundayRepeater = new RepeaterDayName(RepeaterDayName.DayName.SUNDAY);\n sundayRepeater.setStart(Time.cloneAndAdd(getNow(), Calendar.DAY_OF_MONTH, 1));\n sundayRepeater.nextSpan(Pointer.PointerType.PAST);\n Span lastSundaySpan = sundayRepeater.nextSpan(Pointer.PointerType.PAST);\n _currentWeekStart = lastSundaySpan.getBeginCalendar();\n }\n else {\n throw new IllegalArgumentException(\"Unable to handle pointer \" + pointer + \".\");\n }\n }\n else {\n int direction = (pointer == Pointer.PointerType.FUTURE) ? 1 : -1;\n _currentWeekStart.add(Calendar.DAY_OF_MONTH, RepeaterWeek.WEEK_DAYS * direction);\n }\n\n return new Span(_currentWeekStart, Calendar.DAY_OF_MONTH, RepeaterWeek.WEEK_DAYS);\n }\n\n @Override\n protected Span _thisSpan(PointerType pointer) {\n Span thisWeekSpan;\n Calendar thisWeekStart;\n Calendar thisWeekEnd;\n if (pointer == PointerType.FUTURE) {\n thisWeekStart = Time.cloneAndAdd(Time.ymdh(getNow()), Calendar.HOUR, 1);\n RepeaterDayName sundayRepeater = new RepeaterDayName(RepeaterDayName.DayName.SUNDAY);\n sundayRepeater.setStart((Calendar) getNow().clone());\n Span thisSundaySpan = sundayRepeater.thisSpan(Pointer.PointerType.FUTURE);\n thisWeekEnd = thisSundaySpan.getBeginCalendar();\n thisWeekSpan = new Span(thisWeekStart, thisWeekEnd);\n }\n else if (pointer == PointerType.PAST) {\n thisWeekEnd = Time.ymdh(getNow());\n RepeaterDayName sundayRepeater = new RepeaterDayName(RepeaterDayName.DayName.SUNDAY);\n sundayRepeater.setStart((Calendar) getNow().clone());\n Span lastSundaySpan = sundayRepeater.nextSpan(Pointer.PointerType.PAST);\n thisWeekStart = lastSundaySpan.getBeginCalendar();\n thisWeekSpan = new Span(thisWeekStart, thisWeekEnd);\n }\n else if (pointer == PointerType.NONE) {\n RepeaterDayName sundayRepeater = new RepeaterDayName(RepeaterDayName.DayName.SUNDAY);\n sundayRepeater.setStart((Calendar) getNow().clone());\n Span lastSundaySpan = sundayRepeater.nextSpan(Pointer.PointerType.PAST);\n thisWeekStart = lastSundaySpan.getBeginCalendar();\n thisWeekEnd = Time.cloneAndAdd(thisWeekStart, Calendar.DAY_OF_MONTH, RepeaterWeek.WEEK_DAYS);\n thisWeekSpan = new Span(thisWeekStart, thisWeekEnd);\n }\n else {\n throw new IllegalArgumentException(\"Unable to handle pointer \" + pointer + \".\");\n }\n return thisWeekSpan;\n }\n\n @Override\n public Span getOffset(Span span, int amount, Pointer.PointerType pointer) {\n int direction = (pointer == Pointer.PointerType.FUTURE) ? 1 : -1;\n // WARN: Does not use Calendar\n return span.add(direction * amount * RepeaterWeek.WEEK_SECONDS);\n }\n\n @Override\n public int getWidth() {\n // WARN: Does not use Calendar\n return RepeaterWeek.WEEK_SECONDS;\n }\n\n @Override\n public String toString() {\n return super.toString() + \"-week\";\n }\n}",
"public class Pointer extends Tag<Pointer.PointerType> {\n private static final Pattern IN_PATTERN = Pattern.compile(\"\\\\bin\\\\b\");\n private static final Pattern FUTURE_PATTERN = Pattern.compile(\"\\\\bfuture\\\\b\");\n private static final Pattern PAST_PATTERN = Pattern.compile(\"\\\\bpast\\\\b\");\n\n public enum PointerType {\n PAST, FUTURE, NONE\n }\n \n public Pointer(Pointer.PointerType type) {\n super(type);\n }\n\n public static List<Token> scan(List<Token> tokens, Options options) {\n for (Token token : tokens) {\n Pointer t = Pointer.scanForAll(token, options);\n if (t != null) {\n token.tag(t);\n }\n }\n return tokens;\n }\n\n public static Pointer scanForAll(Token token, Options options) {\n Map<Pattern, Pointer.PointerType> scanner = new HashMap<Pattern, Pointer.PointerType>();\n scanner.put(Pointer.PAST_PATTERN, Pointer.PointerType.PAST);\n scanner.put(Pointer.FUTURE_PATTERN, Pointer.PointerType.FUTURE);\n scanner.put(Pointer.IN_PATTERN, Pointer.PointerType.FUTURE);\n for (Pattern scannerItem : scanner.keySet()) {\n if (scannerItem.matcher(token.getWord()).matches()) { \n return new Pointer(scanner.get(scannerItem));\n }\n }\n return null;\n }\n\n @Override\n public String toString() {\n return \"pointer-\" + getType();\n }\n}",
"public class Span extends Range {\n\n public Span(Calendar begin, int field, long amount) {\n this(begin, Time.cloneAndAdd(begin, field, amount));\n }\n\n public Span(Calendar begin, Calendar end) {\n this(begin.getTimeInMillis() / 1000, end.getTimeInMillis() / 1000);\n }\n\n public Span(long begin, long end) {\n super(begin, end);\n }\n\n public Calendar getBeginCalendar() {\n Calendar cal = Calendar.getInstance();\n cal.setTimeInMillis(getBegin() * 1000);\n return cal;\n }\n\n public Calendar getEndCalendar() {\n Calendar cal = Calendar.getInstance();\n cal.setTimeInMillis(getEnd() * 1000);\n return cal;\n }\n\n /**\n * Add a number of seconds to this span, returning the \n * resulting Span\n */\n public Span add(long seconds) {\n return new Span(getBegin() + seconds, getEnd() + seconds);\n }\n\n /**\n * Subtract a number of seconds to this span, returning the \n * resulting Span\n */\n public Span subtract(long seconds) {\n return add(-seconds);\n }\n\n @Override\n public String toString() {\n return \"(\" + DateFormat.getDateTimeInstance().format(getBeginCalendar().getTime()) + \"..\" + DateFormat.getDateTimeInstance().format(getEndCalendar().getTime()) + \")\";\n }\n}",
"public class Time {\n public static Calendar construct(int year, int month) {\n if (year <= 1900) {\n throw new IllegalArgumentException(\"Illegal year '\" + year + \"'\");\n }\n Calendar cal = Calendar.getInstance();\n cal.clear();\n cal.set(Calendar.YEAR, year);\n cal.set(Calendar.MONTH, month - 1);\n return cal;\n }\n\n public static Calendar construct(int year, int month, int day) {\n Calendar cal = Time.construct(year, month);\n cal.set(Calendar.DAY_OF_MONTH, day);\n return cal;\n }\n\n public static Calendar construct(int year, int month, int day, int hour) {\n Calendar cal = Time.construct(year, month, day);\n cal.set(Calendar.HOUR_OF_DAY, hour);\n return cal;\n }\n\n public static Calendar construct(int year, int month, int day, int hour, int minute) {\n Calendar cal = Time.construct(year, month, day, hour);\n cal.set(Calendar.MINUTE, minute);\n return cal;\n }\n\n public static Calendar construct(int year, int month, int day, int hour, int minute, int second) {\n Calendar cal = Time.construct(year, month, day, hour, minute);\n cal.set(Calendar.SECOND, second);\n return cal;\n }\n\n public static Calendar construct(int year, int month, int day, int hour, int minute, int second, int millisecond) {\n Calendar cal = Time.construct(year, month, day, hour, minute, second);\n cal.set(Calendar.MILLISECOND, millisecond);\n return cal;\n }\n\n public static Calendar y(Calendar basis) {\n Calendar clone = Calendar.getInstance();\n clone.clear();\n clone.set(Calendar.YEAR, basis.get(Calendar.YEAR));\n return clone;\n }\n\n public static Calendar yJan1(Calendar basis) {\n Calendar clone = Time.y(basis, 1, 1);\n return clone;\n }\n\n public static Calendar y(Calendar basis, int month) {\n Calendar clone = Time.y(basis);\n clone.set(Calendar.MONTH, month - 1);\n return clone;\n }\n\n public static Calendar y(Calendar basis, int month, int day) {\n Calendar clone = Time.y(basis, month);\n clone.set(Calendar.DAY_OF_MONTH, day);\n return clone;\n }\n\n public static Calendar ym(Calendar basis) {\n Calendar clone = Time.y(basis);\n clone.set(Calendar.MONTH, basis.get(Calendar.MONTH));\n return clone;\n }\n\n public static Calendar ymd(Calendar basis) {\n Calendar clone = Time.ym(basis);\n clone.set(Calendar.DAY_OF_MONTH, basis.get(Calendar.DAY_OF_MONTH));\n return clone;\n }\n\n public static Calendar ymdh(Calendar basis) {\n Calendar clone = Time.ymd(basis);\n clone.set(Calendar.HOUR_OF_DAY, basis.get(Calendar.HOUR_OF_DAY));\n return clone;\n }\n\n public static Calendar ymdhm(Calendar basis) {\n Calendar clone = Time.ymdh(basis);\n clone.set(Calendar.MINUTE, basis.get(Calendar.MINUTE));\n return clone;\n }\n\n public static Calendar cloneAndAdd(Calendar basis, int field, long amount) {\n Calendar next = (Calendar) basis.clone();\n next.add(field, (int) amount);\n return next;\n }\n}"
] | import java.util.Calendar;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import com.mdimension.jchronic.repeaters.RepeaterFortnight;
import com.mdimension.jchronic.repeaters.RepeaterWeek;
import com.mdimension.jchronic.tags.Pointer;
import com.mdimension.jchronic.utils.Span;
import com.mdimension.jchronic.utils.Time; | package com.mdimension.jchronic;
@RunWith(JUnit4.class)
public class RepeaterFortnightTest {
private Calendar _now;
@Before
public void setUp() throws Exception {
_now = Time.construct(2006, 8, 16, 14, 0, 0, 0);
}
@Test
public void testNextFuture() {
RepeaterFortnight fortnights = new RepeaterFortnight();
fortnights.setStart(_now);
| Span nextFortnight = fortnights.nextSpan(Pointer.PointerType.FUTURE); | 3 |
jentrata/jentrata | ebms-msh-jdbc-store/src/main/java/org/jentrata/ebms/messaging/internal/JDBCMessageStore.java | [
"public class EbmsConstants {\n\n public static final String JENTRATA_VERSION = \"JentrataVersion\";\n\n //Jentrata Message Header keys\n public static final String SOAP_VERSION = \"JentrataSOAPVersion\";\n public static final String EBMS_VERSION = \"JentrataEBMSVersion\";\n public static final String VALID_PARTNER_AGREEMENT = \"JentrataIsValidPartnerAgreement\";\n public static final String EBMS_MESSAGE_MEP = \"JentrataMEP\";\n\n public static final String SOAP_VERSION_1_1 = \"1.1\";\n public static final String SOAP_VERSION_1_2 = \"1.2\";\n\n public static final String SOAP_1_1_NAMESPACE = \"http://schemas.xmlsoap.org/soap/envelope/\";\n\n public static final String SOAP_1_2_NAMESPACE = \"http://www.w3.org/2003/05/soap-envelope\";\n public static final String EBXML_V2_NAMESPACE = \"http://www.oasis-open.org/committees/ebxml-msg/schema/msg-header-2_0.xsd\";\n\n public static final String EBXML_V3_NAMESPACE = \"http://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/\";\n\n public static final String EBMS_V2 = \"ebMSV2\";\n public static final String EBMS_V3 = \"ebMSV3\";\n\n public static final String EBMS_V3_MEP_ONE_WAY = \"http://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/oneWay\";\n public static final String EBMS_V3_MEP_TWO_WAY = \"http://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/twoWay\";\n\n public static final String EBMS_V3_MEP_BINDING_PUSH = \"ttp://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/push\";\n\n public static final String EBMS_RECEIPT_REQUIRED = \"JentrataReceiptRequired\";\n\n public static final String CONTENT_ID = \"Content-ID\";\n public static final String CONTENT_LENGTH = Exchange.CONTENT_LENGTH;\n public static final String CONTENT_TRANSFER_ENCODING = \"Content-Transfer-Encoding\";\n public static final String CONTENT_DISPOSITION = \"Content-Disposition\";\n public static final String CONTENT_TYPE = Exchange.CONTENT_TYPE;\n\n public static final String SOAP_XML_CONTENT_TYPE = \"application/soap+xml\";\n public static final String TEXT_XML_CONTENT_TYPE = \"text/xml\";\n public static final String MESSAGE_ID = \"JentrataMessageID\";\n public static final String REF_TO_MESSAGE_ID = \"JentrataRefMessageID\";\n public static final String MESSAGE_FROM = \"JentrataFrom\";\n public static final String MESSAGE_FROM_TYPE = \"JentrataFromPartyIdType\";\n public static final String MESSAGE_FROM_ROLE = \"JentrataPartyFromRole\";\n public static final String MESSAGE_TO = \"JentrataTo\";\n public static final String MESSAGE_TO_TYPE = \"JentrataToPartyIdType\";\n public static final String MESSAGE_TO_ROLE = \"JentrataPartyToRole\";\n public static final String MESSAGE_AGREEMENT_REF = \"JentrataAgreementRef\";\n public static final String MESSAGE_PART_PROPERTIES = \"JentraraPartProperties\";\n public static final String MESSAGE_PAYLOAD_SCHEMA = \"JentrataPayloadSchema\";\n public static final String MESSAGE_DIRECTION = \"JentrataMessageDirection\";\n public static final String MESSAGE_DIRECTION_INBOUND = \"inbox\";\n public static final String MESSAGE_DIRECTION_OUTBOUND = \"outbox\";\n public static final String MESSAGE_STATUS = \"JentrataMessageStatus\";\n public static final String MESSAGE_STATUS_DESCRIPTION = \"JentrataMessageStatusDesc\";\n public static final String MESSAGE_TYPE = \"JentrataMessageType\";\n public static final String MESSAGE_SERVICE = \"JentrataService\";\n public static final String MESSAGE_ACTION = \"JentrataAction\";\n public static final String MESSAGE_CONVERSATION_ID = \"JentrataConversationId\";\n public static final String CPA = \"JentrataCPA\";\n public static final String CPA_ID = \"JentrataCPAId\";\n public static final String PAYLOAD_ID = \"JentrataPayloadId\";\n public static final String PAYLOAD_FILENAME = \"JentrataPayloadFilename\";\n public static final String PAYLOAD_COMPRESSION = \"JentrataPayloadCompression\";\n public static final String CPA_ID_UNKNOWN = \"UNKNOWN\";\n public static final String CONTENT_CHAR_SET = \"JentrataCharSet\";\n public static final String SOAP_BODY_PAYLOAD_ID = \"soapbodypart\";\n public static final String SECURITY_CHECK = \"JentrataSecurityCheck\";\n public static final String SECURITY_RESULTS = \"JentrataSecurityResults\";\n\n public static final String SECURITY_ERROR_CODE = \"JentrataSecurityErrorCode\";\n public static final String EBMS_ERROR = \"JentrataEbmsError\";\n public static final String EBMS_ERROR_CODE = \"JentrataEbmsErrorCode\";\n public static final String EBMS_ERROR_DESCRIPTION = \"JentrataEbmsErrorDesc\";\n public static final String MESSAGE_PAYLOADS = \"JentrataPayloads\";\n public static final String COMPRESSION_TYPE = \"CompressionType\";\n public static final String GZIP = \"application/gzip\";\n public static final String MESSAGE_DATE = \"JentrataMessageDate\";\n public static final String MESSAGE_RECEIPT_PATTERN = \"JentrataMessageReceipt\";\n public static final String MESSAGE_DUP_DETECTION = \"JentrataDupDetection\";\n public static final String DUPLICATE_MESSAGE = \"JentrataIsDuplicateMessage\";\n public static final String DUPLICATE_MESSAGE_ID = \"JentrataDuplicateMessageId\";\n public static final String VALIDATION_ERROR_DESC = \"JentrataValidationErrorDesc\";\n public static final String EBMS_VALIDATION_ERROR = \"JentrataValidationError\";\n\n public static final String DEFAULT_CPA_ID = \"JentrataDefaultCPAId\";\n public static final String DELIVERY_ERROR = \"JentrataDeliveryError\";\n}",
"public enum MessageStatusType {\n RECEIVED,\n DELIVER,\n DELIVERED,\n FAILED,\n DONE,\n IGNORED,\n ERROR;\n}",
"public enum MessageType {\n\n USER_MESSAGE,\n SIGNAL_MESSAGE,\n SIGNAL_MESSAGE_WITH_USER_MESSAGE,\n SIGNAL_MESSAGE_ERROR,\n UNKNOWN\n\n}",
"public interface Message {\n\n String getMessageId();\n String getDirection();\n String getCpaId();\n String getRefMessageId();\n String getConversationId();\n MessageStatusType getStatus();\n String getStatusDescription();\n Date getMessageDate();\n\n}",
"public interface MessageStore {\n\n public static final String DEFAULT_MESSAGE_STORE_ENDPOINT = \"direct:storeMessage\";\n public static final String DEFAULT_MESSAGE_INSERT_ENDPOINT = \"direct:insertMessage\";\n public static final String DEFAULT_MESSAGE_UPDATE_ENDPOINT = \"direct:updateMessage\";\n\n public static final String MESSAGE_STORE_REF = \"JentrataMessageStoreRef\";\n public static final String JENTRATA_MESSAGE_ID = \"JentrataMessageId\";\n\n void store(@Body InputStream message, Exchange exchange);\n\n void storeMessage(Exchange exchange);\n\n void updateMessage(@Header(EbmsConstants.MESSAGE_ID)String messageId,\n @Header(EbmsConstants.MESSAGE_DIRECTION)String messageDirection,\n @Header(EbmsConstants.MESSAGE_STATUS)MessageStatusType status,\n @Header(EbmsConstants.MESSAGE_STATUS_DESCRIPTION)String statusDescription);\n\n Message findByMessageId(@Header(EbmsConstants.MESSAGE_ID)String messageId, @Header(EbmsConstants.MESSAGE_DIRECTION) String messageDirection);\n InputStream findPayloadById(@Header(EbmsConstants.MESSAGE_ID)String messageId);\n List<Message> findByMessageStatus(@Header(EbmsConstants.MESSAGE_DIRECTION)String messageDirection, @Header(EbmsConstants.MESSAGE_STATUS)String status);\n}",
"public class MessageStoreException extends RuntimeException {\n\n public MessageStoreException() {\n }\n\n public MessageStoreException(String message) {\n super(message);\n }\n\n public MessageStoreException(String message, Throwable cause) {\n super(message, cause);\n }\n\n public MessageStoreException(Throwable cause) {\n super(cause);\n }\n\n public MessageStoreException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {\n super(message, cause, enableSuppression, writableStackTrace);\n }\n}",
"public class UUIDGenerator {\n\n private String prefix = \"\";\n private String sufffix = \"@jentrata.org\";\n\n public String generateId() {\n String uuid = UUID.randomUUID().toString();\n return prefix + uuid + sufffix;\n }\n}",
"public interface RepositoryManager {\n void createTablesIfNotExists();\n boolean isDuplicate(String messageId, String messageDirection);\n void insertIntoRepository(String messageId, String contentType, String messageDirection, long contentLength, InputStream content, String duplicateMessageId);\n void updateMessage(String messageId, String messageDirection, MessageStatusType status, String statusDescription);\n void insertMessage(String messageId, String messageDirection, MessageType messageType, String cpaId, String conversationId, String refMessageID);\n List<Message> selectMessageBy(String columnName, String value);\n List<Message> selectMessageBy(Map<String,Object> fields);\n InputStream selectRepositoryBy(String columnName, String value);\n}"
] | import org.apache.camel.Exchange;
import org.apache.camel.Header;
import org.apache.camel.component.ResourceEndpoint;
import org.apache.camel.util.ObjectHelper;
import org.apache.camel.util.ResourceHelper;
import org.apache.commons.io.IOUtils;
import org.jentrata.ebms.EbmsConstants;
import org.jentrata.ebms.MessageStatusType;
import org.jentrata.ebms.MessageType;
import org.jentrata.ebms.messaging.Message;
import org.jentrata.ebms.messaging.MessageStore;
import org.jentrata.ebms.messaging.MessageStoreException;
import org.jentrata.ebms.messaging.UUIDGenerator;
import org.jentrata.ebms.messaging.internal.sql.RepositoryManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.sql.DataSource;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.List;
import java.util.Map; | package org.jentrata.ebms.messaging.internal;
/**
* Store the raw message in Postgres
*
* @author aaronwalker
*/
public class JDBCMessageStore implements MessageStore {
private static final Logger LOG = LoggerFactory.getLogger(JDBCMessageStore.class);
private RepositoryManager repositoryManager;
private UUIDGenerator uuidGenerator;
private boolean createTables = true;
public void init() throws IOException {
if(createTables) {
LOG.info("Checking if Database tables exist");
repositoryManager.createTablesIfNotExists();
} else {
LOG.info("Database should have already been created");
}
}
@Override
public void store(InputStream message, Exchange exchange) {
String messageId = exchange.getIn().getHeader(EbmsConstants.MESSAGE_ID,String.class);
String messageDirection = exchange.getIn().getHeader(EbmsConstants.MESSAGE_DIRECTION,String.class);
String contentType = exchange.getIn().getHeader(EbmsConstants.CONTENT_TYPE,String.class);
long contentLength = exchange.getIn().getHeader(EbmsConstants.CONTENT_LENGTH,0L,Long.class);
boolean duplicate = repositoryManager.isDuplicate(messageId,messageDirection);
String duplicateMessageId = null;
if(duplicate) {
duplicateMessageId = uuidGenerator.generateId();
LOG.info("Message " + messageId + " is a duplicate new message Id " + duplicateMessageId);
exchange.getIn().setHeader(EbmsConstants.DUPLICATE_MESSAGE,true);
exchange.getIn().setHeader(EbmsConstants.DUPLICATE_MESSAGE_ID,duplicateMessageId);
repositoryManager.insertIntoRepository(duplicateMessageId, contentType, messageDirection, contentLength, message, messageId);
} else {
repositoryManager.insertIntoRepository(messageId, contentType, messageDirection, contentLength, message, messageId);
}
}
public void storeMessage(Exchange exchange) {
String messageId = exchange.getIn().getHeader(EbmsConstants.MESSAGE_ID,String.class);
String messageDirection = exchange.getIn().getHeader(EbmsConstants.MESSAGE_DIRECTION,String.class);
MessageType messageType = exchange.getIn().getHeader(EbmsConstants.MESSAGE_TYPE,MessageType.class);
String cpaId = exchange.getIn().getHeader(EbmsConstants.CPA_ID,String.class);
String conversationId = exchange.getIn().getHeader(EbmsConstants.MESSAGE_CONVERSATION_ID,String.class);
String refMessageID = exchange.getIn().getHeader(EbmsConstants.REF_TO_MESSAGE_ID, String.class);
String duplicateMessageId = exchange.getIn().getHeader(EbmsConstants.DUPLICATE_MESSAGE_ID, String.class);
if(duplicateMessageId != null) {
repositoryManager.insertMessage(duplicateMessageId,messageDirection,messageType,cpaId,conversationId,refMessageID);
} else {
repositoryManager.insertMessage(messageId,messageDirection,messageType,cpaId,conversationId,refMessageID);
}
}
@Override
public void updateMessage(String messageId, String messageDirection, MessageStatusType status, String statusDescription) {
repositoryManager.updateMessage(messageId,messageDirection,status,statusDescription);
}
@Override | public Message findByMessageId(String messageId, String messageDirection) { | 3 |
CraftedCart/SMBLevelWorkshop | src/main/java/craftedcart/smblevelworkshop/resource/ResourceManager.java | [
"public class GLSLCompileException extends Exception {\n\n public GLSLCompileException(String message) {\n super(\"\\n\" + message);\n }\n\n}",
"public class OBJLoader {\n\n public static boolean isLastObjTriangulated;\n\n public static ResourceModel loadModel(String filePath) throws IOException {\n\n try {\n Window.drawable.makeCurrent();\n } catch (LWJGLException e) {\n LogHelper.error(OBJLoader.class, e);\n }\n\n LogHelper.info(OBJLoader.class, \"Parsing OBJ file\");\n\n Build builder = new Build();\n\n try {\n new Parse(builder, filePath); //Constructor does work\n } catch (IOException e) {\n LogHelper.error(OBJLoader.class, \"Error while loading OBJ\");\n LogHelper.error(OBJLoader.class, e);\n }\n\n// LogHelper.info(OBJLoader.class, \"Splitting OBJ file faces into list of faces per material\");\n// ArrayList<ArrayList<Face>> facesByTextureList = createFaceListsByMaterial(builder);\n\n LogHelper.info(OBJLoader.class, \"Splitting OBJ file faces into list of faces per object\");\n ArrayList<ArrayList<Face>> facesByObjectList = createFaceListsByObject(builder);\n\n List<OBJObject> objectList = new ArrayList<>();\n\n for (ArrayList<Face> faceList : facesByObjectList) { //Split objects by material\n //Aggregate lists to average to get a center point\n List<Float> aggregateX = new ArrayList<>();\n List<Float> aggregateY = new ArrayList<>();\n List<Float> aggregateZ = new ArrayList<>();\n\n ArrayList<ArrayList<Face>> facesByMaterialList = createFaceListsByMaterial(faceList);\n\n OBJObject object = new OBJObject();\n if (facesByMaterialList.size() > 0 && facesByMaterialList.get(0).size() > 0) {\n object.setName(facesByMaterialList.get(0).get(0).objectName);\n }\n\n for (ArrayList<Face> faceMatList : facesByMaterialList) {\n OBJFacesByMaterial facesByMaterial = new OBJFacesByMaterial();\n facesByMaterial.setFaceList(faceMatList);\n object.addFacesByMaterial(facesByMaterial);\n }\n\n //Add vertex positions to the aggregate lists to average later\n for (Face face : faceList) {\n for (FaceVertex vertex : face.vertices) {\n aggregateX.add(vertex.v.x);\n aggregateY.add(vertex.v.y);\n aggregateZ.add(vertex.v.z);\n }\n }\n\n //Average vertex positions\n float avgX = 0;\n for (Float val : aggregateX) {\n avgX += val;\n }\n avgX = avgX / aggregateX.size();\n\n float avgY = 0;\n for (Float val : aggregateY) {\n avgY += val;\n }\n avgY = avgY / aggregateY.size();\n\n float avgZ = 0;\n for (Float val : aggregateZ) {\n avgZ += val;\n }\n avgZ = avgZ / aggregateZ.size();\n\n object.setCenterPoint(new Vec3f(avgX, avgY, avgZ));\n\n objectList.add(object);\n }\n\n TextureLoader textureLoader = new TextureLoader();\n int defaultTextureID = 0;\n// if (defaultTextureMaterial != null) {\n// log.log(INFO, \"Loading default texture =\" + defaultTextureMaterial);\n// defaultTextureID = setUpDefaultTexture(textureLoader, defaultTextureMaterial);\n// log.log(INFO, \"Done loading default texture =\" + defaultTextureMaterial);\n// }\n// if (defaultTextureID == -1) {\n// BufferedImage img = new BufferedImage(256, 256, BufferedImage.TYPE_INT_ARGB);\n// Graphics g = img.getGraphics();\n// g.setColor(Color.BLUE);\n// g.fillRect(0, 0, 256, 256);\n// g.setColor(Color.RED);\n// for (int loop = 0; loop < 256; loop++) {\n// g.drawLine(loop, 0, loop, 255);\n// g.drawLine(0, loop, 255, loop);\n// }\n// defaultTextureID = textureLoader.convertToTexture(img);\n// }\n int currentTextureID;\n\n OBJScene scene = new OBJScene();\n\n scene.setObjectList(objectList);\n\n for (OBJObject object : objectList) {\n for (OBJFacesByMaterial facesByMaterial : object.facesByMaterialList) {\n List<Face> faceList = facesByMaterial.faceList;\n\n if (faceList.isEmpty()) {\n LogHelper.error(OBJLoader.class, \"Got an empty face list. That shouldn't be possible.\");\n continue;\n }\n LogHelper.info(OBJLoader.class, \"Getting material \" + faceList.get(0).material);\n currentTextureID = getMaterialID(faceList.get(0).material, defaultTextureID, builder, textureLoader);\n LogHelper.info(OBJLoader.class, \"Splitting any quads and throwing any faces with > 4 vertices.\");\n ArrayList<Face> triangleList = splitQuads(faceList);\n LogHelper.info(OBJLoader.class, \"Calculating any missing vertex normals.\");\n calcMissingVertexNormals(triangleList);\n LogHelper.info(OBJLoader.class, \"Ready to build VBO of \" + triangleList.size() + \" triangles\");\n\n if (triangleList.size() <= 0) {\n continue;\n }\n LogHelper.info(OBJLoader.class, \"Building VBO\");\n\n VBO vbo = VBOFactory.build(currentTextureID, faceList.get(0).material, triangleList);\n\n LogHelper.info(OBJLoader.class, \"Adding VBO with texture id \" + currentTextureID + \", with \" + triangleList.size() + \" triangles to OBJFacesByMaterial\");\n facesByMaterial.setVbo(vbo);\n }\n }\n\n LogHelper.info(OBJLoader.class, \"Done loading OBJ\");\n\n try {\n Window.drawable.releaseContext();\n } catch (LWJGLException e) {\n LogHelper.error(OBJLoader.class, e);\n }\n\n return new ResourceModel(scene);\n }\n\n //Iterate over face list from builder, and break it up into a set of face lists by material, i.e. each for each face list, all faces in that specific list use the same material\n private static ArrayList<ArrayList<Face>> createFaceListsByMaterial(ArrayList<Face> faceList) {\n ArrayList<ArrayList<Face>> facesByTextureList;\n facesByTextureList = new ArrayList<>();\n Material currentMaterial = null;\n ArrayList<Face> currentFaceList;\n currentFaceList = new ArrayList<>();\n for (Face face : faceList) {\n if (face.material != currentMaterial) {\n if (!currentFaceList.isEmpty()) {\n String matName = null;\n if (currentMaterial != null) {\n matName = currentMaterial.name;\n }\n\n LogHelper.trace(OBJLoader.class, \"Adding list of \" + currentFaceList.size() + \" triangle faces with material \" + matName + \" to our list of lists of faces.\");\n facesByTextureList.add(currentFaceList);\n }\n\n String faceMatName = null;\n if (face.material != null) {\n faceMatName = face.material.name;\n }\n\n LogHelper.trace(OBJLoader.class, \"Creating new list of faces for material \" + faceMatName);\n currentMaterial = face.material;\n currentFaceList = new ArrayList<>();\n }\n currentFaceList.add(face);\n }\n if (!currentFaceList.isEmpty()) {\n String matName = null;\n if (currentMaterial != null) {\n matName = currentMaterial.name;\n }\n\n LogHelper.trace(OBJLoader.class, \"Adding list of \" + currentFaceList.size() + \" triangle faces with material \" + matName + \" to our list of lists of faces.\");\n facesByTextureList.add(currentFaceList);\n }\n return facesByTextureList;\n }\n\n private static ArrayList<ArrayList<Face>> createFaceListsByObject(Build builder) {\n ArrayList<ArrayList<Face>> facesByObjectList = new ArrayList<>();\n String currentObjectName = null;\n ArrayList<Face> currentFaceList = new ArrayList<>();\n\n for (Face face : builder.faces) {\n if (!Objects.equals(face.objectName, currentObjectName)) {\n if (!currentFaceList.isEmpty()) {\n LogHelper.trace(OBJLoader.class, \"Adding list of \" + currentFaceList.size() + \" triangle faces of object \" + currentObjectName + \" to our list of lists of faces.\");\n facesByObjectList.add(currentFaceList);\n }\n\n LogHelper.trace(OBJLoader.class, \"Creating new list of faces for object \" + face.objectName);\n currentObjectName = face.objectName;\n currentFaceList = new ArrayList<>();\n }\n\n currentFaceList.add(face);\n }\n\n if (!currentFaceList.isEmpty()) {\n LogHelper.trace(OBJLoader.class, \"Adding list of \" + currentFaceList.size() + \" triangle faces of object \" + currentObjectName + \" to our list of lists of faces.\");\n facesByObjectList.add(currentFaceList);\n }\n\n return facesByObjectList;\n }\n\n\n // Get the specified Material, bind it as a texture, and return the OpenGL ID. Returns the default texture ID if we can't\n // load the new texture, or if the material is a non texture and hence we ignore it.\n private static int getMaterialID(Material material, int defaultTextureID, Build builder, TextureLoader textureLoader) {\n int currentTextureID;\n if (material == null) {\n currentTextureID = defaultTextureID;\n } else if (material.mapKdFilename == null) {\n currentTextureID = defaultTextureID;\n } else {\n try {\n File objFile = new File(builder.objFilename);\n File mapKdFile = new File(objFile.getParent(), material.mapKdFilename);\n LogHelper.info(OBJLoader.class, \"Trying to load \" + mapKdFile.getAbsolutePath());\n currentTextureID = textureLoader.load(mapKdFile.getAbsolutePath());\n } catch (IOException ex) {\n LogHelper.error(OBJLoader.class, \"Failed to get material ID\");\n LogHelper.info(OBJLoader.class, \"Got an exception trying to load texture material = \" + material.mapKdFilename + \" , ex=\" + ex);\n ex.printStackTrace();\n LogHelper.info(OBJLoader.class, \"Using default texture ID = \" + defaultTextureID);\n currentTextureID = defaultTextureID;\n }\n }\n return currentTextureID;\n }\n\n // VBOFactory can only handle triangles, not faces with more than 3 vertices. There are much better ways to 'triangulate' polygons, that\n // can be used on polygons with more than 4 sides, but for this simple test code justsplit quads into two triangles\n // and drop all polygons with more than 4 vertices. (I was originally just dropping quads as well but then I kept ending up with nothing\n // left to display. :-) Or at least, not much. )\n private static ArrayList<Face> splitQuads(List<Face> faceList) {\n ArrayList<Face> triangleList = new ArrayList<>();\n int countTriangles = 0;\n int countQuads = 0;\n int countNGons = 0;\n for (Face face : faceList) {\n if (face.vertices.size() == 3) {\n countTriangles++;\n triangleList.add(face);\n } else if (face.vertices.size() == 4) {\n countQuads++;\n FaceVertex v1 = face.vertices.get(0);\n FaceVertex v2 = face.vertices.get(1);\n FaceVertex v3 = face.vertices.get(2);\n FaceVertex v4 = face.vertices.get(3);\n Face f1 = new Face();\n f1.map = face.map;\n f1.material = face.material;\n f1.add(v1);\n f1.add(v2);\n f1.add(v3);\n triangleList.add(f1);\n Face f2 = new Face();\n f2.map = face.map;\n f2.material = face.material;\n f2.add(v1);\n f2.add(v3);\n f2.add(v4);\n triangleList.add(f2);\n } else {\n countNGons++;\n }\n }\n int texturedCount = 0;\n int normalCount = 0;\n for (Face face : triangleList) {\n if ((face.vertices.get(0).n != null)\n && (face.vertices.get(1).n != null)\n && (face.vertices.get(2).n != null)) {\n normalCount++;\n }\n if ((face.vertices.get(0).t != null)\n && (face.vertices.get(1).t != null)\n && (face.vertices.get(2).t != null)) {\n texturedCount++;\n }\n }\n LogHelper.info(OBJLoader.class, \"Building VBO, originally \" + faceList.size() + \" faces, of which originally \" + countTriangles + \" triangles, \" + countQuads + \" quads, and \" + countNGons + \" n-polygons with more than 4 vertices that were dropped.\");\n LogHelper.info(OBJLoader.class, \"Triangle list has \" + triangleList.size() + \" rendered triangles of which \" + normalCount + \" have normals for all vertices and \" + texturedCount + \" have texture coords for all vertices.\");\n\n isLastObjTriangulated = !(countQuads > 0 || countNGons > 0); //Check if OBJ was triangulated\n\n return triangleList;\n }\n\n //@TODO: This is a crappy way to calculate vertex normals if we are missing said normals. I just wanted\n //something that would add normals since my simple VBO creation code expects them. There are better ways\n //to generate normals, especially given that the .obj file allows specification of \"smoothing groups\".\n private static void calcMissingVertexNormals(ArrayList<Face> triangleList) {\n for (Face face : triangleList) {\n face.calculateTriangleNormal();\n for (int loopv = 0; loopv < face.vertices.size(); loopv++) {\n FaceVertex fv = face.vertices.get(loopv);\n if (face.vertices.get(0).n == null) {\n FaceVertex newFv = new FaceVertex();\n newFv.v = fv.v;\n newFv.t = fv.t;\n newFv.n = face.faceNormal;\n face.vertices.set(loopv, newFv);\n }\n }\n }\n }\n\n}",
"public class ResourceModel implements IResource {\n\n public OBJScene scene;\n\n public ResourceModel(OBJScene scene) {\n this.scene = scene;\n }\n\n public void drawModel(ResourceShaderProgram shaderProgram, boolean setTexture) {\n scene.renderAll(shaderProgram, setTexture);\n }\n\n public void drawModel(ResourceShaderProgram shaderProgram, boolean setTexture, UIColor color) {\n scene.renderAll(shaderProgram, setTexture, color);\n }\n\n public void drawModelObject(ResourceShaderProgram shaderProgram, boolean setTexture, String name) {\n scene.renderObjectByName(shaderProgram, setTexture, name);\n }\n\n public void drawModelWireframe(ResourceShaderProgram shaderProgram, boolean setTexture) {\n GL11.glPolygonMode(GL11.GL_FRONT_AND_BACK, GL11.GL_LINE);\n scene.renderAll(shaderProgram, setTexture);\n GL11.glPolygonMode(GL11.GL_FRONT_AND_BACK, GL11.GL_FILL);\n }\n\n public void drawModelObjectWireframe(ResourceShaderProgram shaderProgram, boolean setTexture, String name) {\n GL11.glPolygonMode(GL11.GL_FRONT_AND_BACK, GL11.GL_LINE);\n scene.renderObjectByName(shaderProgram, setTexture, name);\n GL11.glPolygonMode(GL11.GL_FRONT_AND_BACK, GL11.GL_FILL);\n }\n\n public boolean hasObject(String name) {\n return scene.hasObject(name);\n }\n\n// public static void drawModel(ResourceModel m, ResourceShaderProgram shaderProgram, boolean setTexture) {\n// m.scene.render(shaderProgram, setTexture);\n// }\n//\n// public static void drawModel(ResourceModel m, ResourceShaderProgram shaderProgram, boolean setTexture, UIColor color) {\n// m.scene.render(shaderProgram, setTexture, color);\n// }\n//\n// public static void drawModelWireframe(ResourceModel m, ResourceShaderProgram shaderProgram, boolean setTexture) {\n// GL11.glPolygonMode(GL11.GL_FRONT_AND_BACK, GL11.GL_LINE);\n// m.scene.render(shaderProgram, setTexture);\n// GL11.glPolygonMode(GL11.GL_FRONT_AND_BACK, GL11.GL_FILL);\n// }\n\n}",
"public class LoadingScreen implements IUIScreen {\n\n @NotNull public static String headerMessage = \"\";\n @NotNull public static String infoMessage = \"\";\n /**\n * A number between 0 and 1\n * Set to -1 to disable the progress bar\n */\n public static double progress = 0;\n\n @Nullable public static Map<String, UIColor> debugMessagesOverlay;\n\n @Nullable private UnicodeFont headerFont = FontCache.getUnicodeFont(\"Roboto-Regular\", 24);\n @Nullable private UnicodeFont infoFont = FontCache.getUnicodeFont(\"Roboto-Regular\", 16);\n\n public LoadingScreen() {\n UIColor.matWhite().bindClearColor();\n }\n\n public void draw() {\n //<editor-fold desc=\"Draw the background\">\n ResourceTexture texture = ResourceManager.getTexture(\"_loadBackground\", false);\n if (texture != null) {\n double texRatio = texture.getHeight() / (double) texture.getWidth();\n int height;\n int width;\n if (Display.getHeight() / (double) Display.getWidth() > texRatio) {\n height = Display.getHeight();\n width = (int) (height / texRatio);\n } else {\n width = Display.getWidth();\n height = (int) (width * texRatio);\n }\n\n GL11.glEnable(GL11.GL_TEXTURE_2D);\n UIColor.pureWhite().bindColor();\n UIUtils.drawTexturedQuad(\n new PosXY(Display.getWidth() / 2 - width / 2, Display.getHeight() / 2 - height / 2),\n new PosXY(Display.getWidth() / 2 + width / 2, Display.getHeight() / 2 + height / 2),\n texture.getTexture());\n GL11.glDisable(GL11.GL_TEXTURE_2D);\n }\n //</editor-fold>\n\n //<editor-fold desc=\"Draw debugMessagesOverlay\">\n if (infoFont != null && debugMessagesOverlay != null) {\n UIUtils.drawQuad(\n new PosXY(0, 0),\n new PosXY(Display.getWidth(), Display.getHeight()),\n UIColor.matGrey900(0.75));\n\n Map<String, UIColor> duplicateMap = new LinkedHashMap<>();\n duplicateMap.putAll(debugMessagesOverlay);\n ListIterator<Map.Entry<String, UIColor>> iterator = new ArrayList<>(duplicateMap.entrySet()).listIterator(duplicateMap.size());\n\n int currentHeight = 24;\n\n while (iterator.hasPrevious()) {\n Map.Entry<String, UIColor> entry = iterator.previous();\n UIUtils.drawString(infoFont, 24, currentHeight, UIUtils.wrapString(infoFont, Display.getWidth() - 48, entry.getKey()), entry.getValue());\n currentHeight += infoFont.getLineHeight();\n for (char c : UIUtils.wrapString(infoFont, Display.getWidth() - 48, entry.getKey()).toCharArray()) {\n if (c == '\\n') {\n currentHeight += infoFont.getLineHeight();\n }\n }\n }\n }\n //</editor-fold>\n\n UIColor.matGrey900(0.75).bindColor();\n UIUtils.drawQuad(\n new PosXY(0, Display.getHeight() - 110),\n new PosXY(Display.getWidth(), Display.getHeight()));\n\n UIUtils.drawQuadGradientVertical(\n new PosXY(0, Display.getHeight() - 114),\n new PosXY(Display.getWidth(), Display.getHeight() - 110),\n UIColor.matGrey900(0), UIColor.matGrey900(0.5));\n\n if (headerFont != null) {\n UIUtils.drawString(headerFont, 24, Display.getHeight() - 96, headerMessage, UIColor.matWhite());\n }\n\n if (infoFont != null) {\n if (progress == -1) {\n UIUtils.drawString(infoFont, 24, Display.getHeight() - 52, infoMessage, UIColor.matWhite());\n } else {\n UIUtils.drawString(infoFont, 24, Display.getHeight() - 52, String.format(\"%05.2f%% %s\", progress * 100, infoMessage), UIColor.matWhite());\n }\n }\n\n //<editor-fold desc=\"Draw progress bar\">\n if (progress != -1) {\n UIColor.matGrey900().bindColor();\n UIUtils.drawQuad(\n new PosXY((Display.getWidth() - 48) * progress + 24, Display.getHeight() - 26),\n new PosXY(Display.getWidth() - 24, Display.getHeight() - 24));\n UIColor.pureWhite().bindColor();\n UIUtils.drawQuad(\n new PosXY(24, Display.getHeight() - 26),\n new PosXY((Display.getWidth() - 48) * progress + 24, Display.getHeight() - 24));\n }\n //</editor-fold>\n }\n\n}",
"public class CrashHandler {\n\n public static final Thread.UncaughtExceptionHandler UNCAUGHT_EXCEPTION_HANDLER = CrashHandler::handleCrash;\n\n private static JFrame cleanupFrame;\n private static JTextArea cleanupTextArea;\n\n public static void handleCrash(Thread t, Throwable e) {\n Thread.setDefaultUncaughtExceptionHandler(null); //In case something bad happens, don't enter an infinite loop\n\n LogHelper.fatal(CrashHandler.class, generateCrashLog(t, e));\n\n LogHelper.info(CrashHandler.class, \"Uncaught exception - Now handling crash!\");\n\n SMBLevelWorkshop.shouldQuitJVM = false; //Don't auto quit JVM because the Display was destroyed\n\n createCrashCleanupUI();\n\n new Thread(() -> {\n if (Window.drawable != null) {\n LogHelper.info(CrashHandler.class, \"Attempting to stop update loop\");\n updateCrashCleanupUI(\"Attempting to stop update loop\");\n Window.running = false;\n }\n\n if (ProjectManager.getCurrentLevelData() != null) {\n LogHelper.info(CrashHandler.class, \"Attempting to save current project to home directory\");\n updateCrashCleanupUI(\"Attempting to save current project to home directory\");\n\n String dateTimeStr = new SimpleDateFormat(\"yyyy-MM-dd'T'HH-mm-ssZ\").format(new Date());\n File crashProject = new File(System.getProperty(\"user.home\"), \"SMBLevelWorkshop-CrashProject-\" + dateTimeStr + \".xml\");\n\n try {\n ExportXMLManager.writeXMLConfig(ProjectManager.getCurrentLevelData(), crashProject);\n LogHelper.info(CrashHandler.class, \"Saved crash project to \" + crashProject.getPath());\n updateCrashCleanupUI(\"Saved crash project to \" + crashProject.getPath());\n } catch (ParserConfigurationException | TransformerException e1) {\n LogHelper.error(CrashHandler.class, \"Error saving current project\\n\" + getStackTraceString(e1));\n updateCrashCleanupUI(\"Error saving current project\\n\" + getStackTraceString(e1));\n }\n }\n\n destroyCrashCleanupUI();\n showCrashUI();\n }, \"CrashHandlerThread\").start();\n\n }\n\n private static void createCrashCleanupUI() {\n cleanupFrame = new JFrame(\"SMB Level Workshop Crash Handler\");\n cleanupFrame.setSize(800, 300);\n cleanupFrame.setLayout(new BorderLayout());\n\n cleanupTextArea = new JTextArea();\n cleanupTextArea.setEditable(false);\n\n cleanupTextArea.setFont(new Font(\"monospaced\", Font.PLAIN, 12));\n JScrollPane scrollPane = new JScrollPane(cleanupTextArea);\n cleanupFrame.add(scrollPane);\n\n cleanupFrame.setVisible(true);\n }\n\n private static void updateCrashCleanupUI(String text) {\n SwingUtilities.invokeLater(() -> cleanupTextArea.append(text + \"\\n\"));\n }\n\n private static void destroyCrashCleanupUI() {\n cleanupFrame.setVisible(false);\n cleanupFrame = null;\n cleanupTextArea = null;\n }\n\n private static void showCrashUI() {\n JFrame frame = new JFrame(\"SMB Level Workshop Crash Handler\");\n frame.setSize(800, 600);\n frame.setLayout(new BorderLayout());\n\n JTextArea logTextArea = new JTextArea();\n logTextArea.setEditable(false);\n\n StringBuilder logSB = new StringBuilder();\n for (LogHelper.LogEntry entry : LogHelper.log) {\n logSB.append(entry.logLevel.name()).append(\" - \").append(entry.clazz.getCanonicalName()).append(\" - \").append(entry.object).append(\"\\r\\n\");\n }\n\n logTextArea.setText(logSB.toString());\n logTextArea.setFont(new Font(\"monospaced\", Font.PLAIN, 12));\n JScrollPane scrollPane = new JScrollPane(logTextArea);\n frame.add(scrollPane);\n\n frame.addWindowListener(new WindowAdapter() {\n @Override\n public void windowClosing(WindowEvent e) {\n SMBLevelWorkshop.shouldQuitJVM = true;\n SMBLevelWorkshop.onQuit();\n }\n });\n\n frame.setVisible(true);\n\n //Scroll to bottom\n JScrollBar vertical = scrollPane.getVerticalScrollBar();\n vertical.setValue(vertical.getMaximum());\n }\n\n public static String getStackTraceString(Throwable e) {\n //Get the stack trace as a string\n StringWriter sw = new StringWriter();\n e.printStackTrace(new PrintWriter(sw));\n return sw.toString();\n }\n\n public static String generateCrashLog(Thread t, Throwable e) {\n\n RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();\n\n String osName = System.getProperty(\"os.name\");\n String osVersion = System.getProperty(\"os.version\");\n String osArch = System.getProperty(\"os.arch\");\n String javaVersion = System.getProperty(\"java.version\");\n String javaVendor = System.getProperty(\"java.vendor\");\n\n List<String> jvmArgs = runtimeMxBean.getInputArguments();\n StringBuilder builder = new StringBuilder(\" \");\n for (String aValue : jvmArgs) builder.append(aValue).append(\"\\n \");\n if (jvmArgs.size() > 0) {builder.deleteCharAt(builder.length() - 5);} else {builder.append(\"None\");}\n String jvmArgsString = builder.toString();\n\n String lwjglVersion = Sys.getVersion();\n long processors = Runtime.getRuntime().availableProcessors();\n long heapSize = Runtime.getRuntime().maxMemory();\n\n DateFormat df = new SimpleDateFormat(\"yyyy-MM-dd HH:mm:ss zzz\");\n Date dateObj = new Date();\n String time = df.format(dateObj); //Get the date and time\n\n return \"A fatal error has been thrown within SMB Level Workshop\\n\" +\n \"\\n\" +\n \"===============[ BEGIN CRASH REPORT ]===============\\n\" +\n \"\\n\" +\n \"SMB Level Workshop has crashed!\\n\" +\n \"===============================\\n\" +\n \"\\n\" +\n String.format(\"Time: %s\\n\", time) +\n \"\\n\" +\n \"System Information\\n\" +\n \"==================\\n\" +\n \"\\n\" +\n String.format(\"Operating System Name: %s\\n\", osName) +\n String.format(\"Operating System Version: %s\\n\", osVersion) +\n String.format(\"Operating System Architecture: %s\\n\", osArch) +\n String.format(\"Java Version: %s\\n\", javaVersion) +\n String.format(\"Java Vendor: %s\\n\", javaVendor) +\n String.format(\"JVM Arguments:\\n%s\\n\", jvmArgsString) +\n String.format(\"LWJGL Version: %s\\n\", lwjglVersion) +\n String.format(\"OpenGL Version: %s\\n\", Window.openGLVersion) +\n String.format(\"Available Processors: %d\\n\", processors) +\n String.format(\"Heap Size: %d B (%.2f MiB)\\n\", heapSize, heapSize / 1048576d) +\n \"\\n\" +\n \"Crash Details\\n\" +\n \"=============\\n\" +\n \"\\n\" +\n String.format(\"Causing thread: %d \\\"%s\\\"\\n\", t.getId(), t.getName()) +\n \"\\n\" +\n \"Stack Trace\\n\" +\n \"===========\\n\" +\n \"\\n\" +\n String.format(\"%s\\n\", getStackTraceString(e)) +\n \"\\n\" +\n \"===============[ END CRASH REPORT ]===============\\n\";\n }\n\n}",
"public class LogHelper {\n\n public static List<LogEntry> log = new ArrayList<>();\n\n private static void log(Class clazz, Level logLevel, Object object) {\n LogManager.getLogger(clazz).log(logLevel, object);\n log.add(new LogEntry(clazz, logLevel, object));\n if (log.size() > 1024) {\n log.remove(0);\n }\n }\n\n public static void all(Class clazz, Object object) {\n log(clazz, Level.ALL, object);\n }\n\n public static void fatal(Class clazz, Object object) {\n log(clazz, Level.FATAL, object);\n }\n\n public static void error(Class clazz, Object object) {\n log(clazz, Level.ERROR, object);\n }\n\n public static void warn(Class clazz, Object object) {\n log(clazz, Level.WARN, object);\n }\n\n public static void info(Class clazz, Object object) {\n log(clazz, Level.INFO, object);\n }\n\n public static void debug(Class clazz, Object object) {\n log(clazz, Level.DEBUG, object);\n }\n\n public static void trace(Class clazz, Object object) {\n log(clazz, Level.TRACE, object);\n }\n\n public static void off(Class clazz, Object object) {\n log(clazz, Level.OFF, object);\n }\n\n public static String stackTraceToString(Throwable e) {\n StringBuilder sb = new StringBuilder();\n for (StackTraceElement element : e.getStackTrace()) {\n sb.append(\" at \");\n sb.append(element.toString());\n sb.append(\"\\n\");\n }\n return sb.toString();\n }\n\n public static class LogEntry {\n\n public Class clazz;\n public Level logLevel;\n public Object object;\n\n public LogEntry(Class clazz, Level logLevel, Object object) {\n this.clazz = clazz;\n this.logLevel = logLevel;\n this.object = object;\n }\n\n }\n\n}"
] | import craftedcart.smblevelworkshop.exception.GLSLCompileException;
import craftedcart.smblevelworkshop.resource.model.OBJLoader;
import craftedcart.smblevelworkshop.resource.model.ResourceModel;
import craftedcart.smblevelworkshop.ui.LoadingScreen;
import craftedcart.smblevelworkshop.util.CrashHandler;
import craftedcart.smblevelworkshop.util.LogHelper;
import io.github.craftedcart.fluidui.FontCache;
import io.github.craftedcart.fluidui.util.UIColor;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.GL20;
import org.newdawn.slick.SlickException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.awt.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarFile; | */
private static void queueAddResource(@NotNull File resourceFile, @NotNull String resourceID) throws IOException {
if (resourceID.toUpperCase().endsWith(".PNG")) { //PNG texture (Ignore .exclude.png)
pngResourcesToLoad.put(resourceID, resourceFile);
} else if (resourceID.toUpperCase().endsWith(".TTF")) { //TTF Font
fontResourcesToLoad.put(resourceID, resourceFile);
} else if (resourceID.toUpperCase().endsWith(".FONTS.JSON")) { //Fonts to add to the Font cache
fontCacheResourcesToLoad.put(resourceID, resourceFile);
} else if (resourceID.toUpperCase().endsWith(".LANG.XML")) { //Language packs
langPackResourcesToLoad.put(resourceID, resourceFile);
} else if (resourceID.toUpperCase().endsWith(".FRAG")) { //Fragment shader
fragShaderResourcesToLoad.put(resourceID, resourceFile);
} else if (resourceID.toUpperCase().endsWith(".VERT")) { //Vertex shader
vertShaderResourcesToLoad.put(resourceID, resourceFile);
} else if (resourceID.toUpperCase().endsWith(".SHADERS.JSON")) { //Shaders to add to the Shader cache
shaderCacheResourcesToLoad.put(resourceID, resourceFile);
// } else if (resourceID.toUpperCase().endsWith(".BGMUSIC.OGG")) { //OGG Background Music
// musicOggResourcesToLoad.put(resourceID, resourceFile.toURI().toURL());
} else if (resourceID.toUpperCase().endsWith(".OBJ")) { //Shaders to add to the Shader cache
objResourcesToLoad.put(resourceID, resourceFile);
} else if (!Objects.equals(resourceID.toUpperCase(), ".DS_STORE") && //Ignore .DS_STORE
!Objects.equals(resourceID.toUpperCase(), "THUMBS.DB") && //Ignore THUMBS.DB
!resourceID.toUpperCase().endsWith(".MTL")) { //Ignore .MTL (These are handled by the OBJLoader))
addWarnedResource(resourceID, initResources.getString("unrecognisedFileExtension"));
LogHelper.warn(ResourceManager.class, String.format("Unrecognised resource file extension: \"%s\"", resourceID));
}
}
/**
* Will register all resources in the correct order.
*/
public static void registerAllResources() {
erroredResources.clear();
//The total number of resources to load
int totalResources =
fontResourcesToLoad.size() +
fontCacheResourcesToLoad.size() +
pngResourcesToLoad.size() +
langPackResourcesToLoad.size() +
vertShaderResourcesToLoad.size() +
fragShaderResourcesToLoad.size() +
shaderCacheResourcesToLoad.size() +
// musicOggResourcesToLoad.size();
objResourcesToLoad.size();
int currentResource = 0;
for (Map.Entry<String, File> resource : fontResourcesToLoad.entrySet()) { //Register Font TTF files
currentResource++;
LoadingScreen.infoMessage = resource.getKey();
LoadingScreen.progress = currentResource / (double) totalResources;
try {
registerTTF(resource.getValue(), resource.getKey());
} catch (IOException e) {
addErroredResource(resource.getKey(), e.getMessage());
LogHelper.error(ResourceManager.class, CrashHandler.getStackTraceString(e));
}
}
for (Map.Entry<String, File> resource : fontCacheResourcesToLoad.entrySet()) { //Register Font cache JSON files
currentResource++;
LoadingScreen.infoMessage = resource.getKey();
LoadingScreen.progress = currentResource / (double) totalResources;
try {
registerFontCache(resource.getValue(), resource.getKey());
} catch (IOException | LWJGLException | SlickException | FontFormatException | ParseException e) {
addErroredResource(resource.getKey(), e.getMessage());
LogHelper.error(ResourceManager.class, CrashHandler.getStackTraceString(e));
}
}
//Load and register the loading screen background first if it exists
File loadBGFile = pngResourcesToLoad.get("_loadBackground.png");
if (loadBGFile != null) {
currentResource++;
LoadingScreen.infoMessage = "_loadBackground.png";
LoadingScreen.progress = currentResource / (double) totalResources;
try {
registerPNG(loadBGFile, "_loadBackground.png");
} catch (Exception e) {
addErroredResource("_loadBackground.png", e.getMessage());
LogHelper.error(ResourceManager.class, CrashHandler.getStackTraceString(e));
}
pngResourcesToLoad.remove("_loadBackground.png");
}
for (Map.Entry<String, File> resource : pngResourcesToLoad.entrySet()) { //Register PNG textures
currentResource++;
LoadingScreen.infoMessage = resource.getKey();
LoadingScreen.progress = currentResource / (double) totalResources;
try {
registerPNG(resource.getValue(), resource.getKey());
} catch (Exception e) {
addErroredResource(resource.getKey(), e.getMessage());
LogHelper.error(ResourceManager.class, CrashHandler.getStackTraceString(e));
}
}
for (Map.Entry<String, File> resource : langPackResourcesToLoad.entrySet()) { //Register Lang files
currentResource++;
LoadingScreen.infoMessage = resource.getKey();
LoadingScreen.progress = currentResource / (double) totalResources;
try {
registerLangPack(resource.getValue(), resource.getKey());
} catch (ParserConfigurationException | IOException | SAXException e) {
addErroredResource(resource.getKey(), e.getMessage());
LogHelper.error(ResourceManager.class, e);
e.printStackTrace();
}
}
for (Map.Entry<String, File> resource : vertShaderResourcesToLoad.entrySet()) { //Register Vertex shaders
currentResource++;
LoadingScreen.infoMessage = resource.getKey();
LoadingScreen.progress = currentResource / (double) totalResources;
try {
registerShader(resource.getValue(), resource.getKey(), GL20.GL_VERTEX_SHADER); | } catch (IOException | LWJGLException | GLSLCompileException e) { | 0 |
hamadmarri/Biscuit | main/java/com/biscuit/commands/sprint/EditSprint.java | [
"public class ColorCodes {\n\n\t// with normal background\n\tpublic static final String RESET = \"\\u001B[0m\";\n\tpublic static final String BLACK = \"\\u001B[30;1m\";\n\tpublic static final String RED = \"\\u001B[31;1m\";\n\tpublic static final String GREEN = \"\\u001B[32;1m\";\n\tpublic static final String YELLOW = \"\\u001B[33;1m\";\n\tpublic static final String BLUE = \"\\u001B[34;1m\";\n\tpublic static final String PURPLE = \"\\u001B[35;1m\";\n\tpublic static final String CYAN = \"\\u001B[36;1m\";\n\tpublic static final String WHITE = \"\\u001B[37;1m\";\n\n\t// with black background\n\tpublic static final String B_RESET = \"\\u001B[0m\";\n\tpublic static final String B_BLACK = \"\\u001B[30;40;1m\";\n\tpublic static final String B_RED = \"\\u001B[31;40;1m\";\n\tpublic static final String B_GREEN = \"\\u001B[32;40;1m\";\n\tpublic static final String B_YELLOW = \"\\u001B[33;40;1m\";\n\tpublic static final String B_BLUE = \"\\u001B[34;40;1m\";\n\tpublic static final String B_PURPLE = \"\\u001B[35;40;1m\";\n\tpublic static final String B_CYAN = \"\\u001B[36;40;1m\";\n\tpublic static final String B_WHITE = \"\\u001B[37;40;1m\";\n\n}",
"public interface Command {\n\n\tboolean execute() throws IOException;\n}",
"public class DateCompleter {\n\n\tpublic static List<String> months = new ArrayList<String>(\n\t\t\tArrays.asList(\"jan\", \"feb\", \"march\", \"april\", \"may\", \"jun\", \"jul\", \"aug\", \"sep\", \"oct\", \"nov\", \"dec\"));\n\tprivate static List<String> days31 = new ArrayList<String>();\n\tprivate static String[] years = new String[5];\n\n\n\tpublic static List<Completer> getDateCompleter() {\n\t\tList<Completer> completers = new ArrayList<Completer>();\n\n\t\tCalendar cal = new GregorianCalendar();\n\t\tint startingYear = cal.get(Calendar.YEAR) - 2;\n\n\t\tfor (int i = 0; i < 31; i++) {\n\t\t\tdays31.add(String.valueOf(i + 1));\n\t\t}\n\n\t\tfor (int i = 0; i < years.length; i++) {\n\t\t\tyears[i] = String.valueOf(startingYear + i);\n\t\t}\n\n\t\tfor (int i = 0; i < months.size(); i++) {\n\t\t\t// for Feb 28 days\n\t\t\tif (i == 1) {\n\t\t\t\tcompleters.add(new ArgumentCompleter(new StringsCompleter(months.get(i)),\n\t\t\t\t\t\tnew StringsCompleter(days31.subList(0, 28)), new StringsCompleter(years), new NullCompleter()));\n\t\t\t}\n\t\t\t// for april, jun, sept, and nov\n\t\t\telse if (i == 4 || i == 6 || i == 9 || i == 11) {\n\t\t\t\tcompleters.add(new ArgumentCompleter(new StringsCompleter(months.get(i)),\n\t\t\t\t\t\tnew StringsCompleter(days31.subList(0, 29)), new StringsCompleter(years), new NullCompleter()));\n\t\t\t}\n\n\t\t\telse {\n\t\t\t\tcompleters.add(new ArgumentCompleter(new StringsCompleter(months.get(i)), new StringsCompleter(days31),\n\t\t\t\t\t\tnew StringsCompleter(years), new NullCompleter()));\n\t\t\t}\n\t\t}\n\n\t\treturn completers;\n\t}\n}",
"public class Sprint {\n\n\tpublic transient Project project;\n\n\t// info\n\tpublic String name;\n\tpublic String description;\n\tpublic Status state;\n\tpublic Date startDate;\n\tpublic Date dueDate;\n\tpublic int assignedEffort;\n\tpublic int velocity;\n\n\tpublic List<UserStory> userStories = new ArrayList<>();\n\tpublic List<Bug> bugs;\n\tpublic List<Test> tests;\n\n\t// Completed 0pt 0% ToDo 8pt\n\n\tpublic static String[] fields;\n\tpublic static String[] fieldsAsHeader;\n\n\tstatic {\n\t\tfields = new String[] { \"name\", \"description\", \"state\", \"start_date\", \"due_date\", \"assigned_effort\", \"velocity\" };\n\t\tfieldsAsHeader = new String[] { \"Name\", \"Description\", \"State\", \"Start Date\", \"Due Date\", \"Assigned Effort\", \"Velocity\" };\n\t}\n\n\tpublic void addUserStory(UserStory userStory) {\n\t\tthis.userStories.add(userStory);\n\t}\n\n\tpublic void save() {\n\t\tproject.save();\n\t}\n\n}",
"public enum Status {\n\n\tCREATED(0), OPEN(1), PLANNED(2), UNPLANNED(3), IN_PROGRESS(4), IN_TESTING(5), DONE(6), OVERDUE(7), REMOVED(8);\n\n\tprivate final int value;\n\tpublic static List<String> values = new ArrayList<>(\n\t\t\tArrays.asList(\"created\", \"open\", \"planned\", \"unplanned\", \"in_progress\", \"in_testing\", \"done\", \"overdue\", \"removed\"));\n\n\n\tprivate Status(int value) {\n\t\tthis.value = value;\n\t}\n\n\n\tpublic int getValue() {\n\t\treturn value;\n\t}\n\n\n\tpublic static String allStatus() {\n\t\tStringBuilder sb = new StringBuilder();\n\n\t\tfor (String s : values) {\n\t\t\tsb.append(s).append(\", \");\n\t\t}\n\n\t\treturn sb.substring(0, sb.length() - 2);\n\t}\n\n}",
"public class DateService {\n\n\tpublic static transient SimpleDateFormat dateFormat = new SimpleDateFormat(\"MMM. dd, yyyy\");\n\n\n\tpublic static boolean isSet(Date d) {\n\t\treturn (d.compareTo(new Date(0)) > 0);\n\t}\n\n\n\tpublic static String getDateAsString(Date d) {\n\t\tif (DateService.isSet(d)) {\n\t\t\treturn DateService.dateFormat.format(d);\n\t\t}\n\t\treturn \"Not set yet\";\n\t}\n\n}"
] | import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import com.biscuit.ColorCodes;
import com.biscuit.commands.Command;
import com.biscuit.factories.DateCompleter;
import com.biscuit.models.Sprint;
import com.biscuit.models.enums.Status;
import com.biscuit.models.services.DateService;
import jline.console.ConsoleReader;
import jline.console.completer.AggregateCompleter;
import jline.console.completer.ArgumentCompleter;
import jline.console.completer.Completer;
import jline.console.completer.NullCompleter;
import jline.console.completer.StringsCompleter; | package com.biscuit.commands.sprint;
public class EditSprint implements Command {
ConsoleReader reader = null;
Sprint s = new Sprint();
public EditSprint(ConsoleReader reader, Sprint s) {
super();
this.reader = reader;
this.s = s;
}
public boolean execute() throws IOException {
String prompt = reader.getPrompt();
setName();
setDescription();
setState();
setStartDate();
setDueDate();
setVelocity();
reader.setPrompt(prompt);
s.save();
return true;
}
private void setVelocity() throws IOException {
String prompt = ColorCodes.BLUE + "velocity:" + ColorCodes.YELLOW + "(hit Tab to see an example) "
+ ColorCodes.RESET;
String preload = String.valueOf(s.velocity);
String line;
Completer oldCompleter = (Completer) reader.getCompleters().toArray()[0];
Completer pointsCompleter = new ArgumentCompleter(new StringsCompleter("7", "10", "15", "20", "22"),
new NullCompleter());
reader.removeCompleter(oldCompleter);
reader.addCompleter(pointsCompleter);
reader.resetPromptLine(prompt, preload, 0);
reader.print("\r");
while ((line = reader.readLine()) != null) {
line = line.trim();
try {
s.velocity = Integer.valueOf(line);
break;
} catch (NumberFormatException e) {
System.out.println(ColorCodes.RED + "invalid value: must be an integer value!" + ColorCodes.RESET);
}
}
reader.removeCompleter(pointsCompleter);
reader.addCompleter(oldCompleter);
}
private void setDueDate() throws IOException {
String line;
Completer oldCompleter = (Completer) reader.getCompleters().toArray()[0];
| Completer dateCompleter = new AggregateCompleter(DateCompleter.getDateCompleter()); | 2 |
GitLqr/LQRBiliBlili | app/src/main/java/com/lqr/biliblili/mvp/model/LiveModel.java | [
"public interface Api {\n String LIVE_BASE_URL = \"http://api.live.bilibili.com/\";\n String RECOMMEND_BASE_URL = \"https://app.bilibili.com/\";\n String VIDEO_DETAIL_SUMMARY_BASE_URL = \"https://app.bilibili.com/\";\n String VIDEO_DETAIL_REPLY_BASE_URL = \"https://api.bilibili.com/\";\n\n // 没有登录的情况下,使用这个User-Agent\n String COMMON_UA_STR = \"Mozilla/5.0 BiliDroid/5.15.0 ([email protected])\";\n}",
"public interface LiveCache {\n\n // @Encrypt\n @LifeCache(duration = 2, timeUnit = TimeUnit.MINUTES)\n Observable<Reply<GetAllListData>> getLiveIndexList(Observable<GetAllListData> data, EvictProvider evictProvider);\n}",
"public interface LiveService {\n\n /**\n * 首页直播\n */\n @Headers({\"Domain-Name: live\"})\n @GET(\"/room/v1/AppIndex/getAllList?_device=android&_hwid=Pwc3BzUCOllgWW9eIl4i&appkey=1d8b6e7d45233436&build=515000&device=android&mobi_app=android&platform=android&scale=xhdpi&src=kuan&trace_id=20171019034900026&ts=1508399366&version=5.15.0.515000&sign=8fe2091c7683c86721da54690ab9fdbf\")\n Observable<GetAllListData> getLiveIndexList();\n}",
"public interface LiveContract {\n\n interface View extends IView {\n void setHeaderView(LiveMultiItemAdapter adapter);\n\n void setBanner(BGABanner.Adapter<ImageView, String> adapter, List<String> banners);\n\n void setRecyclerAdapter(LiveMultiItemAdapter adapter);\n\n void setFooterView(LiveMultiItemAdapter adapter);\n }\n\n interface Model extends IModel {\n Observable<GetAllListData> getLiveList(boolean update);\n\n List<LiveMultiItem> parseRecommendData(GetAllListData.DataBean getAllListData);\n\n List<LiveMultiItem> parsePartitions(GetAllListData.DataBean getAllListData);\n }\n}",
"public class LiveMultiItem implements MultiItemEntity {\n\n public static final int TITLE = 1;\n public static final int ITEM = 2;\n public static final int BANNER = 3;\n public static final int BOTTOM = 4;\n\n private int itemType;\n private int spanSize;\n private boolean isOdd;// 用于判断ITEM部分是左是右\n\n // TITLE\n private String titleIconSrc;\n private String titleName;// recommend_data_partition_name\n private int titleCount;// recommend_data_partition_count\n\n // ITEM\n private String itemCoverSrc;\n private String itemOwnerName;\n private String itemTitle;\n private String itemSubTitle;// area_v2_name\n private int itemOnline;\n\n // BANNER\n private String bannerCoverSrc;\n private String bannerTitle;\n\n // BOTTOM\n //\n private void setSpanSzieWithItemType(int itemType) {\n switch (itemType) {\n case TITLE:\n spanSize = 2;\n break;\n case ITEM:\n spanSize = 1;\n break;\n case BANNER:\n spanSize = 2;\n break;\n case BOTTOM:\n spanSize = 2;\n break;\n }\n }\n\n @Override\n public int getItemType() {\n return itemType;\n }\n\n public void setItemType(int itemType) {\n this.itemType = itemType;\n setSpanSzieWithItemType(itemType);\n }\n\n\n public int getSpanSize() {\n return spanSize;\n }\n\n public void setSpanSize(int spanSize) {\n this.spanSize = spanSize;\n }\n\n public boolean isOdd() {\n return isOdd;\n }\n\n public void setOdd(boolean odd) {\n isOdd = odd;\n }\n\n public String getTitleIconSrc() {\n return titleIconSrc;\n }\n\n public void setTitleIconSrc(String titleIconSrc) {\n this.titleIconSrc = titleIconSrc;\n }\n\n public String getTitleName() {\n return titleName;\n }\n\n public void setTitleName(String titleName) {\n this.titleName = titleName;\n }\n\n public int getTitleCount() {\n return titleCount;\n }\n\n public void setTitleCount(int titleCount) {\n this.titleCount = titleCount;\n }\n\n public String getItemCoverSrc() {\n return itemCoverSrc;\n }\n\n public void setItemCoverSrc(String itemCoverSrc) {\n this.itemCoverSrc = itemCoverSrc;\n }\n\n public String getItemOwnerName() {\n return itemOwnerName;\n }\n\n public void setItemOwnerName(String itemOwnerName) {\n this.itemOwnerName = itemOwnerName;\n }\n\n public String getItemTitle() {\n return itemTitle;\n }\n\n public void setItemTitle(String itemTitle) {\n this.itemTitle = itemTitle;\n }\n\n public String getItemSubTitle() {\n return itemSubTitle;\n }\n\n public void setItemSubTitle(String itemSubTitle) {\n this.itemSubTitle = itemSubTitle;\n }\n\n public int getItemOnline() {\n return itemOnline;\n }\n\n public void setItemOnline(int itemOnline) {\n this.itemOnline = itemOnline;\n }\n\n public String getBannerCoverSrc() {\n return bannerCoverSrc;\n }\n\n public void setBannerCoverSrc(String bannerCoverSrc) {\n this.bannerCoverSrc = bannerCoverSrc;\n }\n\n public String getBannerTitle() {\n return bannerTitle;\n }\n\n public void setBannerTitle(String bannerTitle) {\n this.bannerTitle = bannerTitle;\n }\n}"
] | import android.app.Application;
import com.google.gson.Gson;
import com.jess.arms.di.scope.FragmentScope;
import com.jess.arms.integration.IRepositoryManager;
import com.jess.arms.mvp.BaseModel;
import com.lqr.biliblili.app.data.api.Api;
import com.lqr.biliblili.app.data.api.cache.LiveCache;
import com.lqr.biliblili.app.data.api.service.LiveService;
import com.lqr.biliblili.app.data.entity.live.GetAllListData;
import com.lqr.biliblili.mvp.contract.LiveContract;
import com.lqr.biliblili.mvp.ui.adapter.entity.LiveMultiItem;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;
import io.rx_cache2.EvictProvider;
import me.jessyan.retrofiturlmanager.RetrofitUrlManager; | package com.lqr.biliblili.mvp.model;
@FragmentScope
public class LiveModel extends BaseModel implements LiveContract.Model {
private Gson mGson;
private Application mApplication;
@Inject
public LiveModel(IRepositoryManager repositoryManager, Gson gson, Application application) {
super(repositoryManager);
mGson = gson;
mApplication = application; | RetrofitUrlManager.getInstance().putDomain("live", Api.LIVE_BASE_URL); | 0 |
ykameshrao/spring-mvc-angular-js-hibernate-bootstrap-java-single-page-jwt-auth-rest-api-webapp-framework | src/main/java/yourwebproject2/controller/JobController.java | [
"@JsonInclude(JsonInclude.Include.NON_NULL)\npublic class APIResponse {\n public static final String API_RESPONSE = \"apiResponse\";\n Object result;\n String time;\n long code;\n\n public static class ExceptionAPIResponse extends APIResponse {\n Object details;\n\n public Object getDetails() {\n return details;\n }\n\n public void setDetails(Object details) {\n this.details = details;\n }\n }\n\n public Object getResult() {\n return result;\n }\n\n public void setResult(Object result) {\n this.result = result;\n }\n\n public String getTime() {\n return time;\n }\n\n public void setTime(String time) {\n this.time = time;\n }\n\n public long getCode() {\n return code;\n }\n\n public void setCode(long code) {\n this.code = code;\n }\n\n public static APIResponse toOkResponse(Object data) {\n return toAPIResponse(data, 200);\n }\n\n public static APIResponse toErrorResponse(Object data) {\n return toAPIResponse(data, 2001);\n }\n\n public static ExceptionAPIResponse toExceptionResponse(String result, Object details) {\n ExceptionAPIResponse response = new ExceptionAPIResponse();\n response.setResult(result);\n response.setDetails(details);\n response.setCode(2001);\n return response;\n }\n\n public APIResponse withModelAndView(ModelAndView modelAndView) {\n modelAndView.addObject(API_RESPONSE, this);\n return this;\n }\n\n public static APIResponse toAPIResponse(Object data, long code) {\n APIResponse response = new APIResponse();\n response.setResult(data);\n response.setCode(code);\n return response;\n }\n}",
"public abstract class BaseController {\n protected static final String JSON_API_CONTENT_HEADER = \"Content-type=application/json\";\n\n public String extractPostRequestBody(HttpServletRequest request) throws IOException {\n if (\"POST\".equalsIgnoreCase(request.getMethod())) {\n Scanner s = new Scanner(request.getInputStream(), \"UTF-8\").useDelimiter(\"\\\\A\");\n return s.hasNext() ? s.next() : \"\";\n }\n return \"\";\n }\n\n public JSONObject parseJSON(String object) {\n return new JSONObject(object);\n }\n\n public void decorateUserDTOWithCredsFromAuthHeader(String authHeader, UserDTO userDTO) {\n String[] basicAuth = authHeader.split(\" \");\n Validate.isTrue(basicAuth.length == 2, \"the auth header is not splittable with space\");\n Validate.isTrue(basicAuth[0].equalsIgnoreCase(\"basic\"), \"not basic auth: \"+basicAuth[0]);\n Validate.isTrue(Base64.isBase64(basicAuth[1].getBytes()), \"encoded value not base64\");\n\n String decodedAuthHeader = new String(Base64.decode(basicAuth[1].getBytes()));\n String[] creds = decodedAuthHeader.split(\":\");\n Validate.isTrue(creds.length == 2, \"the creds were not concatenated using ':', could not split the decoded header\");\n\n userDTO.setEmail(creds[0]);\n userDTO.setPassword(creds[1]);\n }\n}",
"public class JobDTO {\n String name;\n String metadataJsonString;\n String callbackURL;\n Long catId;\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getMetadataJsonString() {\n return metadataJsonString;\n }\n\n public void setMetadataJsonString(String metadataJsonString) {\n this.metadataJsonString = metadataJsonString;\n }\n\n public Long getCatId() {\n return catId;\n }\n\n public void setCatId(Long catId) {\n this.catId = catId;\n }\n\n public String getCallbackURL() {\n return callbackURL;\n }\n\n public void setCallbackURL(String callbackURL) {\n this.callbackURL = callbackURL;\n }\n\n @Override\n public String toString() {\n return \"JobDTO{\" +\n \"name='\" + name + '\\'' +\n \", metadataJsonString='\" + metadataJsonString + '\\'' +\n \", catId=\" + catId +\n \", callbackURL='\" + callbackURL + '\\'' +\n '}';\n }\n}",
"@Entity\n@Table(indexes = { @Index(name=\"name_idx\", columnList = \"name\", unique = true),\n @Index(name=\"priority_idx\", columnList = \"priority\"),\n @Index(name=\"parentCategory_idx\", columnList = \"parent_category\")})\npublic class Category extends JPAEntity<Long> {\n private String name;\n private Integer priority;\n private Category parentCategory;\n\n @NotNull @NotBlank\n @Column\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n @NotNull\n @Column\n public Integer getPriority() {\n return priority;\n }\n\n public void setPriority(Integer priority) {\n this.priority = priority;\n }\n\n @ManyToOne(fetch = FetchType.EAGER)\n public Category getParentCategory() {\n return parentCategory;\n }\n\n public void setParentCategory(Category parentCategory) {\n this.parentCategory = parentCategory;\n }\n\n @Override\n public String toString() {\n return \"Category{\" +\n \"name='\" + name + '\\'' +\n \", priority=\" + priority +\n \", parentCategory=\" + parentCategory +\n '}';\n }\n}",
"@Entity\n@Table(indexes = { @Index(name=\"name_idx\", columnList = \"name\", unique = true),\n @Index(name=\"status_idx\", columnList = \"status\"),\n @Index(name=\"category_idx\", columnList = \"category\")})\npublic class Job extends JPAEntity<Long> {\n public enum Status {\n NEW, EXECUTING, PRIORITIZED, FAILED, RETRYING, SUCCESSFUL\n }\n\n private String name;\n private String metadataJson;\n private String callbackUrl;\n private Date submitTime;\n private Status status;\n private Date scheduledTime;\n private Date completionTime;\n private Integer retryCount;\n private Category category;\n\n @NotNull @NotBlank\n @Column\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n @Column\n public String getCallbackUrl() {\n return callbackUrl;\n }\n\n public void setCallbackUrl(String callbackUrl) {\n this.callbackUrl = callbackUrl;\n }\n\n @Column\n public String getMetadataJson() {\n return metadataJson;\n }\n\n public void setMetadataJson(String metadataJson) {\n this.metadataJson = metadataJson;\n }\n\n @NotNull\n @Column\n public Date getSubmitTime() {\n return submitTime;\n }\n\n public void setSubmitTime(Date submitTime) {\n this.submitTime = submitTime;\n }\n\n @OneToOne(fetch = FetchType.EAGER)\n public Category getCategory() {\n return category;\n }\n\n public void setCategory(Category category) {\n this.category = category;\n }\n\n @NotNull\n @Column\n public Status getStatus() {\n return status;\n }\n\n public void setStatus(Status status) {\n this.status = status;\n }\n\n @Column\n public Date getScheduledTime() {\n return scheduledTime;\n }\n\n public void setScheduledTime(Date scheduledTime) {\n this.scheduledTime = scheduledTime;\n }\n\n @Column\n public Date getCompletionTime() {\n return completionTime;\n }\n\n public void setCompletionTime(Date completionTime) {\n this.completionTime = completionTime;\n }\n\n @Column\n public Integer getRetryCount() {\n return retryCount;\n }\n\n public void setRetryCount(Integer retryCount) {\n this.retryCount = retryCount;\n }\n\n @Override\n public String toString() {\n return \"Job{\" +\n \"name='\" + name + '\\'' +\n \", metadataJson='\" + metadataJson + '\\'' +\n \", callbackUrl='\" + callbackUrl + '\\'' +\n \", submitTime=\" + submitTime +\n \", status=\" + status +\n \", scheduledTime=\" + scheduledTime +\n \", completionTime=\" + completionTime +\n \", retryCount=\" + retryCount +\n \", category=\" + category +\n '}';\n }\n}",
"public interface CategoryService extends BaseService<Category, Long> {\n /**\n * Validates whether the given category already\n * exists in the system.\n *\n * @param categoryName\n *\n * @return\n */\n public boolean isCategoryPresent(String categoryName);\n\n /**\n * Validates whether the given category priority already\n * exists in the system.\n *\n * @param priorityId\n *\n * @return\n */\n public boolean isPriorityPresent(Integer priorityId);\n\n /**\n * Find category by name\n *\n * @param categoryName\n * @return\n */\n public Category findByCategoryName(String categoryName) throws NotFoundException;\n\n /**\n * Find sub categories by parent category\n *\n * @param parentCategory\n * @return\n */\n public List<Category> findSubCategories(Category parentCategory) throws NotFoundException;\n}",
"public interface JobService extends BaseService<Job, Long> {\n /**\n *\n * @param count\n * @return\n */\n public List<Job> fetchNewJobsToBeScheduledForExecutionPerPriority(int count);\n\n /**\n *\n * @param count\n * @return\n */\n public List<Job> fetchFailedJobsToBeScheduledForExecutionPerPriority(int count);\n\n /**\n *\n * @param count\n * @return\n */\n public List<Job> fetchNewJobsToBeScheduledForExecutionPerSubmissionTimePriority(int count);\n\n /**\n *\n * @param count\n * @return\n */\n public List<Job> fetchFailedJobsToBeScheduledForExecutionPerSubmissionTimePriority(int count);\n}"
] | import yourwebproject2.framework.api.APIResponse;
import yourwebproject2.framework.controller.BaseController;
import yourwebproject2.model.dto.JobDTO;
import yourwebproject2.model.entity.Category;
import yourwebproject2.model.entity.Job;
import yourwebproject2.service.CategoryService;
import yourwebproject2.service.JobService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.Date; | package yourwebproject2.controller;
/**
* Job submission and status APIs
*
* Created by Y.Kamesh on 8/2/2015.
*/
@Controller
@RequestMapping("job")
public class JobController extends BaseController {
private static Logger LOG = LoggerFactory.getLogger(JobController.class);
@Autowired
private JobService jobService;
@Autowired
private CategoryService categoryService;
/**
* Method to handle creation of the job by extracting the jobInfo json from
* POST body expected in the format - {"name":"job1", "metadataJsonString":"{}", "callbackUrl":"", "catId":1}
*
* @param jobDTO
* @return
* @throws Exception
*/
@RequestMapping(value = "/submit", method = RequestMethod.POST, headers = {JSON_API_CONTENT_HEADER})
public @ResponseBody | APIResponse submitJob(@RequestBody JobDTO jobDTO) throws Exception { | 2 |
tupilabs/tap4j | src/test/java/org/tap4j/parser/issueGitHub14/TestDiagnostics.java | [
"public interface TapConsumer {\n\n /**\n * Parses a TAP File.\n *\n * Note: this method only works if the {@code TapConsumer} was constructed\n * with an assumed character set encoding, <em>and</em> {@code file} really\n * is encoded in that assumed encoding.\n *\n * For a more flexible approach, the caller (who should know best about the\n * encoding of any given input file) should have already\n * wrapped the file in an {@link InputStreamReader}, and should pass that to\n * {@link #load(Readable)}.\n *\n * @param file TAP File.\n * @return TestSet\n * @throws TapConsumerException error reading\n */\n TestSet load(File file);\n\n /**\n * Parses a TAP Stream.\n *\n * @param tapStream TAP Stream\n * @return TestSet\n * @throws TapConsumerException error reading\n */\n TestSet load(Readable tapStream);\n\n /**\n * Parses a TAP Stream.\n *\n * @param tapStream TAP Stream\n * @return TestSet\n * @throws TapConsumerException error reading\n */\n TestSet load(String tapStream);\n\n /**\n * Returns the TestSet resulted from parsing a TAP File or TAP Stream.\n *\n * @return TestSet\n */\n TestSet getTestSet();\n\n /**\n * Returns the Parser used in the Consumer.\n *\n * @return Parser\n */\n Parser getParser();\n\n}",
"public final class TapConsumerFactory {\n\n /**\n * Default constructor.\n */\n private TapConsumerFactory() {\n super();\n }\n\n /**\n * Produces a new TAP version 13 Consumer.\n *\n * @return TAP Consumer.\n */\n public static TapConsumer makeTap13Consumer() {\n return new TapConsumerImpl();\n }\n\n /**\n * Produces a new TAP version 13 Consumer with YAML diagnostics.\n *\n * @return TAP Consumer with YAML support.\n */\n public static TapConsumer makeTap13YamlConsumer() {\n return new TapConsumerImpl(new Tap13Parser(true));\n }\n\n /**\n * Produces a new TAP version 13 Consumer with YAML diagnostics.\n *\n * @return TAP Consumer with YAML support.\n */\n public static TapConsumer makeTap13YamlConsumerWithoutSubtests() {\n return new TapConsumerImpl(new Tap13Parser(false));\n }\n\n}",
"public class TestResult extends TapResult {\n\n /**\n * Serial Version UID.\n */\n private static final long serialVersionUID = -2735372334488828166L;\n\n /**\n * Test Status (OK, NOT OK).\n */\n private StatusValues status;\n\n /**\n * Test Number.\n */\n private Integer testNumber;\n\n /**\n * Description of the test.\n */\n private String description;\n\n /**\n * Directive of the test (TO DO, SKIP).\n */\n private Directive directive;\n\n /**\n * Child subtest.\n */\n private TestSet subtest;\n\n /**\n * Comment.\n */\n private List<Comment> comments;\n\n /**\n * Default constructor.\n */\n public TestResult() {\n super();\n this.status = StatusValues.NOT_OK;\n this.testNumber = -1;\n this.subtest = null;\n this.comments = new LinkedList<>();\n }\n\n /**\n * Constructor with parameter.\n *\n * @param testStatus Status of the test.\n * @param testNumber Number of the test.\n */\n public TestResult(StatusValues testStatus, Integer testNumber) {\n super();\n this.status = testStatus;\n this.testNumber = testNumber;\n this.comments = new LinkedList<>();\n }\n\n /**\n * @return Status of the test.\n */\n public StatusValues getStatus() {\n return this.status;\n }\n\n /**\n * @param status Status of the test.\n */\n public void setStatus(StatusValues status) {\n this.status = status;\n }\n\n /**\n * @return Test Number.\n */\n public Integer getTestNumber() {\n return this.testNumber;\n }\n\n /**\n * @param testNumber Test Number.\n */\n public void setTestNumber(Integer testNumber) {\n this.testNumber = testNumber;\n }\n\n /**\n * @return Test description.\n */\n public String getDescription() {\n return this.description;\n }\n\n /**\n * @param description Test description.\n */\n public void setDescription(String description) {\n this.description = description;\n }\n\n /**\n * @return Optional Directive.\n */\n public Directive getDirective() {\n return this.directive;\n }\n\n /**\n * @param directive Optional Directive.\n */\n public void setDirective(Directive directive) {\n this.directive = directive;\n }\n\n /**\n * @return the subtest\n */\n public TestSet getSubtest() {\n return subtest;\n }\n\n /**\n * @param subtest the subtest to set\n */\n public void setSubtest(TestSet subtest) {\n this.subtest = subtest;\n }\n\n /**\n * @return The comments for this Test Result.\n */\n public List<Comment> getComments() {\n return this.comments;\n }\n\n /**\n * @param comments list of comments for this Test Result.\n */\n public void setComments(List<Comment> comments) {\n this.comments = comments;\n }\n\n /**\n * Adds a new comment to this Test Result.\n *\n * @param comment comment for this Test Result.\n */\n public void addComment(Comment comment) {\n this.comments.add(comment);\n }\n\n}",
"public class TestSet implements Serializable {\n\n /**\n * Serial Version UID.\n */\n private static final long serialVersionUID = 114777557084672201L;\n\n /**\n * TAP Header.\n */\n private Header header;\n\n /**\n * TAP Plan.\n */\n private Plan plan;\n\n /**\n * List of TAP Lines.\n */\n private final List<TapElement> tapLines = new LinkedList<>();\n\n /**\n * List of Test Results.\n */\n private final List<TestResult> testResults = new LinkedList<>();\n\n /**\n * List of Bail Outs.\n */\n private final List<BailOut> bailOuts = new LinkedList<>();\n\n /**\n * List of comments.\n */\n private final List<Comment> comments = new LinkedList<>();\n\n /**\n * TAP Footer.\n */\n private Footer footer;\n\n /**\n * Default constructor.\n */\n public TestSet() {\n super();\n }\n\n /**\n * @return TAP Header.\n */\n public Header getHeader() {\n return this.header;\n }\n\n /**\n * @param header TAP Header.\n */\n public void setHeader(Header header) {\n this.header = header;\n }\n\n /**\n * @return TAP Plan.\n */\n public Plan getPlan() {\n return this.plan;\n }\n\n /**\n * @param plan TAP Plan.\n */\n public void setPlan(Plan plan) {\n this.plan = plan;\n }\n\n /**\n * @return List of TAP Lines. These lines may be either a TestResult or a\n * BailOut.\n */\n public List<TapElement> getTapLines() {\n return tapLines;\n }\n\n /**\n * @return List of Test Results.\n */\n public List<TestResult> getTestResults() {\n return this.testResults;\n }\n\n /**\n * @return Next test number.\n */\n public int getNextTestNumber() {\n return this.testResults.size() + 1;\n }\n\n /**\n * @return List of Bail Outs.\n */\n public List<BailOut> getBailOuts() {\n return this.bailOuts;\n }\n\n /**\n * @return List of Comments.\n */\n public List<Comment> getComments() {\n return this.comments;\n }\n\n /**\n * Adds a new TAP Line.\n *\n * @param tapLine TAP Line.\n * @return True if the TAP Line could be added into the list successfully.\n */\n public boolean addTapLine(TapResult tapLine) {\n return this.tapLines.add(tapLine);\n }\n\n /**\n * Adds a TestResult into the list of TestResults. If the TestResult Test\n * Number is null or less than or equals to zero it is changed to the next\n * Test Number in the sequence.\n *\n * @param testResult TAP TestResult.\n * @return Whether could add to TestResult list or not.\n */\n public boolean addTestResult(TestResult testResult) {\n if (testResult.getTestNumber() == null\n || testResult.getTestNumber() <= 0) {\n testResult.setTestNumber(this.testResults.size() + 1);\n }\n this.testResults.add(testResult);\n return this.tapLines.add(testResult);\n }\n\n /**\n * @param bailOut Bail Out.\n * @return Whether could add to BailOut list or not.\n */\n public boolean addBailOut(BailOut bailOut) {\n this.bailOuts.add(bailOut);\n return this.tapLines.add(bailOut);\n }\n\n /**\n * @param comment Comment. Whether could add to Comment list or not.\n * @return True if could successfully add the comment.\n */\n public boolean addComment(Comment comment) {\n comments.add(comment);\n return tapLines.add(comment);\n }\n\n /**\n * Removes a TAP Line from the list.\n *\n * @param tapLine TAP Line object.\n * @return True if could successfully remove the TAP Line from the list.\n */\n protected boolean removeTapLine(TapResult tapLine) {\n return this.tapLines.remove(tapLine);\n }\n\n /**\n * Removes a Test Result from the list.\n *\n * @param testResult Test Result.\n * @return True if could successfully remove the Test Result from the list.\n */\n public boolean removeTestResult(TestResult testResult) {\n boolean flag = false;\n if (this.tapLines.remove(testResult)) {\n this.testResults.remove(testResult);\n flag = true;\n }\n return flag;\n }\n\n /**\n * Removes a Bail Out from the list.\n *\n * @param bailOut Bail Out object.\n * @return True if could successfully remove the Bail Out from the list.\n */\n public boolean removeBailOut(BailOut bailOut) {\n boolean flag = false;\n if (this.tapLines.remove(bailOut)) {\n this.bailOuts.remove(bailOut);\n flag = true;\n }\n return flag;\n }\n\n /**\n * Removes a Comment from the list.\n *\n * @param comment Comment.\n * @return True if could successfully remove the Comment from the list.\n */\n public boolean removeComment(Comment comment) {\n boolean flag = false;\n if (this.tapLines.remove(comment)) {\n this.comments.remove(comment);\n flag = true;\n }\n return flag;\n }\n\n /**\n * @return Number of TAP Lines. It includes Test Results, Bail Outs and\n * Comments (the footer is not included).\n */\n public int getNumberOfTapLines() {\n return this.tapLines.size();\n }\n\n /**\n * @return Number of Test Results.\n */\n public int getNumberOfTestResults() {\n return this.testResults.size();\n }\n\n /**\n * @return Number of Bail Outs.\n */\n public int getNumberOfBailOuts() {\n return this.bailOuts.size();\n }\n\n /**\n * @return Number of Comments.\n */\n public int getNumberOfComments() {\n return this.comments.size();\n }\n\n /**\n * @return Footer\n */\n public Footer getFooter() {\n return this.footer;\n }\n\n /**\n * @param footer Footer\n */\n public void setFooter(Footer footer) {\n this.footer = footer;\n }\n\n /**\n * @return <code>true</code> if it has any Bail Out statement,\n * <code>false</code> otherwise.\n */\n public boolean hasBailOut() {\n boolean isBailOut = false;\n\n for (TapElement tapLine : tapLines) {\n if (tapLine instanceof BailOut) {\n isBailOut = true;\n break;\n }\n }\n\n return isBailOut;\n }\n\n /**\n * @return <code>true</code> if it contains OK status, <code>false</code>\n * otherwise.\n */\n public Boolean containsOk() {\n boolean containsOk = false;\n\n for (TestResult testResult : this.testResults) {\n if (testResult.getStatus().equals(StatusValues.OK)) {\n containsOk = true;\n break;\n }\n }\n\n return containsOk;\n }\n\n /**\n * @return <code>true</code> if it contains NOT OK status,\n * <code>false</code> otherwise.\n */\n public Boolean containsNotOk() {\n boolean containsNotOk = false;\n\n for (TestResult testResult : this.testResults) {\n if (testResult.getStatus().equals(StatusValues.NOT_OK)) {\n containsNotOk = true;\n break;\n }\n }\n\n return containsNotOk;\n }\n\n /**\n * @return <code>true</code> if it contains BAIL OUT!, <code>false</code>\n * otherwise.\n */\n public Boolean containsBailOut() {\n return this.bailOuts.size() > 0;\n }\n\n /**\n * @param testNumber test result number.\n * @return Test Result with given number.\n */\n public TestResult getTestResult(Integer testNumber) {\n TestResult foundTestResult = null;\n for (TestResult testResult : this.testResults) {\n if (testResult.getTestNumber().equals(testNumber)) {\n foundTestResult = testResult;\n break;\n }\n }\n return foundTestResult;\n }\n\n}",
"public class TestDirectives {\n\n private TapConsumer consumer;\n\n @Test\n public void testSkipDirective() {\n consumer = TapConsumerFactory.makeTap13YamlConsumer();\n\n TestSet testSet = consumer.load(new File(TestDirectives.class\n .getResource(\"/org/tap4j/parser/issue3406964/ihaveskips.tap\")\n .getFile()));\n assertNotNull(\"Empty Test Set\", testSet);\n assertEquals(\"Wrong number of tests\", 3, testSet.getTestResults().size());\n\n TestResult tr1 = testSet.getTestResult(1);\n Directive directive = tr1.getDirective();\n\n assertSame(directive.getDirectiveValue(), DirectiveValues.SKIP);\n\n TestResult tr2 = testSet.getTestResult(2);\n directive = tr2.getDirective();\n\n assertSame(directive.getDirectiveValue(), DirectiveValues.SKIP);\n assertEquals(directive.getReason(), \"me too\");\n assertEquals(tr2.getDescription(), \"- Wrong version in path \");\n\n TestResult tr3 = testSet.getTestResult(3);\n directive = tr3.getDirective();\n\n assertSame(directive.getDirectiveValue(), DirectiveValues.SKIP);\n assertEquals(directive.getReason(), \"well, then...\");\n }\n\n @Test\n public void testTodoDirective() {\n consumer = TapConsumerFactory.makeTap13YamlConsumer();\n\n TestSet testSet = consumer.load(new File(TestDirectives.class\n .getResource(\"/org/tap4j/parser/issue3406964/ihavetodoes.tap\")\n .getFile()));\n assertNotNull(\"Empty Test Set\", testSet);\n assertEquals(\"Wrong number of tests\", 2, testSet.getTestResults().size());\n\n TestResult tr1 = testSet.getTestResult(1);\n Directive directive = tr1.getDirective();\n\n assertSame(directive.getDirectiveValue(), DirectiveValues.TODO);\n\n TestResult tr2 = testSet.getTestResult(2);\n directive = tr2.getDirective();\n\n assertSame(directive.getDirectiveValue(), DirectiveValues.TODO);\n assertEquals(directive.getReason(), \"configure tail\");\n assertEquals(tr2.getDescription(), \"\");\n\n }\n\n}"
] | import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.File;
import org.junit.Test;
import org.tap4j.consumer.TapConsumer;
import org.tap4j.consumer.TapConsumerFactory;
import org.tap4j.model.TestResult;
import org.tap4j.model.TestSet;
import org.tap4j.parser.issue3406964.TestDirectives; | package org.tap4j.parser.issueGitHub14;
/**
* Diagnostics are added to all test cases, after one with diagnostics was found.
*
* @since 4.0.3
*/
public class TestDiagnostics {
@Test
public void testDiagnostics() {
TapConsumer tapConsumer = TapConsumerFactory.makeTap13YamlConsumer();
TestSet testSet = tapConsumer.load(new File(TestDirectives.class
.getResource("/org/tap4j/parser/issueGitHub14/issue-14-tap-stream.tap")
.getFile()));
| for (TestResult tr : testSet.getTestResults()) { | 2 |
Fabric3/spring-samples | apps/bigbank/bigbank-client/src/main/java/org/fabric3/samples/bigbank/client/ws/LoanServiceClient.java | [
"@XmlAccessorType(XmlAccessType.FIELD)\n@XmlType(name = \"address\", propOrder = {\n \"city\",\n \"state\",\n \"street\",\n \"zip\"\n})\npublic class Address {\n\n protected String city;\n protected String state;\n protected String street;\n protected int zip;\n\n /**\n * Gets the value of the city property.\n *\n * @return possible object is {@link String }\n */\n public String getCity() {\n return city;\n }\n\n /**\n * Sets the value of the city property.\n *\n * @param value allowed object is {@link String }\n */\n public void setCity(String value) {\n this.city = value;\n }\n\n /**\n * Gets the value of the state property.\n *\n * @return possible object is {@link String }\n */\n public String getState() {\n return state;\n }\n\n /**\n * Sets the value of the state property.\n *\n * @param value allowed object is {@link String }\n */\n public void setState(String value) {\n this.state = value;\n }\n\n /**\n * Gets the value of the street property.\n *\n * @return possible object is {@link String }\n */\n public String getStreet() {\n return street;\n }\n\n /**\n * Sets the value of the street property.\n *\n * @param value allowed object is {@link String }\n */\n public void setStreet(String value) {\n this.street = value;\n }\n\n /**\n * Gets the value of the zip property.\n */\n public int getZip() {\n return zip;\n }\n\n /**\n * Sets the value of the zip property.\n */\n public void setZip(int value) {\n this.zip = value;\n }\n\n}",
"@XmlAccessorType(XmlAccessType.FIELD)\n@XmlType(name = \"loanApplication\", propOrder = {\n \"options\",\n \"status\"\n})\npublic class LoanApplication {\n\n @XmlElement(nillable = true)\n protected List<LoanOption> options;\n protected int status;\n\n /**\n * Gets the value of the options property.\n * <p/>\n * <p/>\n * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to the returned list will be\n * present inside the JAXB object. This is why there is not a <CODE>set</CODE> method for the options property.\n * <p/>\n * <p/>\n * For example, to add a new item, do as follows:\n * <pre>\n * getOptions().add(newItem);\n * </pre>\n * <p/>\n * <p/>\n * <p/>\n * Objects of the following type(s) are allowed in the list {@link LoanOption }\n */\n public List<LoanOption> getOptions() {\n if (options == null) {\n options = new ArrayList<LoanOption>();\n }\n return this.options;\n }\n\n /**\n * Gets the value of the status property.\n */\n public int getStatus() {\n return status;\n }\n\n /**\n * Sets the value of the status property.\n */\n public void setStatus(int value) {\n this.status = value;\n }\n\n}",
"@XmlAccessorType(XmlAccessType.FIELD)\n@XmlType(name = \"loanOption\", propOrder = {\n \"apr\",\n \"rate\",\n \"type\"\n})\npublic class LoanOption {\n\n protected float apr;\n protected float rate;\n protected String type;\n\n /**\n * Gets the value of the apr property.\n */\n public float getApr() {\n return apr;\n }\n\n /**\n * Sets the value of the apr property.\n */\n public void setApr(float value) {\n this.apr = value;\n }\n\n /**\n * Gets the value of the rate property.\n */\n public float getRate() {\n return rate;\n }\n\n /**\n * Sets the value of the rate property.\n */\n public void setRate(float value) {\n this.rate = value;\n }\n\n /**\n * Gets the value of the type property.\n *\n * @return possible object is {@link String }\n */\n public String getType() {\n return type;\n }\n\n /**\n * Sets the value of the type property.\n *\n * @param value allowed object is {@link String }\n */\n public void setType(String value) {\n this.type = value;\n }\n\n}",
"@XmlAccessorType(XmlAccessType.FIELD)\n@XmlType(name = \"loanRequest\", propOrder = {\n \"amount\",\n \"downPayment\",\n \"email\",\n \"propertyAddress\",\n \"ssn\"\n})\npublic class LoanRequest {\n\n protected double amount;\n protected double downPayment;\n protected String email;\n protected Address propertyAddress;\n @XmlElement(name = \"SSN\")\n protected String ssn;\n\n /**\n * Gets the value of the amount property.\n */\n public double getAmount() {\n return amount;\n }\n\n /**\n * Sets the value of the amount property.\n */\n public void setAmount(double value) {\n this.amount = value;\n }\n\n /**\n * Gets the value of the downPayment property.\n */\n public double getDownPayment() {\n return downPayment;\n }\n\n /**\n * Sets the value of the downPayment property.\n */\n public void setDownPayment(double value) {\n this.downPayment = value;\n }\n\n /**\n * Gets the value of the email property.\n *\n * @return possible object is {@link String }\n */\n public String getEmail() {\n return email;\n }\n\n /**\n * Sets the value of the email property.\n *\n * @param value allowed object is {@link String }\n */\n public void setEmail(String value) {\n this.email = value;\n }\n\n /**\n * Gets the value of the propertyAddress property.\n *\n * @return possible object is {@link Address }\n */\n public Address getPropertyAddress() {\n return propertyAddress;\n }\n\n /**\n * Sets the value of the propertyAddress property.\n *\n * @param value allowed object is {@link Address }\n */\n public void setPropertyAddress(Address value) {\n this.propertyAddress = value;\n }\n\n /**\n * Gets the value of the ssn property.\n *\n * @return possible object is {@link String }\n */\n public String getSSN() {\n return ssn;\n }\n\n /**\n * Sets the value of the ssn property.\n *\n * @param value allowed object is {@link String }\n */\n public void setSSN(String value) {\n this.ssn = value;\n }\n\n}",
"@WebService(name = \"LoanService\", targetNamespace = \"http://loan.api.bigbank.samples.fabric3.org/\")\n@XmlSeeAlso({\n ObjectFactory.class\n})\npublic interface LoanService {\n\n\n /**\n * @param arg0\n */\n @WebMethod\n @RequestWrapper(localName = \"accept\",\n targetNamespace = \"http://loan.api.bigbank.samples.fabric3.org/\",\n className = \"org.fabric3.samples.bigbank.client.ws.loan.Accept\")\n @ResponseWrapper(localName = \"acceptResponse\",\n targetNamespace = \"http://loan.api.bigbank.samples.fabric3.org/\",\n className = \"org.fabric3.samples.bigbank.client.ws.loan.AcceptResponse\")\n public void accept(\n @WebParam(name = \"arg0\", targetNamespace = \"\")\n OptionSelection arg0);\n\n /**\n * @param arg0\n * @return returns org.fabric3.samples.bigbank.client.ws.loan.LoanApplication\n */\n @WebMethod\n @WebResult(targetNamespace = \"\")\n @RequestWrapper(localName = \"retrieve\",\n targetNamespace = \"http://loan.api.bigbank.samples.fabric3.org/\",\n className = \"org.fabric3.samples.bigbank.client.ws.loan.Retrieve\")\n @ResponseWrapper(localName = \"retrieveResponse\",\n targetNamespace = \"http://loan.api.bigbank.samples.fabric3.org/\",\n className = \"org.fabric3.samples.bigbank.client.ws.loan.RetrieveResponse\")\n public LoanApplication retrieve(\n @WebParam(name = \"arg0\", targetNamespace = \"\")\n long arg0);\n\n /**\n * @param arg0\n * @return returns long\n */\n @WebMethod\n @WebResult(targetNamespace = \"\")\n @RequestWrapper(localName = \"apply\",\n targetNamespace = \"http://loan.api.bigbank.samples.fabric3.org/\",\n className = \"org.fabric3.samples.bigbank.client.ws.loan.Apply\")\n @ResponseWrapper(localName = \"applyResponse\",\n targetNamespace = \"http://loan.api.bigbank.samples.fabric3.org/\",\n className = \"org.fabric3.samples.bigbank.client.ws.loan.ApplyResponse\")\n public long apply(\n @WebParam(name = \"arg0\", targetNamespace = \"\")\n LoanRequest arg0);\n\n /**\n * @param arg0\n */\n @WebMethod\n @RequestWrapper(localName = \"decline\",\n targetNamespace = \"http://loan.api.bigbank.samples.fabric3.org/\",\n className = \"org.fabric3.samples.bigbank.client.ws.loan.Decline\")\n @ResponseWrapper(localName = \"declineResponse\",\n targetNamespace = \"http://loan.api.bigbank.samples.fabric3.org/\",\n className = \"org.fabric3.samples.bigbank.client.ws.loan.DeclineResponse\")\n public void decline(\n @WebParam(name = \"arg0\", targetNamespace = \"\")\n long arg0);\n\n}",
"@WebServiceClient(name = \"LoanServiceService\",\n targetNamespace = \"http://loan.api.bigbank.samples.fabric3.org/\",\n wsdlLocation = \"http://localhost:8181/loanService?wsdl\")\npublic class LoanServiceService\n extends Service {\n\n private final static URL LOANSERVICESERVICE_WSDL_LOCATION;\n private final static Logger logger = Logger.getLogger(org.fabric3.samples.bigbank.client.ws.loan.LoanServiceService.class.getName());\n\n static {\n URL url = null;\n try {\n URL baseUrl;\n baseUrl = org.fabric3.samples.bigbank.client.ws.loan.LoanServiceService.class.getResource(\".\");\n url = new URL(baseUrl, \"http://localhost:8181/loanService?wsdl\");\n } catch (MalformedURLException e) {\n logger.warning(\"Failed to create URL for the wsdl Location: 'http://localhost:8181/loanService?wsdl', retrying as a local file\");\n logger.warning(e.getMessage());\n }\n LOANSERVICESERVICE_WSDL_LOCATION = url;\n }\n\n public LoanServiceService(URL wsdlLocation, QName serviceName) {\n super(wsdlLocation, serviceName);\n }\n\n public LoanServiceService() {\n super(LOANSERVICESERVICE_WSDL_LOCATION, new QName(\"http://loan.api.bigbank.samples.fabric3.org/\", \"LoanServiceService\"));\n }\n\n /**\n * @return returns LoanService\n */\n @WebEndpoint(name = \"LoanServicePort\")\n public LoanService getLoanServicePort() {\n return super.getPort(new QName(\"http://loan.api.bigbank.samples.fabric3.org/\", \"LoanServicePort\"), LoanService.class);\n }\n\n /**\n * @param features A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the\n * <code>features</code> parameter will have their default values.\n * @return returns LoanService\n */\n @WebEndpoint(name = \"LoanServicePort\")\n public LoanService getLoanServicePort(WebServiceFeature... features) {\n return super.getPort(new QName(\"http://loan.api.bigbank.samples.fabric3.org/\", \"LoanServicePort\"), LoanService.class, features);\n }\n\n}",
"@XmlAccessorType(XmlAccessType.FIELD)\n@XmlType(name = \"optionSelection\", propOrder = {\n \"id\",\n \"type\"\n})\npublic class OptionSelection {\n\n protected long id;\n protected String type;\n\n /**\n * Gets the value of the id property.\n */\n public long getId() {\n return id;\n }\n\n /**\n * Sets the value of the id property.\n */\n public void setId(long value) {\n this.id = value;\n }\n\n /**\n * Gets the value of the type property.\n *\n * @return possible object is {@link String }\n */\n public String getType() {\n return type;\n }\n\n /**\n * Sets the value of the type property.\n *\n * @param value allowed object is {@link String }\n */\n public void setType(String value) {\n this.type = value;\n }\n\n}"
] | import javax.xml.namespace.QName;
import java.net.URL;
import java.util.UUID;
import org.fabric3.samples.bigbank.client.ws.loan.Address;
import org.fabric3.samples.bigbank.client.ws.loan.LoanApplication;
import org.fabric3.samples.bigbank.client.ws.loan.LoanOption;
import org.fabric3.samples.bigbank.client.ws.loan.LoanRequest;
import org.fabric3.samples.bigbank.client.ws.loan.LoanService;
import org.fabric3.samples.bigbank.client.ws.loan.LoanServiceService;
import org.fabric3.samples.bigbank.client.ws.loan.OptionSelection; | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.fabric3.samples.bigbank.client.ws;
/**
* Demonstrates interacting with the BigBank Loan Service via web services. This client would typically be a part of a third-party system which interacted with
* BigBank.
* <p/>
* Note the URL needs to be changed depending on the runtime the application is deployed to.
*/
public class LoanServiceClient {
public static void main(String[] args) throws Exception {
// Note you must change the port on the URL when loan service deployed in the cluster without a load-balancer on localhost
// Zone 1 port: 8182
URL url = new URL("http://localhost:8180/loanService?wsdl");
// URL when loan service deployed to WebLogic without a load-balancer and a Managed server set to port 7003 on localhost
// URL url = new URL("http://localhost:7003/loanService?wsdl");
QName name = new QName("http://loan.api.bigbank.samples.fabric3.org/", "LoanServiceService");
LoanServiceService endpoint = new LoanServiceService(url, name);
LoanService loanService = endpoint.getLoanServicePort();
// apply for a loan
LoanRequest request = new LoanRequest();
request.setAmount(300000);
request.setDownPayment(15000);
request.setEmail("[email protected]");
request.setSSN(UUID.randomUUID().toString());
Address address = new Address();
address.setCity("San Francisco");
address.setState("CA");
address.setStreet("123 Kearney");
address.setZip(94110);
request.setPropertyAddress(address);
System.out.println("Submitting loan application...");
long id = loanService.apply(request);
System.out.println("\nLoan application id is: " + id);
LoanApplication application = loanService.retrieve(id);
System.out.println("\nLoan options are: ");
for (LoanOption option : application.getOptions()) {
System.out.println(option.getType() + " " + option.getRate() + "% " + option.getApr() + " apr");
} | OptionSelection selection = new OptionSelection(); | 6 |
commonsguy/cwac-netsecurity | netsecurity/src/androidTest/java/com/commonsware/cwac/netsecurity/test/OkHttp3MemorizationTests.java | [
"public class CertificateNotMemorizedException extends MemorizationException {\n CertificateNotMemorizedException(X509Certificate[] chain, String host) {\n super(chain, host);\n }\n}",
"public class MemorizingTrustManager implements X509Extensions {\n private final File workingDir;\n private final char[] storePassword;\n private final String storeType;\n private final boolean noTOFU;\n private final LruCache<String, MemorizingStore> stores;\n private final DomainMatchRule domainMatchRule;\n private final boolean onlySingleItemChains;\n\n private MemorizingTrustManager(File workingDir, char[] storePassword,\n String storeType, boolean noTOFU,\n int cacheSize, DomainMatchRule domainMatchRule,\n boolean onlySingleItemChains) {\n this.workingDir=workingDir;\n this.storePassword=storePassword;\n this.storeType=storeType;\n this.noTOFU=noTOFU;\n this.stores=new LruCache<>(cacheSize);\n this.domainMatchRule=domainMatchRule;\n this.onlySingleItemChains=onlySingleItemChains;\n }\n\n /*\n * {@inheritDoc}\n */\n @Override\n public void checkClientTrusted(X509Certificate[] chain,\n String authType)\n throws CertificateException {\n throw new UnsupportedOperationException(\"Client checks not supported\");\n }\n\n /*\n * {@inheritDoc}\n */\n @Override\n public void checkServerTrusted(X509Certificate[] chain,\n String authType)\n throws CertificateException {\n throw new IllegalStateException(\"Must use three-parameter checkServerTrusted()\");\n }\n\n /*\n * {@inheritDoc}\n */\n @Override\n public X509Certificate[] getAcceptedIssuers() {\n return(new X509Certificate[0]);\n }\n\n /*\n * {@inheritDoc}\n */\n @Override\n public List<X509Certificate> checkServerTrusted(\n X509Certificate[] chain, String authType, String host)\n throws CertificateException {\n\n if ((!onlySingleItemChains || chain.length==1) &&\n (domainMatchRule==null || domainMatchRule.matches(host))) {\n try {\n getStoreForHost(host).checkServerTrusted(chain, authType);\n }\n catch (Exception e) {\n if (e instanceof CertificateNotMemorizedException ||\n e instanceof MemorizationMismatchException) {\n throw (CertificateException)e;\n }\n else {\n throw new CertificateException(\"Exception setting up memoization\", e);\n }\n }\n }\n\n return(Arrays.asList(chain));\n }\n\n /*\n * {@inheritDoc}\n */\n @Override\n public boolean isUserAddedCertificate(X509Certificate cert) {\n return(false);\n }\n\n /**\n * If you catch an SSLHandshakeException when performing\n * HTTPS I/O, and its getCause() is a\n * CertificateNotMemorizedException, then you know that\n * you configured certificate memorization and the SSL\n * certificate for your request was not recognized.\n *\n * If the user agrees that your app should use the SSL\n * certificate forever (or until you clear it), call\n * this method, supplying the CertificateNotMemorizedException.\n * Note that this will perform disk I/O and therefore\n * should be done on a background thread.\n *\n * @param ex exception with details of the certificate to be memorized\n * @throws Exception if there is a problem in memorizing the certificate\n */\n public void memorize(MemorizationException ex)\n throws Exception {\n getStoreForHost(ex.host).memorize(ex.chain);\n }\n\n /**\n * If you catch an SSLHandshakeException when performing\n * HTTPS I/O, and its getCause() is a\n * CertificateNotMemorizedException, then you know that\n * you configured certificate memorization and the SSL\n * certificate for your request was not recognized.\n *\n * If the user agrees that your app should use the SSL\n * certificate for the lifetime of this process only, but\n * not retain it beyond that, call this method,\n * supplying the CertificateNotMemorizedException. Once\n * your process is terminated, this cached certificate is\n * lost, and you will get a CertificateNotMemorizedException\n * again later on. Also, this class only caches a certain\n * number of domains' worth of certificates, so if you are\n * hitting a wide range of sites, the certificate may be lost.\n *\n * @param ex exception with details of the certificate to be memoized\n */\n synchronized public void memorizeForNow(MemorizationException ex)\n throws Exception {\n getStoreForHost(ex.host).memorizeForNow(ex.chain);\n }\n\n /**\n * Clears the transient key store used by memorizeForNow(),\n * and optionally clears the persistent key store used by\n * memorize().\n *\n * Note that some caching HTTP clients (e.g., OkHttp) may\n * have live SSLSession objects that they reuse. In that\n * case, the effects of this method will not be seen until\n * those SSLSession objects are purged (e.g., you create\n * a fresh OkHttpClient).\n *\n * @param host host whose stores should be cleared\n * @param clearPersistent\n * true to clear both key stores, false to clear\n * only the transient one\n */\n public void clear(String host, boolean clearPersistent)\n throws Exception {\n getStoreForHost(host).clear(clearPersistent);\n }\n\n /**\n * Clears details for all domains.\n *\n * Note that some caching HTTP clients (e.g., OkHttp) may\n * have live SSLSession objects that they reuse. In that\n * case, the effects of this method will not be seen until\n * those SSLSession objects are purged (e.g., you create\n * a fresh OkHttpClient).\n *\n * @param clearPersistent true to clear both memorize() and\n * memorizeForNow() data; false to just\n * clear memorizeForNow()\n * @throws Exception\n */\n synchronized public void clearAll(boolean clearPersistent) throws Exception {\n for (String host : stores.snapshot().keySet()) {\n clear(host, clearPersistent);\n }\n }\n\n private MemorizingStore getStoreForHost(String host) throws Exception {\n MemorizingStore store;\n\n synchronized(this) {\n store=stores.get(host);\n\n if (store==null) {\n store=new MemorizingStore(host, workingDir, storePassword, storeType,\n noTOFU);\n stores.put(host, store);\n }\n }\n\n return(store);\n }\n\n /**\n * Builder-style API for creating instances of MemorizingTrustManager.\n * Create an instance of this class, call either version of saveTo()\n * (and optionally other configuration methods), then call build()\n * to get a MemorizingTrustManager.\n */\n public static class Builder {\n private File workingDir=null;\n private char[] storePassword;\n private String storeType;\n private boolean noTOFU=false;\n private int cacheSize=128;\n private DomainMatchRule domainMatchRule;\n private boolean onlySingleItemChains=false;\n\n /**\n * Indicates where the keystores associated with memorize() should\n * go. This should be an empty directory that you are not using for\n * any other purpose. Also, please put it on internal storage\n * (e.g., subdirectory off of getFilesDir() or getCacheDir()), for\n * security.\n *\n * @param workingDir where we should store memorized certificates\n * @param storePassword passphrase to use for the keystore files\n * @return the builder, for further configuration\n */\n public Builder saveTo(File workingDir, char[] storePassword) {\n return(saveTo(workingDir, storePassword, KeyStore.getDefaultType()));\n }\n\n /**\n * Indicates where the keystores associated with memorize() should\n * go. This should be an empty directory that you are not using for\n * any other purpose. Also, please put it on internal storage\n * (e.g., subdirectory off of getFilesDir() or getCacheDir()), for\n * security.\n *\n * @param workingDir where we should store memorized certificates\n * @param storePassword passphrase to use for the keystore files\n * @param storeType specific type of keystore file to use\n * @return the builder, for further configuration\n */\n public Builder saveTo(File workingDir, char[] storePassword,\n String storeType) {\n this.workingDir=workingDir;\n this.storePassword=storePassword;\n this.storeType=storeType;\n\n return(this);\n }\n\n /**\n * By default, trust on first use (TOFU) is enabled, and so all unrecognized\n * certificates are memorized automatically.\n *\n * If you call noTOFU(), and we encounter a certificate for a domain for\n * which we have no other certificates, you will get a\n * CertificateNotMemorizedException via a wrapper SSLHandshakeException.\n *\n * @return the builder, for further configuration\n */\n public Builder noTOFU() {\n this.noTOFU=true;\n\n return(this);\n }\n\n /**\n * Indicates the number of domains for which to cache certificates in\n * memory. Domains ejected from the cache will lose any transient\n * certificates (memorizeForNow()) but will retain and persistent\n * certificates (memorize()). Value must be greater than zero (duh).\n *\n * @param cacheSize number of domains to keep in cache (default: 128)\n * @return the builder, for further configuration\n */\n public Builder cacheSize(int cacheSize) {\n if (cacheSize<=0) {\n throw new IllegalArgumentException(\"Please provide a sensible cache size\");\n }\n\n this.cacheSize=cacheSize;\n\n return(this);\n }\n\n /**\n * Limits memorization to domains that match the supplied rule\n *\n * @param domainMatchRule Rule for which domains to memorize\n * @return the builder, for further configuration\n */\n public Builder forDomains(DomainMatchRule domainMatchRule) {\n this.domainMatchRule=domainMatchRule;\n\n return(this);\n }\n\n /**\n * Limits memorization to single-item certificate chains, which should\n * effectively limit you to self-signed certificates.\n *\n * @return the builder, for further configuration\n */\n public Builder onlySingleItemChains() {\n this.onlySingleItemChains=true;\n\n return(this);\n }\n\n /**\n * Validates your configuration and builds the MemorizingTrustManager.\n *\n * This creates a new instance each time, so it is safe to hold onto\n * this Builder and create more than one MemorizingTrustManager. However,\n * do not use more than one MemorizingTrustManager at a time, as\n * multiple instances do not coordinate with one another, and so each\n * instance will be oblivious to memorizations (or clear() calls) made\n * on other instances.\n *\n * @return the MemorizingTrustManager, built to your exacting specifications\n */\n public MemorizingTrustManager build() {\n if (workingDir==null) {\n throw new IllegalStateException(\"You have not configured this builder!\");\n }\n\n workingDir.mkdirs();\n\n return(new MemorizingTrustManager(workingDir, storePassword, storeType,\n noTOFU, cacheSize, domainMatchRule, onlySingleItemChains));\n }\n }\n\n private static class MemorizingStore {\n private final String host;\n private final File store;\n private final char[] storePassword;\n private final String storeType;\n private final boolean noTOFU;\n private KeyStore keyStore;\n private X509TrustManager storeTrustManager;\n private KeyStore transientKeyStore;\n private X509TrustManager transientTrustManager;\n\n MemorizingStore(String host, File workingDir, char[] storePassword,\n String storeType, boolean noTOFU) throws Exception {\n this.host=host;\n store=new File(workingDir, host);\n this.storePassword=storePassword;\n this.storeType=storeType;\n this.noTOFU=noTOFU;\n\n init();\n }\n\n synchronized void checkServerTrusted(X509Certificate[] chain,\n String authType)\n throws CertificateException {\n try {\n storeTrustManager.checkServerTrusted(chain, authType);\n }\n catch (CertificateException e) {\n try {\n transientTrustManager.checkServerTrusted(chain, authType);\n }\n catch (CertificateException e2) {\n try {\n if (keyStore.size()==0 && transientKeyStore.size()==0) {\n if (!noTOFU) {\n try {\n memorize(chain);\n return;\n }\n catch (Exception e4) {\n throw new CertificateException(\"Problem while memorizing\", e4);\n }\n }\n\n throw new CertificateNotMemorizedException(chain, host);\n }\n }\n catch (KeyStoreException kse) {\n // srsly?\n }\n\n throw new MemorizationMismatchException(chain, host, e2);\n }\n }\n }\n\n synchronized void memorize(X509Certificate[] chain)\n throws Exception {\n for (X509Certificate cert : chain) {\n String alias=cert.getSubjectDN().getName();\n\n keyStore.setCertificateEntry(alias, cert);\n }\n\n TrustManagerFactory tmf=TrustManagerFactory.getInstance(\"X509\");\n\n tmf.init(keyStore);\n storeTrustManager=findX509TrustManager(tmf);\n\n FileOutputStream fos=new FileOutputStream(store);\n\n keyStore.store(fos, storePassword);\n fos.flush();\n fos.close();\n }\n\n synchronized void memorizeForNow(X509Certificate[] chain)\n throws Exception {\n for (X509Certificate cert : chain) {\n String alias=cert.getSubjectDN().getName();\n\n transientKeyStore.setCertificateEntry(alias, cert);\n }\n\n TrustManagerFactory tmf=TrustManagerFactory.getInstance(\"X509\");\n\n tmf.init(transientKeyStore);\n transientTrustManager=findX509TrustManager(tmf);\n }\n\n synchronized void clear(boolean clearPersistent) throws Exception {\n if (clearPersistent) {\n store.delete();\n }\n\n init();\n }\n\n private void init() throws Exception {\n transientKeyStore=KeyStore.getInstance(storeType);\n transientKeyStore.load(null, null);\n\n TrustManagerFactory tmf=TrustManagerFactory.getInstance(\"X509\");\n\n tmf.init(transientKeyStore);\n transientTrustManager=findX509TrustManager(tmf);\n\n keyStore=KeyStore.getInstance(storeType);\n\n if (store.exists()) {\n keyStore.load(new FileInputStream(store), storePassword);\n }\n else {\n keyStore.load(null, storePassword);\n }\n\n tmf=TrustManagerFactory.getInstance(\"X509\");\n tmf.init(keyStore);\n storeTrustManager=findX509TrustManager(tmf);\n }\n\n private X509TrustManager findX509TrustManager(TrustManagerFactory tmf) {\n for (TrustManager t : tmf.getTrustManagers()) {\n if (t instanceof X509TrustManager) {\n return (X509TrustManager)t;\n }\n }\n\n return(null);\n }\n }\n}",
"public class OkHttp3Integrator {\n static public OkHttpClient.Builder applyTo(TrustManagerBuilder tmb,\n OkHttpClient.Builder builder)\n throws NoSuchAlgorithmException, KeyManagementException {\n CompositeTrustManager trustManager=tmb.build();\n\n if (trustManager.size()>0) {\n SSLContext ssl=SSLContext.getInstance(\"TLS\");\n X509Interceptor interceptor=new X509Interceptor(trustManager, tmb);\n\n ssl.init(null, new TrustManager[]{trustManager}, null);\n builder.sslSocketFactory(ssl.getSocketFactory(), trustManager);\n builder.addInterceptor(interceptor);\n builder.addNetworkInterceptor(interceptor);\n }\n\n return(builder);\n }\n\n static private class X509Interceptor implements Interceptor {\n private final CompositeTrustManager trustManager;\n private final TrustManagerBuilder builder;\n\n private X509Interceptor(CompositeTrustManager trustManager,\n TrustManagerBuilder builder) {\n this.trustManager=trustManager;\n this.builder=builder;\n }\n\n @Override\n public Response intercept(Chain chain) throws IOException {\n Request request=chain.request();\n String host=request.url().host();\n\n if (request.url().scheme().equals(\"http\") &&\n !builder.isCleartextTrafficPermitted(host)) {\n throw new CleartextAttemptException(\"Cleartext blocked for \"+request.url());\n }\n\n synchronized(this) {\n trustManager.setHost(host);\n\n return(chain.proceed(request));\n }\n }\n }\n\n static public class CleartextAttemptException\n extends RuntimeException {\n public CleartextAttemptException(String message) {\n super(message);\n }\n }\n}",
"public class TrustManagerBuilder {\n private static final String META_DATA_NAME=\"android.security.net.config\";\n private CompositeTrustManager mgr=CompositeTrustManager.matchAll();\n private ApplicationConfig appConfig=null;\n\n /**\n * @return the CompositeTrustManager representing the particular\n * rules you want to apply\n */\n public CompositeTrustManager build() {\n return(mgr);\n }\n\n /**\n * @return the TrustManager from build(), wrapped into a\n * one-element array, for convenience\n */\n public X509TrustManager[] buildArray() {\n return(new X509TrustManager[] { build() });\n }\n\n /**\n * Configures the supplied HttpURLConnection to use the trust\n * manager configured via this builder. This will only be done\n * if the connection really is an HttpsURLConnection (a subclass\n * of HttpURLConnection).\n *\n * @param c the connection to configure\n * @return the connection passed in, for chaining\n * @throws NoSuchAlgorithmException\n * @throws KeyManagementException\n */\n public HttpURLConnection applyTo(HttpURLConnection c)\n throws NoSuchAlgorithmException, KeyManagementException {\n mgr.applyTo(c);\n\n return(c);\n }\n\n /**\n * Use this to add arbitrary TrustManagers to\n * the mix. Only the X509TrustManager instances in the\n * array will be used. This is also used, under the\n * covers, by most of the other builder methods, to add\n * configured trust managers.\n *\n * @param mgrs\n * the TrustManager instances to add\n * @return the builder for chained calls\n */\n public TrustManagerBuilder add(TrustManager... mgrs) {\n for (TrustManager tm : mgrs) {\n if (tm instanceof X509TrustManager) {\n mgr.add((X509TrustManager)tm);\n }\n }\n\n return(this);\n }\n\n /**\n * Any subsequent configuration of this builder, until the\n * next and() call (or build()/buildArray()), will be\n * logically OR'd with whatever came previously. For\n * example, if you need to support two possible\n * self-signed certificates, use\n * selfSigned(...).or().selfSigned(...) to accept either\n * one.\n * \n * @return the builder for chained calls\n */\n public TrustManagerBuilder or() {\n if (mgr.isMatchAll()) {\n if (mgr.size() < 2) {\n mgr.setMatchAll(false);\n }\n else {\n mgr=CompositeTrustManager.matchAny(mgr);\n }\n }\n\n return(this);\n }\n\n /**\n * Any subsequent configuration of this builder, until the\n * next or() call (or build()/buildArray()), will be\n * logically AND'd with whatever came previously. Note\n * that this is the default state or the builder, so you\n * only need an and() to reverse a previous or().\n * \n * @return the builder for chained calls\n */\n public TrustManagerBuilder and() {\n if (!mgr.isMatchAll()) {\n if (mgr.size() < 2) {\n mgr.setMatchAll(true);\n }\n else {\n mgr=CompositeTrustManager.matchAll(mgr);\n }\n }\n\n return(this);\n }\n\n /**\n * Tells the builder to add the default (system)\n * TrustManagers to the roster of ones to consider. For\n * example, to support normal certificates plus a\n * self-signed certificate, use\n * useDefault().or().selfSigned(...).\n * \n * @return the builder for chained calls\n * @throws NoSuchAlgorithmException\n * @throws KeyStoreException\n */\n public TrustManagerBuilder useDefault()\n throws NoSuchAlgorithmException, KeyStoreException {\n TrustManagerFactory tmf=\n TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());\n\n tmf.init((KeyStore)null);\n add(tmf.getTrustManagers());\n\n return(this);\n }\n\n /**\n * Rejects all certificates. At most, this is useful in\n * testing. Use in a production app will cause us to\n * question your sanity.\n * \n * @return the builder for chained calls\n */\n public TrustManagerBuilder denyAll() {\n mgr.add(new DenyAllTrustManager());\n\n return(this);\n }\n\n /**\n * Use the network security configuration identified by the supplied\n * XML resource ID.\n *\n * @param ctxt any Context will work\n * @param resourceId an R.xml value pointing to the configuration\n * @return the builder for chained calls\n */\n public TrustManagerBuilder withConfig(Context ctxt,\n int resourceId) {\n validateConfig(ctxt, resourceId, false);\n\n return(withConfig(new XmlConfigSource(ctxt, resourceId, false)));\n }\n\n /**\n * Use the network security configuration identified by the supplied\n * XML resource ID.\n *\n * @param ctxt any Context will work\n * @param resourceId an R.xml value pointing to the configuration\n * @param isDebugBuild true if this should be treated as a debug\n * build, false otherwise\n * @return the builder for chained calls\n */\n public TrustManagerBuilder withConfig(Context ctxt,\n int resourceId,\n boolean isDebugBuild) {\n validateConfig(ctxt, resourceId, false);\n\n return(withConfig(new XmlConfigSource(ctxt, resourceId,\n isDebugBuild)));\n }\n\n /**\n * Use the network security configuration identified configured\n * in the app's manifest.\n *\n * @param ctxt any Context will work\n * @return the builder for chained calls\n */\n public TrustManagerBuilder withManifestConfig(Context ctxt) {\n if (Build.VERSION.SDK_INT<Build.VERSION_CODES.N) {\n ApplicationInfo info=null;\n\n try {\n info=ctxt.getPackageManager().getApplicationInfo(ctxt.getPackageName(),\n PackageManager.GET_META_DATA);\n }\n catch (PackageManager.NameNotFoundException e) {\n throw new RuntimeException(\"We could not find ourselves?!?\", e);\n }\n\n if (info.metaData==null) {\n throw new RuntimeException(\"Could not find manifest meta-data!\");\n }\n else {\n int resourceId=info.metaData.getInt(META_DATA_NAME, -1);\n\n if (resourceId==-1) {\n throw new RuntimeException(\"Could not find android.security.net.config meta-data!\");\n }\n else {\n validateConfig(ctxt, resourceId, true);\n }\n }\n\n return(withConfig(new ManifestConfigSource(ctxt.getApplicationContext())));\n }\n\n return(this);\n }\n\n TrustManagerBuilder withConfig(ConfigSource config) {\n appConfig=new ApplicationConfig(config);\n\n return(add(appConfig.getTrustManager()));\n }\n\n /**\n * Add a listener to be handed all certificate chains. Use this\n * solely for diagnostic purposes (e.g., to understand what\n * root CA to add to a network security configuration). Do not use\n * this in production code.\n *\n * @param listener a listener to be notified of certificate chains\n * @return the builder for chained calls\n */\n public TrustManagerBuilder withCertChainListener(CertChainListener listener) {\n mgr.addCertChainListener(listener);\n\n return(this);\n }\n\n /**\n * @return true if the network security configuration allows\n * cleartext traffic, false otherwise\n */\n public boolean isCleartextTrafficPermitted() {\n if (appConfig==null) {\n return(true);\n }\n\n return(appConfig.isCleartextTrafficPermitted());\n }\n\n /**\n * @param hostname the domain name to check for cleartext availability\n * @return true if the network security configuration allows\n * cleartext traffic for this domain name, false otherwise\n */\n public boolean isCleartextTrafficPermitted(String hostname) {\n if (appConfig==null) {\n return(true);\n }\n\n return(appConfig.isCleartextTrafficPermitted(hostname));\n }\n\n private void validateConfig(Context ctxt, int resourceId,\n boolean isUserAllowed) {\n XmlResourceParser xpp=ctxt.getResources().getXml(resourceId);\n RuntimeException result=null;\n\n try {\n while (xpp.getEventType()!=XmlPullParser.END_DOCUMENT) {\n if (xpp.getEventType()==XmlPullParser.START_TAG) {\n if (\"certificates\".equals(xpp.getName())) {\n for (int i=0; i<xpp.getAttributeCount(); i++) {\n String name=xpp.getAttributeName(i);\n\n if (\"src\".equals(name)) {\n String src=xpp.getAttributeValue(i);\n\n if (\"user\".equals(src)) {\n if (isUserAllowed) {\n Log.w(\"CWAC-NetSecurity\", \"requested <certificates src=\\\"user\\\">, treating as <certificates src=\\\"system\\\">\");\n }\n else {\n result=new RuntimeException(\n \"requested <certificates src=\\\"user\\\">, not supported\");\n }\n }\n }\n }\n }\n }\n\n xpp.next();\n }\n }\n catch (Exception e) {\n throw new RuntimeException(\"Could not parse config XML\", e);\n }\n\n if (result!=null) {\n throw result;\n }\n }\n}",
"public static DomainMatchRule is(Pattern pattern) {\n return(new Regex(pattern));\n}"
] | import androidx.test.InstrumentationRegistry;
import androidx.test.runner.AndroidJUnit4;
import com.commonsware.cwac.netsecurity.CertificateNotMemorizedException;
import com.commonsware.cwac.netsecurity.MemorizingTrustManager;
import com.commonsware.cwac.netsecurity.OkHttp3Integrator;
import com.commonsware.cwac.netsecurity.TrustManagerBuilder;
import junit.framework.Assert;
import junit.framework.AssertionFailedError;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.io.File;
import javax.net.ssl.SSLHandshakeException;
import okhttp3.CacheControl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import static com.commonsware.cwac.netsecurity.DomainMatchRule.is; | OkHttpClient.Builder freshBuilder=new OkHttpClient.Builder();
OkHttp3Integrator.applyTo(tmb, freshBuilder);
client=freshBuilder.build();
memo.clearAll(false);
try {
client.newCall(buildRequest()).execute();
throw new AssertionFailedError("Expected SSLHandshakeException, did not get!");
}
catch (SSLHandshakeException e) {
if (!(e.getCause() instanceof CertificateNotMemorizedException)) {
throw e;
}
}
}
@Test
public void testNoTOFU() throws Exception {
MemorizingTrustManager memo=new MemorizingTrustManager.Builder()
.saveTo(memoDir, "sekrit".toCharArray())
.noTOFU()
.build();
final TrustManagerBuilder tmb=new TrustManagerBuilder().add(memo);
OkHttp3Integrator.applyTo(tmb, builder);
OkHttpClient client=builder.build();
CertificateNotMemorizedException memoEx;
try {
client.newCall(buildRequest()).execute();
throw new AssertionFailedError("Expected SSLHandshakeException, did not get!");
}
catch (SSLHandshakeException e) {
if (e.getCause() instanceof CertificateNotMemorizedException) {
memoEx=(CertificateNotMemorizedException)e.getCause();
}
else {
throw new AssertionFailedError("Expected CertificateNotMemorizedException, did not get!");
}
}
memo.memorize(memoEx);
Response response=client.newCall(buildRequest()).execute();
Assert.assertEquals(getExpectedResponse(), response.body().string());
OkHttpClient.Builder freshBuilder=new OkHttpClient.Builder();
OkHttp3Integrator.applyTo(tmb, freshBuilder);
client=freshBuilder.build();
memo.clearAll(true);
try {
client.newCall(buildRequest()).execute();
throw new AssertionFailedError("Expected SSLHandshakeException, did not get!");
}
catch (SSLHandshakeException e) {
if (!(e.getCause() instanceof CertificateNotMemorizedException)) {
throw e;
}
}
}
@Test
public void testTOFU() throws Exception {
MemorizingTrustManager memo=new MemorizingTrustManager.Builder()
.saveTo(memoDir, "sekrit".toCharArray())
.build();
final TrustManagerBuilder tmb=new TrustManagerBuilder().add(memo);
OkHttp3Integrator.applyTo(tmb, builder);
OkHttpClient client=builder.build();
Response response=client.newCall(buildRequest()).execute();
Assert.assertEquals(getExpectedResponse(), response.body().string());
response=client.newCall(buildRequest()).execute();
Assert.assertEquals(getExpectedResponse(), response.body().string());
MemorizingTrustManager memoNoTofu=new MemorizingTrustManager.Builder()
.saveTo(memoDir, "sekrit".toCharArray())
.noTOFU()
.build();
TrustManagerBuilder tmbNoTofu=new TrustManagerBuilder().add(memoNoTofu);
OkHttpClient.Builder builderNoTofu=new OkHttpClient.Builder();
OkHttp3Integrator.applyTo(tmbNoTofu, builderNoTofu);
OkHttpClient clientNoTofu=builderNoTofu.build();
response=clientNoTofu.newCall(buildRequest()).execute();
Assert.assertEquals(getExpectedResponse(), response.body().string());
memoNoTofu.clearAll(true);
builderNoTofu=new OkHttpClient.Builder();
OkHttp3Integrator.applyTo(tmbNoTofu, builderNoTofu);
clientNoTofu=builderNoTofu.build();
try {
clientNoTofu.newCall(buildRequest()).execute();
throw new AssertionFailedError("Expected SSLHandshakeException, did not get!");
}
catch (SSLHandshakeException e) {
if (!(e.getCause() instanceof CertificateNotMemorizedException)) {
throw e;
}
}
}
@Test
public void testDomainMatchRule() throws Exception {
MemorizingTrustManager memo=new MemorizingTrustManager.Builder()
.saveTo(memoDir, "sekrit".toCharArray())
.noTOFU() | .forDomains(is("this-so-does-not-exist.com")) | 4 |
jaychang0917/SimpleRecyclerView | app/src/main/java/com/jaychang/demo/srv/SectionHeaderActivity.java | [
"public class BookCell extends SimpleCell<Book, BookCell.ViewHolder>\n implements Updatable<Book> {\n\n private static final String KEY_TITLE = \"KEY_TITLE\";\n private boolean showHandle;\n\n public BookCell(Book item) {\n super(item);\n }\n\n @Override\n protected int getLayoutRes() {\n return R.layout.cell_book;\n }\n\n @NonNull\n @Override\n protected ViewHolder onCreateViewHolder(ViewGroup parent, View cellView) {\n return new ViewHolder(cellView);\n }\n\n @Override\n protected void onBindViewHolder(ViewHolder holder, int position, Context context, Object payload) {\n if (payload != null) {\n // payload from updateCell()\n if (payload instanceof Book) {\n holder.textView.setText(((Book) payload).getTitle());\n }\n // payloads from updateCells()\n if (payload instanceof ArrayList) {\n List<Book> payloads = ((ArrayList<Book>) payload);\n holder.textView.setText(payloads.get(position).getTitle());\n }\n // payload from addOrUpdate()\n if (payload instanceof Bundle) {\n Bundle bundle = ((Bundle) payload);\n for (String key : bundle.keySet()) {\n if (KEY_TITLE.equals(key)) {\n holder.textView.setText(bundle.getString(key));\n }\n }\n }\n return;\n }\n\n holder.textView.setText(getItem().getTitle());\n\n if (showHandle) {\n holder.dragHandle.setVisibility(View.VISIBLE);\n } else {\n holder.dragHandle.setVisibility(View.GONE);\n }\n }\n\n // Optional\n @Override\n protected void onUnbindViewHolder(ViewHolder holder) {\n // do your cleaning jobs here when the item view is recycled.\n }\n\n public void setShowHandle(boolean showHandle) {\n this.showHandle = showHandle;\n }\n\n @Override\n protected long getItemId() {\n return getItem().getId();\n }\n\n /**\n * If the titles of books are same, no need to update the cell, onBindViewHolder() will not be called.\n */\n @Override\n public boolean areContentsTheSame(Book newItem) {\n return getItem().getTitle().equals(newItem.getTitle());\n }\n\n /**\n * If getItem() is the same as newItem (i.e. their return value of getItemId() are the same)\n * and areContentsTheSame() return false, then the cell need to be updated,\n * onBindViewHolder() will be called with this payload object.\n */\n @Override\n public Object getChangePayload(Book newItem) {\n Bundle bundle = new Bundle();\n bundle.putString(KEY_TITLE, newItem.getTitle());\n return bundle;\n }\n\n public static class ViewHolder extends SimpleViewHolder {\n @BindView(R.id.textView)\n TextView textView;\n @BindView(R.id.dragHandle)\n ImageView dragHandle;\n\n ViewHolder(View itemView) {\n super(itemView);\n ButterKnife.bind(this, itemView);\n }\n }\n\n}",
"public class Book {\n\n private long id;\n private String title;\n private String author;\n private Category category;\n\n public Book(long id, String title, String author, Category category) {\n this.id = id;\n this.title = title;\n this.author = author;\n this.category = category;\n }\n\n public long getId() {\n return id;\n }\n\n public String getTitle() {\n return title;\n }\n\n public String getAuthor() {\n return author;\n }\n\n public long getCategoryId() {\n return category.getId();\n }\n\n public String getCategoryName() {\n return category.getName();\n }\n\n public void setTitle(String title) {\n this.title = title;\n }\n\n @Override\n public String toString() {\n return title;\n }\n\n}",
"public final class DataUtils {\n\n public interface DataCallback {\n void onSuccess(List<Book> books);\n }\n\n public static List<Book> getBooks() {\n List<Book> books = getAllBooks();\n return books.subList(0, 9);\n }\n\n public static List<Book> getBooks(@IntRange(from = 0, to = 30) int count) {\n List<Book> books = getAllBooks();\n return books.subList(0, count);\n }\n\n public static List<Book> getAllBooks() {\n List<Book> books = new ArrayList<>();\n for (int i = 0; i < 30; i++) {\n books.add(newBook(i));\n }\n return books;\n }\n\n public static Book getBook(int id) {\n List<Book> books = getAllBooks();\n return books.get(id);\n }\n\n public static void getBooksAsync(final Activity activity, final DataCallback callback) {\n AsyncTask.execute(new Runnable() {\n @Override\n public void run() {\n SystemClock.sleep(500);\n activity.runOnUiThread(new Runnable() {\n @Override\n public void run() {\n callback.onSuccess(getBooks());\n }\n });\n }\n });\n }\n\n public static Book newBook(long id) {\n String title = \"Book \" + id;\n String author = \"Foo \" + id;\n long categoryId = id / 3;\n Category category = new Category(categoryId, String.valueOf(categoryId));\n return new Book(id, title, author, category);\n }\n\n public static List<Ad> getAds() {\n List<Ad> ads = new ArrayList<>();\n ads.add(new Ad(0, \"Ad 0\"));\n ads.add(new Ad(1, \"Ad 1\"));\n return ads;\n }\n\n}",
"public final class Utils {\n\n private Utils() {\n }\n\n public static int dp2px(Context context, int dp) {\n float density = context.getApplicationContext().getApplicationContext().getResources().getDisplayMetrics().density;\n return (int) (dp * density + 0.5f);\n }\n\n}",
"public class SimpleRecyclerView extends RecyclerView\n implements CellOperations {\n\n private int layoutMode;\n private int gridSpanCount;\n private String gridSpanSequence;\n private int spacing;\n private int verticalSpacing;\n private int horizontalSpacing;\n private boolean isSpacingIncludeEdge;\n private boolean showDivider;\n private boolean showLastDivider;\n private int dividerColor;\n private int dividerOrientation;\n private int dividerPaddingLeft;\n private int dividerPaddingRight;\n private int dividerPaddingTop;\n private int dividerPaddingBottom;\n private boolean isSnappyEnabled;\n private int snapAlignment;\n private int emptyStateViewRes;\n private boolean showEmptyStateView;\n private int loadMoreViewRes;\n\n private SimpleAdapter adapter;\n private AdapterDataObserver adapterDataObserver = new AdapterDataObserver() {\n @Override\n public void onChanged() {\n updateEmptyStateViewVisibility();\n }\n\n @Override\n public void onItemRangeInserted(int positionStart, int itemCount) {\n updateEmptyStateViewVisibility();\n }\n\n @Override\n public void onItemRangeRemoved(int positionStart, int itemCount) {\n updateEmptyStateViewVisibility();\n }\n };\n\n private List<String> noDividerCellTypes;\n\n private InternalEmptyStateViewCell emptyStateViewCell;\n private boolean isEmptyViewShown;\n private boolean isRefreshing;\n\n private InternalLoadMoreViewCell loadMoreViewCell;\n private boolean isScrollUp;\n private int autoLoadMoreThreshold;\n private OnLoadMoreListener onLoadMoreListener;\n private boolean isLoadMoreToTop;\n private boolean isLoadingMore;\n private boolean isLoadMoreViewShown;\n\n public SimpleRecyclerView(Context context) {\n this(context, null);\n }\n\n public SimpleRecyclerView(Context context, AttributeSet attrs) {\n this(context, attrs, 0);\n }\n\n public SimpleRecyclerView(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n\n initAttrs(context, attrs, defStyle);\n\n if (!isInEditMode()) {\n setup();\n }\n }\n\n private void initAttrs(Context context, AttributeSet attrs, int defStyle) {\n TypedArray typedArray = context.getTheme().obtainStyledAttributes(attrs, R.styleable.SimpleRecyclerView, defStyle, 0);\n layoutMode = typedArray.getInt(R.styleable.SimpleRecyclerView_srv_layoutMode, 0);\n gridSpanCount = typedArray.getInt(R.styleable.SimpleRecyclerView_srv_gridSpanCount, 0);\n gridSpanSequence = typedArray.getString(R.styleable.SimpleRecyclerView_srv_gridSpanSequence);\n spacing = typedArray.getDimensionPixelSize(R.styleable.SimpleRecyclerView_srv_spacing, 0);\n verticalSpacing = typedArray.getDimensionPixelSize(R.styleable.SimpleRecyclerView_srv_verticalSpacing, 0);\n horizontalSpacing = typedArray.getDimensionPixelSize(R.styleable.SimpleRecyclerView_srv_horizontalSpacing, 0);\n isSpacingIncludeEdge = typedArray.getBoolean(R.styleable.SimpleRecyclerView_srv_isSpacingIncludeEdge, false);\n showDivider = typedArray.getBoolean(R.styleable.SimpleRecyclerView_srv_showDivider, false);\n showLastDivider = typedArray.getBoolean(R.styleable.SimpleRecyclerView_srv_showLastDivider, false);\n dividerColor = typedArray.getColor(R.styleable.SimpleRecyclerView_srv_dividerColor, 0);\n dividerOrientation = typedArray.getInt(R.styleable.SimpleRecyclerView_srv_dividerOrientation, 2);\n dividerPaddingLeft = typedArray.getDimensionPixelSize(R.styleable.SimpleRecyclerView_srv_dividerPaddingLeft, 0);\n dividerPaddingRight = typedArray.getDimensionPixelSize(R.styleable.SimpleRecyclerView_srv_dividerPaddingRight, 0);\n dividerPaddingTop = typedArray.getDimensionPixelSize(R.styleable.SimpleRecyclerView_srv_dividerPaddingTop, 0);\n dividerPaddingBottom = typedArray.getDimensionPixelSize(R.styleable.SimpleRecyclerView_srv_dividerPaddingBottom, 0);\n isSnappyEnabled = typedArray.getBoolean(R.styleable.SimpleRecyclerView_srv_snappy, false);\n snapAlignment = typedArray.getInt(R.styleable.SimpleRecyclerView_srv_snap_alignment, 0);\n showEmptyStateView = typedArray.getBoolean(R.styleable.SimpleRecyclerView_srv_showEmptyStateView, false);\n emptyStateViewRes = typedArray.getResourceId(R.styleable.SimpleRecyclerView_srv_emptyStateView, 0);\n loadMoreViewRes = typedArray.getResourceId(R.styleable.SimpleRecyclerView_srv_loadMoreView, 0);\n typedArray.recycle();\n }\n\n /**\n * setup\n */\n private void setup() {\n setupRecyclerView();\n setupDecorations();\n setupBehaviors();\n }\n\n private void setupRecyclerView() {\n setupAdapter();\n setupLayoutManager();\n setupEmptyView();\n setupLoadMore();\n disableChangeAnimations();\n }\n\n private void setupAdapter() {\n adapter = new SimpleAdapter();\n adapter.registerAdapterDataObserver(adapterDataObserver);\n setAdapter(adapter);\n }\n\n private void setupLayoutManager() {\n if (layoutMode == 0) {\n useLinearVerticalMode();\n } else if (layoutMode == 1) {\n useLinearHorizontalMode();\n } else if (layoutMode == 2) {\n if (!TextUtils.isEmpty(gridSpanSequence)) {\n try {\n useGridModeWithSequence(Utils.toIntList(gridSpanSequence));\n } catch (NumberFormatException e) {\n throw new IllegalArgumentException(\"gridSpanSequence must be digits. (e.g. 2233)\");\n }\n } else {\n useGridMode(gridSpanCount);\n }\n }\n }\n\n private void setupEmptyView() {\n if (emptyStateViewRes != 0) {\n setEmptyStateView(emptyStateViewRes);\n }\n if (showEmptyStateView) {\n showEmptyStateView();\n }\n }\n\n private void setupLoadMore() {\n if (loadMoreViewRes != 0) {\n setLoadMoreView(loadMoreViewRes);\n }\n\n addOnScrollListener(new OnScrollListener() {\n @Override\n public void onScrolled(RecyclerView recyclerView, int dx, int dy) {\n super.onScrolled(recyclerView, dx, dy);\n\n if (onLoadMoreListener == null) {\n return;\n }\n\n isScrollUp = dy < 0;\n\n checkLoadMoreThreshold();\n }\n });\n\n // trigger checkLoadMoreThreshold() if the recyclerview if not scrollable.\n setOnTouchListener(new OnTouchListener() {\n float preY;\n\n @Override\n public boolean onTouch(View v, MotionEvent event) {\n if (onLoadMoreListener == null) {\n return false;\n }\n\n switch (event.getAction()) {\n case MotionEvent.ACTION_MOVE:\n isScrollUp = event.getY() > preY;\n preY = event.getY();\n checkLoadMoreThreshold();\n }\n\n if (Utils.isScrollable(SimpleRecyclerView.this)) {\n setOnTouchListener(null);\n }\n\n return false;\n }\n });\n }\n\n private void checkLoadMoreThreshold() {\n // check isEmpty() to prevent the case: removeAllCells triggers this call\n if (isEmptyViewShown || isLoadingMore || isEmpty()) {\n return;\n }\n\n if (isLoadMoreToTop && isScrollUp) {\n int topHiddenItemCount = getFirstVisibleItemPosition();\n\n if (topHiddenItemCount == -1) {\n return;\n }\n\n if (topHiddenItemCount <= autoLoadMoreThreshold) {\n handleLoadMore();\n }\n\n return;\n }\n\n if (!isLoadMoreToTop && !isScrollUp) {\n int bottomHiddenItemCount = getItemCount() - getLastVisibleItemPosition() - 1;\n\n if (bottomHiddenItemCount == -1) {\n return;\n }\n\n if (bottomHiddenItemCount <= autoLoadMoreThreshold) {\n handleLoadMore();\n }\n }\n }\n\n private void handleLoadMore() {\n if (onLoadMoreListener.shouldLoadMore()) {\n onLoadMoreListener.onLoadMore();\n }\n }\n\n private int getFirstVisibleItemPosition() {\n if (getLayoutManager() instanceof GridLayoutManager) {\n return ((GridLayoutManager) getLayoutManager()).findFirstVisibleItemPosition();\n } else if (getLayoutManager() instanceof LinearLayoutManager) {\n return ((LinearLayoutManager) getLayoutManager()).findFirstVisibleItemPosition();\n } else {\n return -1;\n }\n }\n\n private int getLastVisibleItemPosition() {\n if (getLayoutManager() instanceof GridLayoutManager) {\n return ((GridLayoutManager) getLayoutManager()).findLastVisibleItemPosition();\n } else if (getLayoutManager() instanceof LinearLayoutManager) {\n return ((LinearLayoutManager) getLayoutManager()).findLastVisibleItemPosition();\n } else {\n return -1;\n }\n }\n\n private void disableChangeAnimations() {\n ItemAnimator animator = getItemAnimator();\n if (animator instanceof SimpleItemAnimator) {\n ((SimpleItemAnimator) animator).setSupportsChangeAnimations(false);\n }\n\n // todo temp fix: load more doesn't work good with grid layout mode\n setItemAnimator(null);\n }\n\n private void setupDecorations() {\n if (showDivider) {\n if (dividerColor != 0) {\n showDividerInternal(dividerColor, dividerPaddingLeft, dividerPaddingTop, dividerPaddingRight, dividerPaddingBottom);\n } else {\n showDivider();\n }\n }\n\n if (spacing != 0) {\n setSpacingInternal(spacing, spacing, isSpacingIncludeEdge);\n } else if (verticalSpacing != 0 || horizontalSpacing != 0) {\n setSpacingInternal(verticalSpacing, horizontalSpacing, isSpacingIncludeEdge);\n }\n }\n\n private void setupBehaviors() {\n if (isSnappyEnabled) {\n if (snapAlignment == 0) {\n enableSnappy(SnapAlignment.CENTER);\n } else if (snapAlignment == 1) {\n enableSnappy(SnapAlignment.START);\n }\n }\n }\n\n /**\n * layout modes\n */\n public void useLinearVerticalMode() {\n setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));\n }\n\n public void useLinearHorizontalMode() {\n setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));\n }\n\n public void useGridMode(int spanCount) {\n setGridSpanCount(spanCount);\n setLayoutManager(new GridLayoutManager(getContext(), spanCount));\n\n GridLayoutManager.SpanSizeLookup spanSizeLookup = new GridLayoutManager.SpanSizeLookup() {\n @Override\n public int getSpanSize(int position) {\n try {\n return adapter.getCell(position).getSpanSize();\n } catch (Exception e) {\n return 1;\n }\n }\n };\n spanSizeLookup.setSpanIndexCacheEnabled(true);\n ((GridLayoutManager) getLayoutManager()).setSpanSizeLookup(spanSizeLookup);\n }\n\n public void useGridModeWithSequence(int first, int... rest) {\n useGridModeWithSequence(Utils.toIntList(first, rest));\n }\n\n public void useGridModeWithSequence(@NonNull List<Integer> sequence) {\n final int lcm = Utils.lcm(sequence);\n final ArrayList<Integer> sequenceList = new ArrayList<>();\n for (int i = 0; i < sequence.size(); i++) {\n int item = sequence.get(i);\n for (int j = 0; j < item; j++) {\n sequenceList.add(lcm / item);\n }\n }\n\n setGridSpanCount(lcm);\n setLayoutManager(new GridLayoutManager(getContext(), lcm));\n\n GridLayoutManager.SpanSizeLookup spanSizeLookup = new GridLayoutManager.SpanSizeLookup() {\n @Override\n public int getSpanSize(int position) {\n try {\n return sequenceList.get(position % sequenceList.size());\n } catch (Exception e) {\n return 1;\n }\n }\n };\n spanSizeLookup.setSpanIndexCacheEnabled(true);\n ((GridLayoutManager) getLayoutManager()).setSpanSizeLookup(spanSizeLookup);\n }\n\n private void setGridSpanCount(int spanCount) {\n if (spanCount <= 0) {\n throw new IllegalArgumentException(\"spanCount must >= 1\");\n }\n\n this.gridSpanCount = spanCount;\n }\n\n /**\n * divider\n */\n private void showDividerInternal(@ColorInt int color,\n int paddingLeft, int paddingTop,\n int paddingRight, int paddingBottom) {\n if (getLayoutManager() instanceof GridLayoutManager) {\n if (dividerOrientation == 0) {\n addDividerItemDecoration(color, DividerItemDecoration.HORIZONTAL,\n paddingLeft, paddingTop, paddingRight, paddingBottom);\n } else if (dividerOrientation == 1) {\n addDividerItemDecoration(color, DividerItemDecoration.VERTICAL,\n paddingLeft, paddingTop, paddingRight, paddingBottom);\n } else {\n addDividerItemDecoration(color, DividerItemDecoration.VERTICAL,\n paddingLeft, paddingTop, paddingRight, paddingBottom);\n addDividerItemDecoration(color, DividerItemDecoration.HORIZONTAL,\n paddingLeft, paddingTop, paddingRight, paddingBottom);\n }\n } else if (getLayoutManager() instanceof LinearLayoutManager) {\n int orientation = ((LinearLayoutManager) getLayoutManager()).getOrientation();\n addDividerItemDecoration(color, orientation,\n paddingLeft, paddingTop, paddingRight, paddingBottom);\n }\n }\n\n private void addDividerItemDecoration(@ColorInt int color, int orientation,\n int paddingLeft, int paddingTop,\n int paddingRight, int paddingBottom) {\n DividerItemDecoration decor = new DividerItemDecoration(getContext(), orientation);\n if (color != 0) {\n ShapeDrawable shapeDrawable = new ShapeDrawable(new RectShape());\n shapeDrawable.setIntrinsicHeight(Utils.dpToPx(getContext(), 1));\n shapeDrawable.setIntrinsicWidth(Utils.dpToPx(getContext(), 1));\n shapeDrawable.getPaint().setColor(color);\n InsetDrawable insetDrawable = new InsetDrawable(shapeDrawable, paddingLeft, paddingTop, paddingRight, paddingBottom);\n decor.setDrawable(insetDrawable);\n }\n decor.setShowLastDivider(showLastDivider);\n addItemDecoration(decor);\n }\n\n public void showDivider() {\n showDividerInternal(Color.parseColor(\"#e0e0e0\"), dividerPaddingLeft, dividerPaddingTop, dividerPaddingRight, dividerPaddingBottom);\n }\n\n public void showDivider(@ColorRes int colorRes) {\n showDividerInternal(ContextCompat.getColor(getContext(), colorRes),\n dividerPaddingLeft, dividerPaddingTop, dividerPaddingRight, dividerPaddingBottom);\n }\n\n public void showDivider(@ColorRes int colorRes, int paddingLeftDp, int paddingTopDp, int paddingRightDp, int paddingBottomDp) {\n showDividerInternal(ContextCompat.getColor(getContext(), colorRes),\n Utils.dpToPx(getContext(), paddingLeftDp), Utils.dpToPx(getContext(), paddingTopDp),\n Utils.dpToPx(getContext(), paddingRightDp), Utils.dpToPx(getContext(), paddingBottomDp));\n }\n\n public void dontShowDividerForCellType(@NonNull Class<?>... classes) {\n if (noDividerCellTypes == null) {\n noDividerCellTypes = new ArrayList<>();\n }\n\n for (Class<?> aClass : classes) {\n noDividerCellTypes.add(aClass.getSimpleName());\n }\n }\n\n public List<String> getNoDividerCellTypes() {\n return noDividerCellTypes == null ? Collections.<String>emptyList() : noDividerCellTypes;\n }\n\n /**\n * spacing\n */\n private void setGridSpacingInternal(int verSpacing, int horSpacing, boolean includeEdge) {\n addItemDecoration(GridSpacingItemDecoration.newBuilder().verticalSpacing(verSpacing).horizontalSpacing(horSpacing).includeEdge(includeEdge).build());\n }\n\n private void setLinearSpacingInternal(int spacing, boolean includeEdge) {\n int orientation = ((LinearLayoutManager) getLayoutManager()).getOrientation();\n addItemDecoration(LinearSpacingItemDecoration.newBuilder().spacing(spacing).orientation(orientation).includeEdge(includeEdge).build());\n }\n\n private void setSpacingInternal(int verSpacing, int horSpacing, boolean includeEdge) {\n if (getLayoutManager() instanceof GridLayoutManager) {\n setGridSpacingInternal(verSpacing, horSpacing, includeEdge);\n } else if (getLayoutManager() instanceof LinearLayoutManager) {\n setLinearSpacingInternal(verSpacing, includeEdge);\n }\n }\n\n public void setSpacing(int spacingDp) {\n int spacing = Utils.dpToPx(getContext(), spacingDp);\n setSpacingInternal(spacing, spacing, false);\n }\n\n public void setSpacingIncludeEdge(int spacingDp) {\n int spacing = Utils.dpToPx(getContext(), spacingDp);\n setSpacingInternal(spacing, spacing, true);\n }\n\n public void setSpacing(int verticalSpacingDp, int horizontalSpacingDp) {\n int verticalSpacing = Utils.dpToPx(getContext(), verticalSpacingDp);\n int horizontalSpacing = Utils.dpToPx(getContext(), horizontalSpacingDp);\n setSpacingInternal(verticalSpacing, horizontalSpacing, false);\n }\n\n public void setSpacingIncludeEdge(int verticalSpacingDp, int horizontalSpacingDp) {\n int verticalSpacing = Utils.dpToPx(getContext(), verticalSpacingDp);\n int horizontalSpacing = Utils.dpToPx(getContext(), horizontalSpacingDp);\n setSpacingInternal(verticalSpacing, horizontalSpacing, true);\n }\n\n /**\n * empty view\n */\n private void updateEmptyStateViewVisibility() {\n adapter.unregisterAdapterDataObserver(adapterDataObserver);\n if (adapter.getItemCount() <= 0) {\n showEmptyStateView();\n } else {\n hideEmptyStateView();\n }\n adapter.registerAdapterDataObserver(adapterDataObserver);\n }\n\n public void showEmptyStateView() {\n if (isRefreshing) {\n isRefreshing = false;\n return;\n }\n\n if (isEmptyViewShown || emptyStateViewCell == null) {\n return;\n }\n\n addCell(emptyStateViewCell);\n\n isEmptyViewShown = true;\n }\n\n public void hideEmptyStateView() {\n if (!isEmptyViewShown || emptyStateViewCell == null) {\n return;\n }\n\n removeCell(emptyStateViewCell);\n\n isEmptyViewShown = false;\n }\n\n public void setEmptyStateView(@LayoutRes int emptyStateView) {\n View view = LayoutInflater.from(getContext()).inflate(emptyStateView, this, false);\n setEmptyStateView(view);\n }\n\n public void setEmptyStateView(@NonNull View emptyStateView) {\n this.emptyStateViewCell = new InternalEmptyStateViewCell(emptyStateView);\n emptyStateViewCell.setSpanSize(gridSpanCount);\n }\n\n /**\n * load more\n */\n public void setLoadMoreView(@LayoutRes int loadMoreView) {\n View view = LayoutInflater.from(getContext()).inflate(loadMoreView, this, false);\n setLoadMoreView(view);\n }\n\n public void setLoadMoreView(@NonNull View loadMoreView) {\n this.loadMoreViewCell = new InternalLoadMoreViewCell(loadMoreView);\n loadMoreViewCell.setSpanSize(gridSpanCount);\n }\n\n public void showLoadMoreView() {\n if (loadMoreViewCell == null || isLoadMoreViewShown) {\n isLoadingMore = true;\n return;\n }\n\n if (isLoadMoreToTop) {\n addCell(0, loadMoreViewCell);\n } else {\n addCell(loadMoreViewCell);\n }\n\n isLoadMoreViewShown = true;\n isLoadingMore = true;\n }\n\n public void hideLoadMoreView() {\n if (loadMoreViewCell == null || !isLoadMoreViewShown) {\n isLoadingMore = false;\n return;\n }\n\n removeCell(loadMoreViewCell);\n\n isLoadMoreViewShown = false;\n isLoadingMore = false;\n }\n\n public void setAutoLoadMoreThreshold(int hiddenCellCount) {\n if (hiddenCellCount < 0) {\n throw new IllegalArgumentException(\"hiddenCellCount must >= 0\");\n }\n this.autoLoadMoreThreshold = hiddenCellCount;\n }\n\n public int getAutoLoadMoreThreshold() {\n return autoLoadMoreThreshold;\n }\n\n public void setLoadMoreToTop(boolean isLoadMoreForTop) {\n this.isLoadMoreToTop = isLoadMoreForTop;\n }\n\n public boolean isLoadMoreToTop() {\n return isLoadMoreToTop;\n }\n\n public void setOnLoadMoreListener(@NonNull OnLoadMoreListener listener) {\n this.onLoadMoreListener = listener;\n }\n\n @Deprecated\n public void setLoadMoreCompleted() {\n this.isLoadingMore = false;\n }\n\n /**\n * drag & drop\n */\n public void enableDragAndDrop(@NonNull DragAndDropCallback dragAndDropCallback) {\n enableDragAndDrop(0, dragAndDropCallback);\n }\n\n public void enableDragAndDrop(@IdRes int dragHandleId, @NonNull DragAndDropCallback dragAndDropCallback) {\n DragAndDropOptions options = new DragAndDropOptions();\n options.setDragHandleId(dragHandleId);\n options.setCanLongPressToDrag(dragHandleId == 0);\n options.setDragAndDropCallback(dragAndDropCallback);\n options.setEnableDefaultEffect(dragAndDropCallback.enableDefaultRaiseEffect());\n DragAndDropHelper dragAndDropHelper = DragAndDropHelper.create(adapter, options);\n adapter.setDragAndDropHelper(dragAndDropHelper);\n dragAndDropHelper.attachToRecyclerView(this);\n }\n\n /**\n * swipe to dismiss\n */\n public void enableSwipeToDismiss(@NonNull SwipeToDismissCallback swipeToDismissCallback, @NonNull SwipeDirection... directions) {\n enableSwipeToDismiss(swipeToDismissCallback, new HashSet<>(Arrays.asList(directions)));\n }\n\n public void enableSwipeToDismiss(@NonNull SwipeToDismissCallback swipeToDismissCallback, @NonNull Set<SwipeDirection> directions) {\n SwipeToDismissOptions options = new SwipeToDismissOptions();\n options.setEnableDefaultFadeOutEffect(swipeToDismissCallback.enableDefaultFadeOutEffect());\n options.setSwipeToDismissCallback(swipeToDismissCallback);\n options.setSwipeDirections(directions);\n SwipeToDismissHelper helper = SwipeToDismissHelper.create(adapter, options);\n helper.attachToRecyclerView(this);\n }\n\n /**\n * snappy\n */\n public void enableSnappy() {\n enableSnappy(SnapAlignment.CENTER);\n }\n\n public void enableSnappy(@NonNull SnapAlignment alignment) {\n SnapHelper snapHelper = alignment.equals(SnapAlignment.CENTER) ?\n new LinearSnapHelper() : new StartSnapHelper(spacing);\n snapHelper.attachToRecyclerView(this);\n }\n\n /**\n * section header\n */\n public <T> void setSectionHeader(@NonNull SectionHeaderProvider<T> provider) {\n if (getLayoutManager() instanceof GridLayoutManager) {\n // todo\n return;\n }\n if (getLayoutManager() instanceof LinearLayoutManager) {\n addItemDecoration(new SectionHeaderItemDecoration(Utils.getTypeArgumentClass(provider.getClass()), provider));\n }\n }\n\n /**\n * cell operations\n */\n @Override\n public void addCell(@NonNull SimpleCell cell) {\n adapter.addCell(cell);\n }\n\n @Override\n public void addCell(int atPosition, @NonNull SimpleCell cell) {\n adapter.addCell(atPosition, cell);\n }\n\n @Override\n public void addCells(@NonNull List<? extends SimpleCell> cells) {\n adapter.addCells(cells);\n }\n\n @Override\n public void addCells(@NonNull SimpleCell... cells) {\n adapter.addCells(cells);\n }\n\n @Override\n public void addCells(int fromPosition, @NonNull List<? extends SimpleCell> cells) {\n adapter.addCells(fromPosition, cells);\n }\n\n @Override\n public void addCells(int fromPosition, @NonNull SimpleCell... cells) {\n adapter.addCells(fromPosition, cells);\n }\n\n @Override\n public <T extends SimpleCell & Updatable> void addOrUpdateCell(@NonNull T cell) {\n adapter.addOrUpdateCell(cell);\n }\n\n @Override\n public <T extends SimpleCell & Updatable> void addOrUpdateCells(@NonNull List<T> cells) {\n adapter.addOrUpdateCells(cells);\n }\n\n @Override\n public <T extends SimpleCell & Updatable> void addOrUpdateCells(@NonNull T... cells) {\n adapter.addOrUpdateCells(cells);\n }\n\n @Override\n public void removeCell(@NonNull SimpleCell cell) {\n adapter.removeCell(cell);\n }\n\n @Override\n public void removeCell(int atPosition) {\n adapter.removeCell(atPosition);\n }\n\n @Override\n public void removeCells(int fromPosition, int toPosition) {\n adapter.removeCells(fromPosition, toPosition);\n }\n\n @Override\n public void removeCells(int fromPosition) {\n adapter.removeCells(fromPosition);\n }\n\n @Override\n public void updateCell(int atPosition, @NonNull Object payload) {\n adapter.updateCell(atPosition, payload);\n }\n\n @Override\n public void updateCells(int fromPosition, int toPosition, @NonNull Object payloads) {\n adapter.updateCells(fromPosition, toPosition, payloads);\n }\n\n @Override\n public SimpleCell getCell(int atPosition) {\n return adapter.getCell(atPosition);\n }\n\n @Override\n public List<SimpleCell> getCells(int fromPosition, int toPosition) {\n return adapter.getCells(fromPosition, toPosition);\n }\n\n @Override\n public List<SimpleCell> getAllCells() {\n return adapter.getAllCells();\n }\n\n @Override\n public void removeAllCells() {\n removeAllCells(true);\n }\n\n // remove all cells and indicates that data is refreshing, so the empty view will not be shown.\n public void removeAllCells(boolean showEmptyStateView) {\n this.isRefreshing = !showEmptyStateView;\n this.isEmptyViewShown = false;\n adapter.removeAllCells();\n }\n\n public boolean isEmpty() {\n return getItemCount() <= 0;\n }\n\n public int getItemCount() {\n return isEmptyViewShown ? 0 : adapter.getItemCount();\n }\n\n public void smoothScrollToPosition(int position, ScrollPosition scrollPosition, boolean skipSpacing) {\n if (position < 0 || position >= getAllCells().size()) {\n return;\n }\n\n SimpleLinearSmoothScroller scroller = new SimpleLinearSmoothScroller(getContext(), skipSpacing);\n if (getLayoutManager().canScrollVertically()) {\n scroller.setVerticalScrollPosition(scrollPosition);\n } else if (getLayoutManager().canScrollHorizontally()) {\n scroller.setHorizontalScrollPosition(scrollPosition);\n }\n scroller.setTargetPosition(position);\n getLayoutManager().startSmoothScroll(scroller);\n }\n\n public void smoothScrollToPosition(int position, ScrollPosition scrollPosition) {\n smoothScrollToPosition(position, scrollPosition, false);\n }\n\n @Override\n public void smoothScrollToPosition(int position) {\n smoothScrollToPosition(position, ScrollPosition.TOP, false);\n }\n\n public void scrollToPosition(int position, ScrollPosition scrollPosition, boolean skipSpacing) {\n if (position < 0 || position >= getAllCells().size()) {\n return;\n }\n \n if (!(getLayoutManager() instanceof LinearLayoutManager)) {\n return;\n }\n\n LinearLayoutManager layoutManager = ((LinearLayoutManager) getLayoutManager());\n\n int padding = layoutManager.getOrientation() == HORIZONTAL ? layoutManager.getPaddingLeft() : layoutManager.getPaddingTop();\n\n if (scrollPosition == ScrollPosition.TOP) {\n int spacing = skipSpacing ? this.spacing : 0;\n layoutManager.scrollToPositionWithOffset(position, -(padding + spacing));\n } else if (scrollPosition == ScrollPosition.START) {\n int spacing = skipSpacing ? -this.spacing : this.spacing;\n layoutManager.scrollToPositionWithOffset(position, -padding + spacing / 2);\n }\n }\n\n /**\n * common\n */\n public int getGridSpanCount() {\n return gridSpanCount;\n }\n\n}",
"public abstract class SimpleSectionHeaderProvider<T> implements SectionHeaderProvider<T> {\n\n @NonNull\n public abstract View getSectionHeaderView(@NonNull T item, int position);\n\n public abstract boolean isSameSection(@NonNull T item, @NonNull T nextItem);\n\n @Override\n public boolean isSticky() {\n return false;\n }\n\n @Override\n public int getSectionHeaderMarginTop(@NonNull T item, int position) {\n return 0;\n }\n\n}"
] | import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import com.jaychang.demo.srv.cell.BookCell;
import com.jaychang.demo.srv.model.Book;
import com.jaychang.demo.srv.util.DataUtils;
import com.jaychang.demo.srv.util.Utils;
import com.jaychang.srv.SimpleRecyclerView;
import com.jaychang.srv.decoration.SimpleSectionHeaderProvider;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnCheckedChanged; | package com.jaychang.demo.srv;
public class SectionHeaderActivity extends BaseActivity {
@BindView(R.id.recyclerView)
SimpleRecyclerView recyclerView;
@BindView(R.id.stickyCheckbox)
CheckBox stickyCheckbox;
@BindView(R.id.marginTopCheckbox)
CheckBox marginTopCheckbox;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_section_header);
ButterKnife.bind(this);
init();
bindBooks();
}
private void init() { | recyclerView.setSectionHeader(new SimpleSectionHeaderProvider<Book>() { | 1 |
uvagfx/hipi | core/src/main/java/org/hipi/image/io/JpegCodec.java | [
"public class HipiImageHeader implements WritableComparable<HipiImageHeader> {\n\n /**\n * Enumeration of the image storage formats supported in HIPI (e.g, JPEG, PNG, etc.).\n */\n public enum HipiImageFormat {\n UNDEFINED(0x0), JPEG(0x1), PNG(0x2), PPM(0x3);\n\n private int format;\n\n /**\n * Creates an ImageFormat from an int.\n *\n * @param format Integer representation of ImageFormat.\n */\n HipiImageFormat(int format) {\n this.format = format;\n }\n\n /**\n * Creates an ImageFormat from an int.\n *\n * @param format Integer representation of ImageFormat.\n *\n * @return Associated ImageFormat.\n *\n * @throws IllegalArgumentException if the parameter value does not correspond to a valid\n * HipiImageFormat.\n */\n public static HipiImageFormat fromInteger(int format) throws IllegalArgumentException {\n for (HipiImageFormat fmt : values()) {\n if (fmt.format == format) {\n return fmt;\n }\n }\n throw new IllegalArgumentException(String.format(\"There is no HipiImageFormat enum value \" +\n \"associated with integer [%d]\", format));\n }\n\n /** \n * @return Integer representation of ImageFormat.\n */\n public int toInteger() {\n return format;\n }\n\n /**\n * Default HipiImageFormat.\n *\n * @return HipiImageFormat.UNDEFINED\n */\n public static HipiImageFormat getDefault() {\n return UNDEFINED;\n }\n\n } // public enum ImageFormat\n\n /**\n * Enumeration of the color spaces supported in HIPI.\n */\n public enum HipiColorSpace {\n UNDEFINED(0x0), RGB(0x1), LUM(0x2);\n\n private int cspace;\n\n /**\n * Creates a HipiColorSpace from an int\n *\n * @param format Integer representation of ColorSpace.\n */\n HipiColorSpace(int cspace) {\n this.cspace = cspace;\n }\n\n /**\n * Creates a HipiColorSpace from an int.\n *\n * @param cspace Integer representation of ColorSpace.\n *\n * @return Associated HipiColorSpace value.\n *\n * @throws IllegalArgumentException if parameter does not correspond to a valid HipiColorSpace.\n */\n public static HipiColorSpace fromInteger(int cspace) throws IllegalArgumentException {\n for (HipiColorSpace cs : values()) {\n if (cs.cspace == cspace) {\n\t return cs;\n }\n }\n throw new IllegalArgumentException(String.format(\"There is no HipiColorSpace enum value \" +\n \"with an associated integer value of %d\", cspace));\n }\n\n /** \n * Integer representation of ColorSpace.\n *\n * @return Integer representation of ColorSpace.\n */\n public int toInteger() {\n return cspace;\n }\n\n /**\n * Default HipiColorSpace. Currently (linear) RGB.\n *\n * @return Default ColorSpace enum value.\n */\n public static HipiColorSpace getDefault() {\n return RGB;\n }\n\n } // public enum ColorSpace\n\n private HipiImageFormat storageFormat; // format used to store image on HDFS\n private HipiColorSpace colorSpace; // color space of pixel data\n private int width; // width of image\n private int height; // height of image\n private int bands; // number of color bands (aka channels)\n\n /**\n * A map containing key/value pairs of meta data associated with the\n * image. These are (optionally) added during HIB construction and\n * are distinct from the exif data that may be stored within the\n * image file, which is accessed through the IIOMetadata object. For\n * example, this would be the correct place to store the image tile\n * offset and size if you were using a HIB to store a very large\n * image as a collection of smaller image tiles. Another example\n * would be using this dictionary to store the source url for an\n * image downloaded from the Internet.\n */\n private Map<String, String> metaData = new HashMap<String,String>();\n\n /**\n * EXIF data associated with the image represented as a\n * HashMap. {@see hipi.image.io.ExifDataUtils}\n */\n private Map<String, String> exifData = new HashMap<String,String>();\n\n /**\n * Creates an ImageHeader.\n */\n public HipiImageHeader(HipiImageFormat storageFormat, HipiColorSpace colorSpace, \n\t\t\t int width, int height,\n\t\t\t int bands, byte[] metaDataBytes, Map<String,String> exifData)\n throws IllegalArgumentException {\n if (width < 1 || height < 1 || bands < 1) {\n throw new IllegalArgumentException(String.format(\"Invalid spatial dimensions or number \" + \n \"of bands: (%d,%d,%d)\", width, height, bands));\n }\n this.storageFormat = storageFormat;\n this.colorSpace = colorSpace;\n this.width = width;\n this.height = height;\n this.bands = bands;\n if (metaDataBytes != null) {\n setMetaDataFromBytes(metaDataBytes);\n }\n this.exifData = exifData;\n }\n\n /**\n * Creates an ImageHeader by calling #readFields on the data input\n * object. Note that this function does not populate the exifData\n * field. That must be done with a separate method call.\n */\n public HipiImageHeader(DataInput input) throws IOException {\n readFields(input);\n }\n\n /**\n * Get the image storage type.\n *\n * @return Current image storage type.\n */\n public HipiImageFormat getStorageFormat() {\n return storageFormat;\n }\n\n /**\n * Get the image color space.\n *\n * @return Image color space.\n */\n public HipiColorSpace getColorSpace() {\n return colorSpace;\n }\n\n /**\n * Get width of image.\n *\n * @return Width of image.\n */\n public int getWidth() {\n return width;\n }\n\n /**\n * Get height of image.\n *\n * @return Height of image.\n */\n public int getHeight() {\n return height;\n }\n\n /**\n * Get number of color bands.\n *\n * @return Number of image bands.\n */\n public int getNumBands() {\n return bands;\n }\n\n /**\n * Adds an metadata field to this header object. The information consists of a\n * key-value pair where the key is an application-specific field name and the \n * value is the corresponding information for that field.\n * \n * @param key\n * the metadata field name\n * @param value\n * the metadata information\n */\n public void addMetaData(String key, String value) {\n metaData.put(key, value);\n }\n\n /**\n * Sets the entire metadata map structure.\n *\n * @param metaData hash map containing the metadata key/value pairs\n */\n public void setMetaData(HashMap<String, String> metaData) {\n this.metaData = new HashMap<String, String>(metaData);\n }\n\n /**\n * Attempt to retrieve metadata value associated with key.\n *\n * @param key field name of the desired metadata record\n * @return either the value corresponding to the key or null if the\n * key was not found\n */\n public String getMetaData(String key) {\n return metaData.get(key);\n }\n\n /**\n * Get the entire list of all metadata that applications have\n * associated with this image.\n *\n * @return a hash map containing the keys and values of the metadata\n */\n public HashMap<String, String> getAllMetaData() {\n return new HashMap<String, String>(metaData);\n }\n\n /**\n * Create a binary representation of the application-specific\n * metadata, ready to be serialized into a HIB file.\n *\n * @return A byte array containing the serialized hash map\n */\n public byte[] getMetaDataAsBytes() {\n try {\n String jsonText = JSONValue.toJSONString(metaData);\n final byte[] utf8Bytes = jsonText.getBytes(\"UTF-8\");\n return utf8Bytes;\n } catch (java.io.UnsupportedEncodingException e) {\n System.err.println(\"UTF-8 encoding exception in getMetaDataAsBytes()\");\n return null;\n }\n }\n\n /**\n * Recreates the general metadata from serialized bytes, usually\n * from the beginning of a HIB file.\n *\n * @param utf8Bytes UTF-8-encoded bytes of a JSON object\n * representing the data\n */\n @SuppressWarnings(\"unchecked\")\n public void setMetaDataFromBytes(byte[] utf8Bytes) {\n try {\n String jsonText = new String(utf8Bytes, \"UTF-8\");\n JSONObject jsonObject = (JSONObject)JSONValue.parse(jsonText);\n metaData = (HashMap)jsonObject;\n } catch (java.io.UnsupportedEncodingException e) {\n System.err.println(\"UTF-8 encoding exception in setMetaDataAsBytes()\");\n }\n }\n\n /**\n * Attempt to retrieve EXIF data value for specific key.\n *\n * @param key field name of the desired EXIF data record\n * @return either the value corresponding to the key or null if the\n * key was not found\n */\n public String getExifData(String key) {\n return exifData.get(key);\n }\n\n /**\n * Get the entire map of EXIF data.\n *\n * @return a hash map containing the keys and values of the metadata\n */\n public HashMap<String, String> getAllExifData() {\n return new HashMap<String, String>(exifData);\n }\n\n /**\n * Sets the entire EXIF data map structure.\n *\n * @param exifData hash map containing the EXIF data key/value pairs\n */\n public void setExifData(HashMap<String, String> exifData) {\n this.exifData = new HashMap<String, String>(exifData);\n }\n\n /**\n * Sets the current object to be equal to another\n * ImageHeader. Performs deep copy of meta data.\n *\n * @param header Target image header.\n */\n public void set(HipiImageHeader header) {\n this.storageFormat = header.getStorageFormat();\n this.colorSpace = header.getColorSpace();\n this.width = header.getWidth();\n this.height = header.getHeight();\n this.bands = header.getNumBands();\n this.metaData = header.getAllMetaData();\n this.exifData = header.getAllExifData();\n }\n\n /**\n * Produce readable string representation of header.\n * @see java.lang.Object#toString\n */\n @Override\n public String toString() {\n String metaText = JSONValue.toJSONString(metaData);\n return String.format(\"ImageHeader: (%d %d) %d x %d x %d meta: %s\", \n\t\t\t storageFormat.toInteger(), colorSpace.toInteger(), width, height, bands, metaText);\n } \n\n /**\n * Serializes the HipiImageHeader object into a simple uncompressed binary format using the\n * {@link java.io.DataOutput} interface.\n *\n * @see #readFields\n * @see org.apache.hadoop.io.WritableComparable#write\n */\n @Override\n public void write(DataOutput out) throws IOException {\n out.writeInt(storageFormat.toInteger());\n out.writeInt(colorSpace.toInteger());\n out.writeInt(width);\n out.writeInt(height);\n out.writeInt(bands);\n byte[] metaDataBytes = getMetaDataAsBytes();\n if (metaDataBytes == null || metaDataBytes.length == 0) {\n out.writeInt(0);\n } else {\n out.writeInt(metaDataBytes.length);\n out.write(metaDataBytes);\n }\n }\n\n /**\n * Deserializes HipiImageHeader object stored in a simple uncompressed binary format using the\n * {@link java.io.DataInput} interface. The first twenty bytes are the image storage type,\n * color space, width, height, and number of color bands (aka channels), all stored as ints,\n * followed by the meta data stored as a set of key/value pairs in JSON UTF-8 format.\n *\n * @see org.apache.hadoop.io.WritableComparable#readFields\n */\n @Override\n public void readFields(DataInput input) throws IOException {\n this.storageFormat = HipiImageFormat.fromInteger(input.readInt());\n this.colorSpace = HipiColorSpace.fromInteger(input.readInt());\n this.width = input.readInt();\n this.height = input.readInt();\n this.bands = input.readInt();\n int len = input.readInt();\n if (len > 0) {\n byte[] metaDataBytes = new byte[len];\n input.readFully(metaDataBytes, 0, len);\n setMetaDataFromBytes(metaDataBytes);\n }\n }\n\n /**\n * Compare method inherited from the {@link java.lang.Comparable} interface. This method is\n * currently incomplete and uses only the storage format to determine order.\n *\n * @param that another {@link HipiImageHeader} to compare with the current object\n *\n * @return An integer result of the comparison.\n *\n * @see java.lang.Comparable#compareTo\n */\n @Override\n public int compareTo(HipiImageHeader that) {\n\n int thisFormat = this.storageFormat.toInteger();\n int thatFormat = that.storageFormat.toInteger();\n\n return (thisFormat < thatFormat ? -1 : (thisFormat == thatFormat ? 0 : 1));\n }\n\n /**\n * Hash method inherited from the {@link java.lang.Object} base class. This method is\n * currently incomplete and uses only the storage format to determine this hash.\n *\n * @return hash code for this object\n *\n * @see java.lang.Object#hashCode\n */\n @Override\n public int hashCode() {\n return this.storageFormat.toInteger();\n }\n\n}",
"public enum HipiImageFormat {\n UNDEFINED(0x0), JPEG(0x1), PNG(0x2), PPM(0x3);\n\n private int format;\n\n /**\n * Creates an ImageFormat from an int.\n *\n * @param format Integer representation of ImageFormat.\n */\n HipiImageFormat(int format) {\n this.format = format;\n }\n\n /**\n * Creates an ImageFormat from an int.\n *\n * @param format Integer representation of ImageFormat.\n *\n * @return Associated ImageFormat.\n *\n * @throws IllegalArgumentException if the parameter value does not correspond to a valid\n * HipiImageFormat.\n */\n public static HipiImageFormat fromInteger(int format) throws IllegalArgumentException {\n for (HipiImageFormat fmt : values()) {\n if (fmt.format == format) {\n return fmt;\n }\n }\n throw new IllegalArgumentException(String.format(\"There is no HipiImageFormat enum value \" +\n \"associated with integer [%d]\", format));\n }\n\n /** \n * @return Integer representation of ImageFormat.\n */\n public int toInteger() {\n return format;\n }\n\n /**\n * Default HipiImageFormat.\n *\n * @return HipiImageFormat.UNDEFINED\n */\n public static HipiImageFormat getDefault() {\n return UNDEFINED;\n }\n\n} // public enum ImageFormat",
"public enum HipiColorSpace {\n UNDEFINED(0x0), RGB(0x1), LUM(0x2);\n\n private int cspace;\n\n /**\n * Creates a HipiColorSpace from an int\n *\n * @param format Integer representation of ColorSpace.\n */\n HipiColorSpace(int cspace) {\n this.cspace = cspace;\n }\n\n /**\n * Creates a HipiColorSpace from an int.\n *\n * @param cspace Integer representation of ColorSpace.\n *\n * @return Associated HipiColorSpace value.\n *\n * @throws IllegalArgumentException if parameter does not correspond to a valid HipiColorSpace.\n */\n public static HipiColorSpace fromInteger(int cspace) throws IllegalArgumentException {\n for (HipiColorSpace cs : values()) {\n if (cs.cspace == cspace) {\n return cs;\n }\n }\n throw new IllegalArgumentException(String.format(\"There is no HipiColorSpace enum value \" +\n \"with an associated integer value of %d\", cspace));\n }\n\n /** \n * Integer representation of ColorSpace.\n *\n * @return Integer representation of ColorSpace.\n */\n public int toInteger() {\n return cspace;\n }\n\n /**\n * Default HipiColorSpace. Currently (linear) RGB.\n *\n * @return Default ColorSpace enum value.\n */\n public static HipiColorSpace getDefault() {\n return RGB;\n }\n\n} // public enum ColorSpace",
"public class HipiImageFactory {\n\n private static final HipiImageFactory staticFloatImageFactory = \n new HipiImageFactory(HipiImageType.FLOAT);\n\n public static HipiImageFactory getFloatImageFactory() {\n return staticFloatImageFactory;\n }\n\n private static final HipiImageFactory staticByteImageFactory = \n new HipiImageFactory(HipiImageType.BYTE);\n\n public static HipiImageFactory getByteImageFactory() {\n return staticByteImageFactory;\n }\n\n private Class<?> imageClass = null;\n private HipiImageType imageType = HipiImageType.UNDEFINED;\n\n public HipiImageFactory(Class<? extends Mapper<?,?,?,?>> mapperClass)\n throws InstantiationException,\n\t IllegalAccessException,\n\t ExceptionInInitializerError,\n\t SecurityException,\n\t RuntimeException {\n\n findImageClass(mapperClass);\n \n HipiImage image = (HipiImage)imageClass.newInstance();\n imageType = image.getType();\n }\n\n public HipiImageFactory(HipiImageType imageType)\n throws IllegalArgumentException {\n\n\t// Call appropriate decode function based on type of image object\n switch (imageType) {\n\tcase FLOAT:\n\t imageClass = FloatImage.class;\n\t break;\n\tcase BYTE:\n\t imageClass = ByteImage.class;\n\t break;\n\tcase RAW:\n imageClass = RawImage.class;\n\tcase UNDEFINED:\n\tdefault:\n\t throw new IllegalArgumentException(\"Unexpected image type. Cannot proceed.\");\n\t}\n\n this.imageType = imageType;\n }\n\n private void findImageClass(Class<? extends Mapper<?,?,?,?>> mapperClass) \n throws SecurityException,\n\t RuntimeException {\n\n for (Method method : mapperClass.getMethods()) {\n // Find map method (there will be at least two: one in concrete\n // base class and one in abstract Mapper superclass)\n if (!method.getName().equals(\"map\")) {\n\tcontinue;\n }\n \n // Get parameter list of map method\n Class<?> params[] = method.getParameterTypes();\n if (params.length != 3) {\n\tcontinue;\n }\n\n // Use the fact that first parameter should be ImageHeader\n // object to identify target map method\n if (params[0] != HipiImageHeader.class) {\n\tcontinue;\n }\n \n // Store pointer to requested image class\n imageClass = params[1];\n }\n \n if (imageClass == null) {\n throw new RuntimeException(\"Failed to determine image class used in \" +\n \"mapper (second argument in map method).\");\n }\n\n if (!HipiImage.class.isAssignableFrom(imageClass)) {\n throw new RuntimeException(\"Found image class [\" + imageClass + \"], but it's not \" +\n \"derived from HipiImage as required.\");\n }\n\n }\n\n public HipiImageType getType() {\n return imageType;\n }\n \n public HipiImage createImage(HipiImageHeader imageHeader)\n throws InstantiationException,\n\t IllegalAccessException,\n\t ExceptionInInitializerError,\n\t SecurityException,\n\t IllegalArgumentException {\n \n HipiImage image = (HipiImage)imageClass.newInstance();\n image.setHeader(imageHeader);\n return image;\n \n }\n\n}",
"public abstract class PixelArray {\n\n public static final int TYPE_BYTE = 0;\n public static final int TYPE_USHORT = 1;\n public static final int TYPE_SHORT = 2;\n public static final int TYPE_INT = 3;\n public static final int TYPE_FLOAT = 4;\n public static final int TYPE_DOUBLE = 5;\n public static final int TYPE_UNDEFINED = 32;\n\n private static final int dataTypeSize[] = {1,2,2,4,4,8};\n\n /**\n * Integer value indicating underlying scalar value data type.\n */\n protected int dataType;\n\n /**\n * Size, in bytes, of a single scalar value in pixel array.\n */\n protected int size;\n\n /**\n * Static function that reports size, in bytes, of a single scalar value for different types\n * of pixel arrays.\n *\n * @param type scalar value type\n *\n * @return size, in bytes, of single scalar value for specified type\n */\n public static int getDataTypeSize(int type) {\n if (type < TYPE_BYTE || type > TYPE_DOUBLE) {\n throw new IllegalArgumentException(\"Unknown data type \"+type);\n }\n return dataTypeSize[type];\n }\n\n public PixelArray() {\n this.dataType = TYPE_UNDEFINED;\n this.size = 0;\n }\n\n protected PixelArray(int dataType, int size) {\n this.dataType = dataType;\n this.size = size;\n }\n\n public int getDataType() {\n return dataType;\n }\n\n public int getSize() {\n return size;\n }\n\n public abstract void setSize(int size) throws IllegalArgumentException;\n\n public abstract byte[] getByteArray();\n\n public abstract void setFromByteArray(byte[] bytes) throws IllegalArgumentException;\n\n public abstract int getElem(int i);\n\n public abstract int getElemNonLinSRGB(int i);\n\n public abstract void setElem(int i, int val);\n\n public abstract void setElemNonLinSRGB(int i, int val);\n\n public float getElemFloat(int i) {\n return (float)getElem(i);\n }\n\n public void setElemFloat(int i, float val) {\n setElem(i,(int)val);\n }\n\n public double getElemDouble(int i) {\n return (double)getElem(i);\n }\n\n public void setElemDouble(int i, double val) {\n setElem(i,(int)val);\n }\n\n}"
] | import org.hipi.image.HipiImageHeader;
import org.hipi.image.HipiImageHeader.HipiImageFormat;
import org.hipi.image.HipiImageHeader.HipiColorSpace;
import org.hipi.image.HipiImage;
import org.hipi.image.HipiImage.HipiImageType;
import org.hipi.image.RasterImage;
import org.hipi.image.HipiImageFactory;
import org.hipi.image.PixelArray;
import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.HashMap;
import javax.imageio.IIOImage;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageOutputStream; | package org.hipi.image.io;
/**
* Extends {@link ImageCodec} and serves as both an {@link ImageDecoder} and
* {@link ImageEncoder} for the JPEG image storage format.
*/
public class JpegCodec extends ImageCodec {
private static final JpegCodec staticObject = new JpegCodec();
public static JpegCodec getInstance() {
return staticObject;
}
public HipiImageHeader decodeHeader(InputStream inputStream, boolean includeExifData)
throws IOException, IllegalArgumentException {
DataInputStream dis = new DataInputStream(new BufferedInputStream(inputStream));
dis.mark(Integer.MAX_VALUE);
// all JPEGs start with -40
short magic = dis.readShort();
if (magic != -40)
return null;
int width=0, height=0, depth=0;
byte[] data = new byte[6];
// read in each block to determine resolution and bit depth
for (;;) {
dis.read(data, 0, 4);
if ((data[0] & 0xff) != 0xff)
return null;
if ((data[1] & 0xff) == 0x01 || ((data[1] & 0xff) >= 0xd0 && (data[1] & 0xff) <= 0xd7))
continue;
long length = (((data[2] & 0xff) << 8) | (data[3] & 0xff)) - 2;
if ((data[1] & 0xff) == 0xc0 || (data[1] & 0xff) == 0xc2) {
dis.read(data);
height = ((data[1] & 0xff) << 8) | (data[2] & 0xff);
width = ((data[3] & 0xff) << 8) | (data[4] & 0xff);
depth = data[0] & 0xff;
break;
} else {
while (length > 0) {
long skipped = dis.skip(length);
if (skipped == 0)
break;
length -= skipped;
}
}
}
if (depth != 8) {
throw new IllegalArgumentException(String.format("Image has unsupported bit depth [%d].", depth));
}
HashMap<String,String> exifData = null;
if (includeExifData) {
dis.reset();
exifData = ExifDataReader.extractAndFlatten(dis);
}
| return new HipiImageHeader(HipiImageFormat.JPEG, HipiColorSpace.RGB, | 2 |
CS-SI/Stavor | stavor/src/main/java/org/nikkii/embedhttp/HttpServer.java | [
"public interface HttpRequestHandler {\n\n\t/**\n\t * Handle a request\n\t * \n\t * @param request\n\t * The request to handle\n\t * @return The response if handled, or null to let another class handle it.\n\t */\n\tpublic HttpResponse handleRequest(HttpRequest request);\n}",
"public enum HttpCapability {\n\tHTTP_1_1, STANDARD_POST, MULTIPART_POST, THREADEDRESPONSE, COOKIES\n}",
"public class HttpRequest {\n\n\t/**\n\t * The session which constructed this request\n\t */\n\tprivate HttpSession session;\n\n\t/**\n\t * The request method\n\t */\n\tprivate HttpMethod method;\n\n\t/**\n\t * The requested URI\n\t */\n\tprivate String uri;\n\n\t/**\n\t * The request headers\n\t */\n\tprivate Map<String, String> headers;\n\n\t/**\n\t * Raw Query String\n\t */\n\tprivate String queryString;\n\n\t/**\n\t * Raw POST data (Not applicable for form-encoded, automatically parsed)\n\t */\n\tprivate String data;\n\t\n\t/**\n\t * The parsed GET data\n\t */\n\tprivate Map<String, Object> getData;\n\n\t/**\n\t * The parsed POST data\n\t */\n\tprivate Map<String, Object> postData;\n\n\t/**\n\t * The list of parsed cookies\n\t */\n\tprivate Map<String, HttpCookie> cookies;\n\n\t/**\n\t * Construct a new HTTP request\n\t * \n\t * @param session\n\t * The session which initiated the request\n\t * @param method\n\t * The method used to request this page\n\t * @param uri\n\t * The URI of the request\n\t * @param headers\n\t * The request headers\n\t */\n\tpublic HttpRequest(HttpSession session, HttpMethod method, String uri, Map<String, String> headers) {\n\t\tthis.session = session;\n\t\tthis.method = method;\n\t\tthis.uri = uri;\n\t\tthis.headers = headers;\n\t}\n\n\t/**\n\t * Get the session which initiated this request\n\t * \n\t * @return The session\n\t */\n\tpublic HttpSession getSession() {\n\t\treturn session;\n\t}\n\n\t/**\n\t * Get the request method\n\t * \n\t * @return The request method\n\t */\n\tpublic HttpMethod getMethod() {\n\t\treturn method;\n\t}\n\n\t/**\n\t * Get the request uri\n\t * \n\t * @return The request uri\n\t */\n\tpublic String getUri() {\n\t\treturn uri;\n\t}\n\n\t/**\n\t * Get the request headers\n\t * \n\t * @return The request headers\n\t */\n\tpublic Map<String, String> getHeaders() {\n\t\treturn headers;\n\t}\n\t\n\t/**\n\t * Gets a request header\n\t * @param key\n\t * \t\t\tThe request header key\n\t * @return\n\t * \t\t\tThe header value\n\t */\n\tpublic String getHeader(String key) {\n\t\treturn headers.get(HttpUtil.capitalizeHeader(key));\n\t}\n\n\t/**\n\t * Set the request's raw POST data\n\t * \n\t * @param data\n\t * The data to set\n\t */\n\tpublic void setData(String data) {\n\t\tthis.data = data;\n\t}\n\n\t/**\n\t * Set the request's parsed GET data\n\t * @param getData\n\t * \t\t\tThe parsed data map to set\n\t */\n\tpublic void setGetData(Map<String, Object> getData) {\n\t\tthis.getData = getData;\n\t}\n\n\t/**\n\t * Set the request's parsed POST data\n\t * \n\t * @param postData\n\t * The parsed data map to set\n\t */\n\tpublic void setPostData(Map<String, Object> postData) {\n\t\tthis.postData = postData;\n\t}\n\t\n\t/**\n\t * Set the request's URI\n\t * \n\t * @param uri\n\t * \t\t\tThe uri to set\n\t */\n\tpublic void setUri(String uri) {\n\t\tthis.uri = uri;\n\t}\n\t\n\t/**\n\t * Sets the request's query string\n\t * @param queryString\n\t * \t\t\tThe query string to set\n\t */\n\tpublic void setQueryString(String queryString) {\n\t\tthis.queryString = queryString;\n\t}\n\t\n\t/**\n\t * Gets the request's query string\n\t * \n\t * @return\n\t * \t\t\tThe query string\n\t */\n\tpublic String getQueryString() {\n\t\treturn queryString;\n\t}\n\n\t/**\n\t * Get the request's raw POST data\n\t * \n\t * @return The request's POST data\n\t */\n\tpublic String getData() {\n\t\treturn data;\n\t}\n\t\n\t/**\n\t * Get the request's parsed GET data\n\t * \n\t * @return the parsed data map\n\t */\n\tpublic Map<String, Object> getGetData() {\n\t\treturn getData;\n\t}\n\n\t/**\n\t * Get the request's parsed POST data\n\t * \n\t * @return The parsed data map\n\t */\n\tpublic Map<String, Object> getPostData() {\n\t\treturn postData;\n\t}\n\n\t/**\n\t * Set the request's cookies\n\t * \n\t * @param cookies\n\t * \t\t\tThe cookie list\n\t */\n\tpublic void setCookies(List<HttpCookie> cookies) {\n\t\tMap<String, HttpCookie> map = new HashMap<String, HttpCookie>();\n\t\tfor(HttpCookie cookie : cookies) {\n\t\t\tmap.put(cookie.getName(), cookie);\n\t\t}\n\t\tthis.cookies = map;\n\t}\n\t\n\t/**\n\t * Get a cookie with the specified name\n\t * @param name\n\t * \t\t\tThe cookie name\n\t * @return\n\t * \t\t\tThe cookie\n\t */\n\tpublic HttpCookie getCookie(String name) {\n\t\treturn cookies.get(name);\n\t}\n\t\n\t/**\n\t * Get the request's cookies\n\t * @return\n\t * \t\t\tThe cookie list\n\t */\n\tpublic Collection<HttpCookie> getCookies() {\n\t\treturn cookies == null ? null : cookies.values();\n\t}\n\n\t@Override\n\tpublic void finalize() {\n\t\tif (postData != null) {\n\t\t\tfor (Object value : postData.values()) {\n\t\t\t\tif (value instanceof HttpFileUpload) {\n\t\t\t\t\tHttpFileUpload u = (HttpFileUpload) value;\n\t\t\t\t\tif (!u.getTempFile().delete()) {\n\t\t\t\t\t\tu.getTempFile().deleteOnExit();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}",
"public class HttpResponse {\n\n\t/**\n\t * The Http response status\n\t */\n\tprivate HttpStatus status;\n\n\t/**\n\t * The Http response headers\n\t */\n\tprivate Map<String, List<Object>> headers = new HashMap<String, List<Object>>();\n\n\t/**\n\t * The response (InputStream, String or byte array)\n\t */\n\tprivate Object response;\n\n\t/**\n\t * The response length\n\t */\n\tprivate long responseLength = 0;\n\n\t/**\n\t * Construct a new empty Http response\n\t */\n\tpublic HttpResponse() {\n\t\tthis.status = HttpStatus.OK;\n\t\tthis.response = \"\";\n\t}\n\n\t/**\n\t * Construct a new empty Http response\n\t */\n\tpublic HttpResponse(HttpStatus status) {\n\t\tthis.status = status;\n\t\tthis.response = \"\";\n\t}\n\n\t/**\n\t * Construct a new Http Response from an InputStream. Note: When using this\n\t * make sure to add a request header for length! The auto-calculated header\n\t * WILL NOT be accurate.\n\t * \n\t * @param status\n\t * The response status\n\t * @param response\n\t * The response data\n\t */\n\tpublic HttpResponse(HttpStatus status, InputStream response) {\n\t\tthis.status = status;\n\t\tthis.response = response;\n\t\ttry {\n\t\t\tthis.responseLength = response.available();\n\t\t} catch (IOException e) {\n\t\t\t// This shouldn't happen.\n\t\t}\n\t}\n\n\t/**\n\t * Construct a new Http response with a string as the data\n\t * \n\t * @param status\n\t * The response status\n\t * @param response\n\t * The response data\n\t */\n\tpublic HttpResponse(HttpStatus status, String response) {\n\t\tthis.status = status;\n\t\tthis.response = response;\n\t\tthis.responseLength = response.length();\n\t}\n\n\t/**\n\t * Construct a new Http response with a byte array as the data\n\t * \n\t * @param status\n\t * The response status\n\t * @param response\n\t * The response data\n\t */\n\tpublic HttpResponse(HttpStatus status, byte[] response) {\n\t\tthis.status = status;\n\t\tthis.response = response;\n\t\tthis.responseLength = response.length;\n\t}\n\n\t/**\n\t * Get the Http response status\n\t * \n\t * @return The response status\n\t */\n\tpublic HttpStatus getStatus() {\n\t\treturn status;\n\t}\n\t\n\t/**\n\t * Adds a cookie to this response\n\t * @param cookie\n\t * \t\t\tThe cookie to add\n\t */\n\tpublic void addCookie(HttpCookie cookie) {\n\t\taddHeader(HttpHeader.SET_COOKIE, cookie.toHeader());\n\t}\n\n\t/**\n\t * Add a header to the response\n\t * \n\t * @param key\n\t * The header name\n\t * @param value\n\t * The header value\n\t */\n\tpublic void addHeader(String key, Object value) {\n\t\tList<Object> values = headers.get(key);\n\t\tif(values == null) {\n\t\t\theaders.put(key, values = new ArrayList<Object>());\n\t\t}\n\t\tvalues.add(value);\n\t}\n\n\t/**\n\t * Get a response header\n\t * \n\t * @param key\n\t * The header name (Case sensitive)\n\t * @return The header value\n\t */\n\tpublic List<Object> getHeaders(String key) {\n\t\treturn headers.get(key);\n\t}\n\n\t/**\n\t * Get the response headers\n\t * \n\t * @return The header map\n\t */\n\tpublic Map<String, List<Object>> getHeaders() {\n\t\treturn headers;\n\t}\n\n\t/**\n\t * Get the response as the specified type\n\t * \n\t * @return The response\n\t */\n\t@SuppressWarnings(\"unchecked\")\n\tpublic <T> T getResponse() {\n\t\treturn (T) response;\n\t}\n\t\n\t/**\n\t * Set the response string\n\t * \n\t * @param response\n\t * \t\t\tThe response to set\n\t */\n\tpublic void setResponse(String response) {\n\t\tthis.response = response;\n\t\ttry {\n\t\t\tthis.responseLength = response.getBytes(\"UTF-8\").length;\n\t\t} catch (UnsupportedEncodingException e) {\n\t\t\tthis.responseLength = response.length();\n\t\t}\n\t}\n\n\t/**\n\t * Set the response Input Stream\n\t * \n\t * @param response\n\t * \t\t\tThe response to set\n\t */\n\tpublic void setResponse(InputStream response) {\n\t\tthis.response = response;\n\t\ttry {\n\t\t\tthis.responseLength = response.available();\n\t\t} catch (IOException e) {\n\t\t\t// This shouldn't happen.\n\t\t}\n\t}\n\n\t/**\n\t * Get the response length\n\t * \n\t * @return The response length, may not be accurate\n\t */\n\tpublic long getResponseLength() {\n\t\treturn responseLength;\n\t}\n\n\t/**\n\t * Set the response length\n\t * \n\t * @param length\n\t * The response length to set.\n\t */\n\tpublic void setResponseLength(long responseLength) {\n\t\tthis.responseLength = responseLength;\n\t}\n}",
"public class HttpSession implements Runnable {\n\n\t/**\n\t * The HttpServer which this session belongs to\n\t */\n\tprivate HttpServer server;\n\n\t/**\n\t * The socket of the client\n\t */\n\tprivate Socket socket;\n\n\t/**\n\t * The InputStream of the socket\n\t */\n\tprivate InputStream input;\n\n\t/**\n\t * The OutputStream of the socket\n\t */\n\tprivate OutputStream output;\n\n\tpublic HttpSession(HttpServer server, Socket socket) throws IOException {\n\t\tthis.server = server;\n\t\tthis.socket = socket;\n\t\tthis.input = socket.getInputStream();\n\t\tthis.output = socket.getOutputStream();\n\t}\n\n\t/**\n\t * Parse the Http Request\n\t */\n\t@Override\n\tpublic void run() {\n\t\ttry {\n\t\t\tbyte[] bytes = new byte[8192];\n\n\t\t\tint pos = 0;\n\t\t\t\n\t\t\t// Read the first part of the header\n\t\t\twhile (true) {\n\t\t\t\tint read = input.read();\n\t\t\t\tif (read == -1) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tbytes[pos] = (byte) read;\n\t\t\t\tif (pos >= 4) {\n\t\t\t\t\t// Find \\r\\n\\r\\n\n\t\t\t\t\tif (bytes[pos - 3] == '\\r' && bytes[pos - 2] == '\\n' && bytes[pos - 1] == '\\r' && bytes[pos] == '\\n') {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tpos++;\n\t\t\t}\n\n\t\t\t// Read from the header data\n\t\t\tBufferedReader reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(bytes, 0, pos)));\n\n\t\t\t// Read the first line, defined as the status line\n\t\t\tString l = reader.readLine();\n\n\t\t\t// Sanity check, after not returning data the client MIGHT attempt\n\t\t\t// to send something back and it will end up being something we\n\t\t\t// cannot read.\n\t\t\tif (l == null) {\n\t\t\t\tsendError(HttpStatus.BAD_REQUEST, HttpStatus.BAD_REQUEST.toString());\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Otherwise continue on\n\t\t\tint idx = l.indexOf(' ');\n\n\t\t\t// Split out the method and path\n\t\t\tHttpMethod method = HttpMethod.valueOf(l.substring(0, idx));\n\n\t\t\t// If it's an known method it won't be defined in the enum\n\t\t\tif (method == null) {\n\t\t\t\tsendError(HttpStatus.METHOD_NOT_ALLOWED, \"This server currently does not support this method.\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// The URI\n\t\t\tString path = l.substring(idx + 1, l.lastIndexOf(' '));\n\n\t\t\t// Parse the headers\n\t\t\tMap<String, String> headers = new HashMap<String, String>();\n\t\t\twhile ((l = reader.readLine()) != null) {\n\t\t\t\t// End header.\n\t\t\t\tif (l.equals(\"\"))\n\t\t\t\t\tbreak;\n\n\t\t\t\t// Headers are usually Key: Value\n\t\t\t\tString key = l.substring(0, l.indexOf(':'));\n\t\t\t\tString value = l.substring(l.indexOf(':') + 1).trim();\n\n\t\t\t\t// Put the header in the map, correcting the header key if\n\t\t\t\t// needed.\n\t\t\t\theaders.put(HttpUtil.capitalizeHeader(key), value);\n\t\t\t}\n\n\t\t\t// Close the reader used for the header\n\t\t\treader.close();\n\n\t\t\tHttpRequest request = new HttpRequest(this, method, path, headers);\n\t\t\t\n\t\t\tint questionIdx = path.indexOf('?');\n\t\t\tif(questionIdx != -1) {\n\t\t\t\tString queryString = path.substring(questionIdx+1);\n\t\t\t\trequest.setQueryString(queryString);\n\t\t\t\trequest.setGetData(HttpUtil.parseData(queryString));\n\t\t\t\t\n\t\t\t\tpath = path.substring(0, questionIdx);\n\t\t\t\trequest.setUri(path);\n\t\t\t}\n\t\t\t\n\t\t\t// Parse cookies, only if the server has the capability enabled (to save time, processing power, and memory if it isn't used)\n\t\t\tif(headers.containsKey(HttpHeader.COOKIE) && server.hasCapability(HttpCapability.COOKIES)) {\n\t\t\t\tList<HttpCookie> cookies = new LinkedList<HttpCookie>();\n\t\t\t\tStringTokenizer tok = new StringTokenizer(headers.get(HttpHeader.COOKIE), \";\");\n\t\t\t\twhile(tok.hasMoreTokens()) {\n\t\t\t\t\tString token = tok.nextToken();\n\t\t\t\t\tint eqIdx = token.indexOf('=');\n\t\t\t\t\tif(eqIdx == -1) {\n\t\t\t\t\t\t// Invalid cookie\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tString key = token.substring(0, eqIdx);\n\t\t\t\t\tString value = token.substring(eqIdx + 1);\n\t\t\t\t\t\n\t\t\t\t\tcookies.add(new HttpCookie(key, value));\n\t\t\t\t}\n\t\t\t\trequest.setCookies(cookies);\n\t\t\t}\n\n\t\t\t// Read the request data\n\t\t\tif (method == HttpMethod.POST) {\n\t\t\t\tboolean acceptsStandard = server.hasCapability(HttpCapability.STANDARD_POST), acceptsMultipart = server.hasCapability(HttpCapability.MULTIPART_POST);\n\t\t\t\t// Make sure the server will accept POST or Multipart POST\n\t\t\t\t// before we start checking the content\n\t\t\t\tif (acceptsStandard || acceptsMultipart) {\n\t\t\t\t\t// Validate that there's a length header\n\t\t\t\t\tif (!headers.containsKey(HttpHeader.CONTENT_LENGTH)) {\n\t\t\t\t\t\t// If there isn't, send the correct response\n\t\t\t\t\t\tsendError(HttpStatus.LENGTH_REQUIRED, HttpStatus.LENGTH_REQUIRED.toString());\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Otherwise, continue on\n\t\t\t\t\t\tint contentLength = Integer.parseInt(headers.get(HttpHeader.CONTENT_LENGTH));\n\n\t\t\t\t\t\tString contentTypeHeader = headers.get(HttpHeader.CONTENT_TYPE);\n\n\t\t\t\t\t\t// Copy it to trim to what we need, keeping the original\n\t\t\t\t\t\t// to parse the boundary\n\t\t\t\t\t\tString contentType = contentTypeHeader;\n\n\t\t\t\t\t\tif (contentTypeHeader.indexOf(';') != -1) {\n\t\t\t\t\t\t\tcontentType = contentTypeHeader.substring(0, contentTypeHeader.indexOf(';'));\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// Check the content type\n\t\t\t\t\t\tif (contentType.equalsIgnoreCase(\"multipart/form-data\")) {\n\t\t\t\t\t\t\tif (acceptsMultipart) {\n\t\t\t\t\t\t\t\t// The server will accept post requests with\n\t\t\t\t\t\t\t\t// multipart data\n\t\t\t\t\t\t\t\tString boundary = contentTypeHeader.substring(contentTypeHeader.indexOf(';')).trim();\n\t\t\t\t\t\t\t\tboundary = boundary.substring(boundary.indexOf('=') + 1);\n\t\t\t\t\t\t\t\t// Parse file uploads etc.\n\t\t\t\t\t\t\t\trequest.setPostData(readMultipartData(boundary));\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t// The server has the multipart post\n\t\t\t\t\t\t\t\t// capabilities disabled\n\t\t\t\t\t\t\t\tsendError(HttpStatus.BAD_REQUEST, \"This server does not support multipart/form-data requests.\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tif (acceptsStandard) {\n\t\t\t\t\t\t\t\t// Read the reported content length, TODO some\n\t\t\t\t\t\t\t\t// kind of check/timeout to make sure it won't\n\t\t\t\t\t\t\t\t// hang the thread?\n\t\t\t\t\t\t\t\tbyte[] b = new byte[contentLength];\n\t\t\t\t\t\t\t\tint read, totalRead = 0;\n\t\t\t\t\t\t\t\twhile (contentLength - totalRead > 0 && (read = input.read(b, totalRead, contentLength - totalRead)) > -1) {\n\t\t\t\t\t\t\t\t\ttotalRead += read;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t// We either read all of the data, or the\n\t\t\t\t\t\t\t\t// connection closed.\n\t\t\t\t\t\t\t\tif (totalRead < contentLength) {\n\t\t\t\t\t\t\t\t\tsendError(HttpStatus.BAD_REQUEST, \"Unable to read correct amount of data!\");\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tString data = new String(b);\n\t\t\t\t\t\t\t\t\tif (contentType.equalsIgnoreCase(\"application/x-www-form-urlencoded\")) {\n\t\t\t\t\t\t\t\t\t\t// It is FOR SURE regular data.\n\t\t\t\t\t\t\t\t\t\trequest.setPostData(HttpUtil.parseData(data));\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\t// Could be JSON or XML etc\n\t\t\t\t\t\t\t\t\t\trequest.setData(data);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t// The server has the Standard post capabilities\n\t\t\t\t\t\t\t\t// disabled\n\t\t\t\t\t\t\t\tsendError(HttpStatus.BAD_REQUEST, \"This server does not support POST requests.\");\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\t// The server has the Standard and Multipart capabilities\n\t\t\t\t\t// disabled\n\t\t\t\t\tsendError(HttpStatus.METHOD_NOT_ALLOWED, \"This server does not support POST requests.\");\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tserver.dispatchRequest(request);\n\t\t} catch (SocketException e) {\n\t\t\t//Socket was closed probably\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\t/**\n\t * Read the data from a multipart/form-data request\n\t * \n\t * @param boundary\n\t * The boundary specified by the client\n\t * @return A map of the POST data.\n\t * @throws IOException\n\t * If an error occurs\n\t */\n\tpublic Map<String, Object> readMultipartData(String boundary) throws IOException {\n\t\t// Boundaries are '--' + the boundary.\n\t\tboundary = \"--\" + boundary;\n\t\t// Form data\n\t\tMap<String, Object> form = new HashMap<String, Object>();\n\t\t// Implementation of a reader to parse out form boundaries.\n\t\tMultipartReader reader = new MultipartReader(input, boundary);\n\t\tString l;\n\t\twhile ((l = reader.readLine()) != null) {\n\t\t\tif (!l.startsWith(boundary) || l.startsWith(boundary) && l.endsWith(\"--\")) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t// Read headers\n\t\t\tMap<String, String> props = new HashMap<String, String>();\n\t\t\twhile ((l = reader.readLine()) != null && l.trim().length() > 0) {\n\t\t\t\t// Properties\n\t\t\t\tString key = HttpUtil.capitalizeHeader(l.substring(0, l.indexOf(':')));\n\t\t\t\tString value = l.substring(l.indexOf(':') + 1);\n\t\t\t\tif (value.charAt(0) == ' ')\n\t\t\t\t\tvalue = value.substring(1);\n\n\t\t\t\tprops.put(key, value);\n\t\t\t}\n\t\t\t// Check if the line STILL isn't null\n\t\t\tif (l != null) {\n\t\t\t\tString contentDisposition = props.get(HttpHeader.CONTENT_DISPOSITION);\n\t\t\t\tMap<String, String> disposition = new HashMap<String, String>();\n\t\t\t\tString[] dis = contentDisposition.split(\"; \");\n\t\t\t\tfor (String s : dis) {\n\t\t\t\t\tint eqIdx = s.indexOf('=');\n\t\t\t\t\tif (eqIdx != -1) {\n\t\t\t\t\t\tString key = s.substring(0, eqIdx);\n\t\t\t\t\t\tString value = s.substring(eqIdx + 1).trim();\n\t\t\t\t\t\tif (value.charAt(0) == '\"') {\n\t\t\t\t\t\t\tvalue = value.substring(1, value.length() - 1);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdisposition.put(key, value);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tString name = disposition.get(\"name\");\n\t\t\t\tif (props.containsKey(HttpHeader.CONTENT_TYPE)) {\n\t\t\t\t\tString fileName = disposition.get(\"filename\");\n\t\t\t\t\t// Create a temporary file, this'll hopefully be deleted\n\t\t\t\t\t// when the request object has finalize() called\n\t\t\t\t\tFile tmp = File.createTempFile(\"upload\", fileName);\n\t\t\t\t\t// Open an output stream to the new file\n\t\t\t\t\tFileOutputStream output = new FileOutputStream(tmp);\n\t\t\t\t\t// Read the file data right from the connection, NO MEMORY\n\t\t\t\t\t// CACHE.\n\t\t\t\t\tbyte[] buffer = new byte[1024];\n\t\t\t\t\twhile (true) {\n\t\t\t\t\t\tint read = reader.readUntilBoundary(buffer, 0, buffer.length);\n\t\t\t\t\t\tif (read == -1) {\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t}\n\t\t\t\t\t\toutput.write(buffer, 0, read);\n\t\t\t\t\t}\n\t\t\t\t\t// Close it\n\t\t\t\t\toutput.close();\n\t\t\t\t\t// Put the temp file\n\t\t\t\t\tform.put(name, new HttpFileUpload(fileName, tmp));\n\t\t\t\t} else {\n\t\t\t\t\tString value = \"\";\n\t\t\t\t\t// String value\n\t\t\t\t\twhile ((l = reader.readLineUntilBoundary()) != null) {\n\t\t\t\t\t\tvalue += l;\n\t\t\t\t\t}\n\t\t\t\t\tform.put(name, value);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn form;\n\t}\n\n\t/**\n\t * Send a response\n\t * \n\t * @param resp\n\t * The response to send\n\t * @throws IOException\n\t * If an error occurred while sending\n\t */\n\tpublic void sendResponse(HttpResponse resp) throws IOException {\n\t\tsendResponse(resp, true);\n\t}\n\n\t/**\n\t * Send a response\n\t * \n\t * @param resp\n\t * The response to send\n\t * @param close\n\t * Whether to close the session\n\t * @throws IOException\n\t * If an error occurred while sending\n\t */\n\tpublic void sendResponse(HttpResponse resp, boolean close) throws IOException {\n\t\tStringBuilder header = new StringBuilder();\n\t\theader.append(\"HTTP/1.1\").append(' ').append(resp.getStatus().getCode()).append(' ').append(resp.getStatus());\n\t\theader.append('\\r').append('\\n');\n\t\t// Set the content type header if it's not already set\n\t\tif (!resp.getHeaders().containsKey(HttpHeader.CONTENT_TYPE)) {\n\t\t\tresp.addHeader(HttpHeader.CONTENT_TYPE, \"text/html; charset=utf-8\");\n\t\t}\n\t\t// Set the content length header if it's not already set\n\t\tif (!resp.getHeaders().containsKey(HttpHeader.CONTENT_LENGTH)) {\n\t\t\tresp.addHeader(HttpHeader.CONTENT_LENGTH, resp.getResponseLength());\n\t\t}\n\t\t// Copy in the headers\n\t\tfor (Entry<String, List<Object>> entry : resp.getHeaders().entrySet()) {\n\t\t\tString headerName = HttpUtil.capitalizeHeader(entry.getKey());\n\t\t\tfor(Object o : entry.getValue()) {\n\t\t\t\theader.append(headerName);\n\t\t\t\theader.append(':').append(' ');\n\t\t\t\theader.append(o);\n\t\t\t\theader.append('\\r').append('\\n');\n\t\t\t}\n\t\t}\n\t\theader.append('\\r').append('\\n');\n\t\t// Write the header\n\t\toutput.write(header.toString().getBytes(\"UTF-8\"));\n\t\t// Responses can be InputStreams or Strings\n\t\tif (resp.getResponse() instanceof InputStream) {\n\t\t\t// InputStreams will block the session thread (No big deal) and send\n\t\t\t// data without loading it into memory\n\t\t\tInputStream res = resp.getResponse();\n\t\t\ttry {\n\t\t\t\t// Write the body\n\t\t\t\tbyte[] buffer = new byte[1024];\n\t\t\t\twhile (true) {\n\t\t\t\t\tint read = res.read(buffer, 0, buffer.length);\n\t\t\t\t\tif (read == -1)\n\t\t\t\t\t\tbreak;\n\t\t\t\t\toutput.write(buffer, 0, read);\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tres.close();\n\t\t\t}\n\t\t} else if (resp.getResponse() instanceof String) {\n\t\t\tString responseString = (String) resp.getResponse();\n\t\t\toutput.write(responseString.getBytes(\"UTF-8\"));\n\t\t} else if (resp.getResponse() instanceof byte[]) {\n\t\t\toutput.write((byte[]) resp.getResponse());\n\t\t}\n\t\t// Close it if required.\n\t\tif (close) {\n\t\t\tsocket.close();\n\t\t}\n\t}\n\n\t/**\n\t * Send an HttpStatus\n\t * \n\t * @param status\n\t * The status to send\n\t * @throws IOException\n\t * If an error occurred while sending\n\t */\n\tpublic void sendError(HttpStatus status) throws IOException {\n\t\tsendResponse(new HttpResponse(status, status.toString()));\n\t}\n\n\t/**\n\t * Send an HttpStatus with the specified error message\n\t * \n\t * @param status\n\t * The status to send\n\t * @param message\n\t * The error message to send\n\t * @throws IOException\n\t * If an error occurred while sending\n\t */\n\tpublic void sendError(HttpStatus status, String message) throws IOException {\n\t\tsendResponse(new HttpResponse(status, status.toString() + ':' + message));\n\t}\n\t\n\t/**\n\t * Get the remote address from this session\n\t * @return\n\t * \t\tThe remote address\n\t */\n\tpublic InetSocketAddress getRemoteAddress() {\n\t\treturn (InetSocketAddress) socket.getRemoteSocketAddress();\n\t}\n}"
] | import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.SocketAddress;
import java.util.BitSet;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.nikkii.embedhttp.handler.HttpRequestHandler;
import org.nikkii.embedhttp.impl.HttpCapability;
import org.nikkii.embedhttp.impl.HttpRequest;
import org.nikkii.embedhttp.impl.HttpResponse;
import org.nikkii.embedhttp.impl.HttpSession;
import org.nikkii.embedhttp.impl.HttpStatus; | package org.nikkii.embedhttp;
/**
* The main HttpServer class
*
* @author Nikki
*
*/
public class HttpServer implements Runnable {
/**
* The request service
*/
private ExecutorService service = Executors.newCachedThreadPool();
/**
* The server socket
*/
private ServerSocket socket;
/**
* A list of HttpRequestHandlers for the server
*/
private List<HttpRequestHandler> handlers = new LinkedList<HttpRequestHandler>();
@SuppressWarnings("serial")
private BitSet capabilities = new BitSet() {
{
set(HttpCapability.HTTP_1_1.ordinal(), true);
set(HttpCapability.STANDARD_POST.ordinal(), true);
}
};
private boolean running;
/**
* Construct a new HttpServer
*/
public HttpServer() {
}
/**
* Construct and bind the HttpServer
*
* @param port
* The port to bind to
* @throws IOException
*/
public HttpServer(int port) throws IOException {
bind(port);
}
/**
* Bind the server to the specified port
*
* @param port
* The port to bind to
* @throws IOException
*/
public void bind(int port) throws IOException {
bind(new InetSocketAddress(port));
}
/**
* Bind the server to the specified SocketAddress
*
* @param addr
* The address to bind to
* @throws IOException
* If an error occurs while binding, usually port already in
* use.
*/
public void bind(SocketAddress addr) throws IOException {
socket = new ServerSocket();
socket.bind(addr);
}
/**
* Start the server in a new thread
*/
public void start() {
if (socket == null) {
throw new RuntimeException("Cannot bind a server that has not been initialized!");
}
running = true;
Thread t = new Thread(this);
t.setName("HttpServer");
t.start();
}
/**
* Stop the server
*/
public void stop() {
running = false;
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Run and process requests.
*/
@Override
public void run() {
while (running) {
try {
// Read the request
service.execute(new HttpSession(this, socket.accept()));
} catch (IOException e) {
// Ignore mostly.
}
}
}
/**
* Set a capability
*
* @param capability
* The capability to set
* @param value
* The value to set
*/
public void setCapability(HttpCapability capability, boolean value) {
capabilities.set(capability.ordinal(), value);
}
/**
* Add a request handler
*
* @param handler
* The request handler to add
*/
public void addRequestHandler(HttpRequestHandler handler) {
handlers.add(handler);
}
/**
* Remove a request handler
*
* @param handler
* The request handler to remove
*/
public void removeRequestHandler(HttpRequestHandler handler) {
handlers.remove(handler);
}
/**
* Dispatch a request to all handlers
*
* @param httpRequest
* The request to dispatch
* @throws IOException
* If an error occurs while sending the response from the
* handler
*/ | public void dispatchRequest(HttpRequest httpRequest) throws IOException { | 2 |
gizwits/GizOpenSource_AppKit_Android | src/com/gizwits/opensource/appkit/UserModule/GosUserLoginActivity.java | [
"public class GosApplication extends Application {\n\n\tpublic static int flag = 0;\n\n\tpublic void onCreate() {\n\t\tsuper.onCreate();\n\n\t}\n}",
"public class GosBaseActivity extends FragmentActivity {\n\n\t/** 设备热点默认密码 */\n\tpublic static String SoftAP_PSW = \"123456789\";\n\n\t/** 设备热点默认前缀 */\n\tpublic static String SoftAP_Start = \"XPG-GAgent\";\n\n\t/** 存储器默认名称 */\n\tpublic static final String SPF_Name = \"set\";\n\n\t/** Toast time */\n\tpublic int toastTime = 2000;\n\n\t/** 存储器 */\n\tpublic SharedPreferences spf;\n\n\t/** 等待框 */\n\tpublic ProgressDialog progressDialog;\n\n\t/** 标题栏 */\n\tpublic ActionBar actionBar;\n\n\t/** 实现WXEntryActivity与GosUserLoginActivity共用 */\n\tpublic static Handler baseHandler;\n\n\tpublic static boolean isclean = false;\n\n\tpublic void setBaseHandler(Handler basehandler) {\n\t\tif (null != basehandler) {\n\t\t\tbaseHandler = basehandler;\n\t\t}\n\t}\n\n\t@Override\n\tprotected void onCreate(Bundle savedInstanceState) {\n\t\tsuper.onCreate(savedInstanceState);\n\n\t\t/**\n\t\t * 设置为竖屏\n\t\t */\n\t\tif (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {\n\t\t\tsetRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);\n\t\t}\n\n\t\tspf = getSharedPreferences(SPF_Name, Context.MODE_PRIVATE);\n\t\tMessageCenter.getInstance(this);\n\t\t// 初始化\n\t\tsetProgressDialog();\n\t}\n\t\n\t\n\t\n\n\t/**\n\t * 添加ProductKeys\n\t * \n\t * @param productkeys\n\t * @return\n\t */\n\tpublic List<String> addProductKey(String[] productkeys) {\n\t\tList<String> productkeysList = new ArrayList<String>();\n\t\tfor (String productkey : productkeys) {\n\t\t\tproductkeysList.add(productkey);\n\t\t}\n\n\t\treturn productkeysList;\n\t}\n\n\t/**\n\t * 设置ActionBar(工具方法*开发用*)\n\t * \n\t * @param HBE\n\t * @param DSHE\n\t * @param Title\n\t */\n\tpublic void setActionBar(Boolean HBE, Boolean DSHE, int Title) {\n\n\t\tSpannableString ssTitle = new SpannableString(this.getString(Title));\n\t\tssTitle.setSpan(new ForegroundColorSpan(GosDeploy.setNavigationBarTextColor()), 0, ssTitle.length(),\n\t\t\t\tSpannable.SPAN_INCLUSIVE_EXCLUSIVE);\n\t\tactionBar = getActionBar();// 初始化ActionBar\n\t\tactionBar.setBackgroundDrawable(GosDeploy.setNavigationBarColor());\n\t\tactionBar.setHomeButtonEnabled(HBE);\n\t\tactionBar.setIcon(R.drawable.back_bt_);\n\t\tactionBar.setTitle(ssTitle);\n\t\tactionBar.setDisplayShowHomeEnabled(DSHE);\n\t}\n\n\t/**\n\t * 设置ActionBar(工具方法*GosAirlinkChooseDeviceWorkWiFiActivity.java中使用*)\n\t * \n\t * @param HBE\n\t * @param DSHE\n\t * @param Title\n\t */\n\tpublic void setActionBar(Boolean HBE, Boolean DSHE, CharSequence Title) {\n\n\t\tSpannableString ssTitle = new SpannableString(Title);\n\t\tssTitle.setSpan(new ForegroundColorSpan(GosDeploy.setNavigationBarTextColor()), 0, ssTitle.length(),\n\t\t\t\tSpannable.SPAN_INCLUSIVE_EXCLUSIVE);\n\t\tactionBar = getActionBar();// 初始化ActionBar\n\t\tactionBar.setBackgroundDrawable(GosDeploy.setNavigationBarColor());\n\t\tactionBar.setHomeButtonEnabled(HBE);\n\t\tactionBar.setIcon(R.drawable.back_bt_);\n\t\tactionBar.setTitle(ssTitle);\n\t\tactionBar.setDisplayShowHomeEnabled(DSHE);\n\t}\n\n\t/**\n\t * 设置ProgressDialog\n\t */\n\tpublic void setProgressDialog() {\n\t\tprogressDialog = new ProgressDialog(this);\n\t\tString loadingText = getString(R.string.loadingtext);\n\t\tprogressDialog.setMessage(loadingText);\n\t\tprogressDialog.setCanceledOnTouchOutside(false);\n\t}\n\n\t/**\n\t * 设置ProgressDialog\n\t * \n\t * @param Message\n\t * @param Cancelable\n\t * @param CanceledOnTouchOutside\n\t */\n\tpublic void setProgressDialog(String Message, boolean Cancelable, boolean CanceledOnTouchOutside) {\n\t\tprogressDialog = new ProgressDialog(this);\n\t\tprogressDialog.setMessage(Message);\n\t\tprogressDialog.setCancelable(Cancelable);\n\t\tprogressDialog.setCanceledOnTouchOutside(CanceledOnTouchOutside);\n\t}\n\n\t/**\n\t * 检查网络连通性(工具方法)\n\t * \n\t * @param context\n\t * @return\n\t */\n\tpublic boolean checkNetwork(Context context) {\n\t\tConnectivityManager conn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);\n\t\tNetworkInfo net = conn.getActiveNetworkInfo();\n\t\tif (net != null && net.isConnected()) {\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * 验证手机格式.(工具方法)\n\t */\n\t// public boolean isMobileNO(String mobiles) {\n\t// /*\n\t// * 移动:134、135、136、137、138、139、150、151、157(TD)、158、159、187、188\n\t// * 联通:130、131、132、152、155、156、185、186 电信:133、153、180、189、(1349卫通)\n\t// * 总结起来就是第一位必定为1,第二位必定为3或5或8,其他位置的可以为0-9\n\t// */\n\t// String telRegex = \"[1][3578]\\\\d{9}\";//\n\t// \"[1]\"代表第1位为数字1,\"[358]\"代表第二位可以为3、5、8中的一个,\"\\\\d{9}\"代表后面是可以是0~9的数字,有9位。\n\t// if (TextUtils.isEmpty(mobiles))\n\t// return false;\n\t// else\n\t// return !mobiles.matches(telRegex);\n\t// }\n\n\tpublic String toastError(GizWifiErrorCode errorCode) {\n\t\tString errorString = (String) getText(R.string.UNKNOWN_ERROR);\n\t\tswitch (errorCode) {\n\t\tcase GIZ_SDK_PARAM_FORM_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_PARAM_FORM_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_CLIENT_NOT_AUTHEN:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_CLIENT_NOT_AUTHEN);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_CLIENT_VERSION_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_CLIENT_VERSION_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_UDP_PORT_BIND_FAILED:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_UDP_PORT_BIND_FAILED);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_DAEMON_EXCEPTION:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_DAEMON_EXCEPTION);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_PARAM_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_PARAM_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_APPID_LENGTH_ERROR:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_APPID_LENGTH_ERROR);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_LOG_PATH_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_LOG_PATH_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_LOG_LEVEL_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_LOG_LEVEL_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_DEVICE_CONFIG_SEND_FAILED:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_DEVICE_CONFIG_SEND_FAILED);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_DEVICE_CONFIG_IS_RUNNING:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_DEVICE_CONFIG_IS_RUNNING);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_DEVICE_CONFIG_TIMEOUT:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_DEVICE_CONFIG_TIMEOUT);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_DEVICE_DID_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_DEVICE_DID_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_DEVICE_MAC_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_DEVICE_MAC_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_SUBDEVICE_DID_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_SUBDEVICE_DID_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_DEVICE_PASSCODE_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_DEVICE_PASSCODE_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_DEVICE_NOT_SUBSCRIBED:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_DEVICE_NOT_SUBSCRIBED);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_DEVICE_NO_RESPONSE:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_DEVICE_NO_RESPONSE);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_DEVICE_NOT_READY:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_DEVICE_NOT_READY);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_DEVICE_NOT_BINDED:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_DEVICE_NOT_BINDED);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_DEVICE_CONTROL_WITH_INVALID_COMMAND:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_DEVICE_CONTROL_WITH_INVALID_COMMAND);\n\t\t\tbreak;\n\t\t// case GIZ_SDK_DEVICE_CONTROL_FAILED:\n\t\t// errorString= (String)\n\t\t// getText(R.string.GIZ_SDK_DEVICE_CONTROL_FAILED);\n\t\t// break;\n\t\tcase GIZ_SDK_DEVICE_GET_STATUS_FAILED:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_DEVICE_GET_STATUS_FAILED);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_DEVICE_CONTROL_VALUE_TYPE_ERROR:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_DEVICE_CONTROL_VALUE_TYPE_ERROR);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_DEVICE_CONTROL_VALUE_OUT_OF_RANGE:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_DEVICE_CONTROL_VALUE_OUT_OF_RANGE);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_DEVICE_CONTROL_NOT_WRITABLE_COMMAND:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_DEVICE_CONTROL_NOT_WRITABLE_COMMAND);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_BIND_DEVICE_FAILED:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_BIND_DEVICE_FAILED);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_UNBIND_DEVICE_FAILED:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_UNBIND_DEVICE_FAILED);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_DNS_FAILED:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_DNS_FAILED);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_M2M_CONNECTION_SUCCESS:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_M2M_CONNECTION_SUCCESS);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_SET_SOCKET_NON_BLOCK_FAILED:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_SET_SOCKET_NON_BLOCK_FAILED);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_CONNECTION_TIMEOUT:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_CONNECTION_TIMEOUT);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_CONNECTION_REFUSED:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_CONNECTION_REFUSED);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_CONNECTION_ERROR:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_CONNECTION_ERROR);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_CONNECTION_CLOSED:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_CONNECTION_CLOSED);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_SSL_HANDSHAKE_FAILED:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_SSL_HANDSHAKE_FAILED);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_DEVICE_LOGIN_VERIFY_FAILED:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_DEVICE_LOGIN_VERIFY_FAILED);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_INTERNET_NOT_REACHABLE:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_INTERNET_NOT_REACHABLE);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_HTTP_ANSWER_FORMAT_ERROR:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_HTTP_ANSWER_FORMAT_ERROR);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_HTTP_ANSWER_PARAM_ERROR:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_HTTP_ANSWER_PARAM_ERROR);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_HTTP_SERVER_NO_ANSWER:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_HTTP_SERVER_NO_ANSWER);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_HTTP_REQUEST_FAILED:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_HTTP_REQUEST_FAILED);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_OTHERWISE:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_OTHERWISE);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_MEMORY_MALLOC_FAILED:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_MEMORY_MALLOC_FAILED);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_THREAD_CREATE_FAILED:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_THREAD_CREATE_FAILED);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_USER_ID_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_USER_ID_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_TOKEN_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_TOKEN_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_GROUP_ID_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_GROUP_ID_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_GROUPNAME_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_GROUPNAME_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_GROUP_PRODUCTKEY_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_GROUP_PRODUCTKEY_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_GROUP_FAILED_DELETE_DEVICE:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_GROUP_FAILED_DELETE_DEVICE);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_GROUP_FAILED_ADD_DEVICE:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_GROUP_FAILED_ADD_DEVICE);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_GROUP_GET_DEVICE_FAILED:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_GROUP_GET_DEVICE_FAILED);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_DATAPOINT_NOT_DOWNLOAD:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_DATAPOINT_NOT_DOWNLOAD);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_DATAPOINT_SERVICE_UNAVAILABLE:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_DATAPOINT_SERVICE_UNAVAILABLE);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_DATAPOINT_PARSE_FAILED:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_DATAPOINT_PARSE_FAILED);\n\t\t\tbreak;\n\t\t// case GIZ_SDK_NOT_INITIALIZED:\n\t\t// errorString= (String) getText(R.string.GIZ_SDK_SDK_NOT_INITIALIZED);\n\t\t// break;\n\t\tcase GIZ_SDK_APK_CONTEXT_IS_NULL:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_APK_CONTEXT_IS_NULL);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_APK_PERMISSION_NOT_SET:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_APK_PERMISSION_NOT_SET);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_CHMOD_DAEMON_REFUSED:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_CHMOD_DAEMON_REFUSED);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_EXEC_DAEMON_FAILED:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_EXEC_DAEMON_FAILED);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_EXEC_CATCH_EXCEPTION:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_EXEC_CATCH_EXCEPTION);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_APPID_IS_EMPTY:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_APPID_IS_EMPTY);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_UNSUPPORTED_API:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_UNSUPPORTED_API);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_REQUEST_TIMEOUT:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_REQUEST_TIMEOUT);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_DAEMON_VERSION_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_DAEMON_VERSION_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_PHONE_NOT_CONNECT_TO_SOFTAP_SSID:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_PHONE_NOT_CONNECT_TO_SOFTAP_SSID);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_DEVICE_CONFIG_SSID_NOT_MATCHED:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_DEVICE_CONFIG_SSID_NOT_MATCHED);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_NOT_IN_SOFTAPMODE:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_NOT_IN_SOFTAPMODE);\n\t\t\tbreak;\n\t\t// case GIZ_SDK_PHONE_WIFI_IS_UNAVAILABLE:\n\t\t// errorString= (String)\n\t\t// getText(R.string.GIZ_SDK_PHONE_WIFI_IS_UNAVAILABLE);\n\t\t// break;\n\t\tcase GIZ_SDK_RAW_DATA_TRANSMIT:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_RAW_DATA_TRANSMIT);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_PRODUCT_IS_DOWNLOADING:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_PRODUCT_IS_DOWNLOADING);\n\t\t\tbreak;\n\t\tcase GIZ_SDK_START_SUCCESS:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_START_SUCCESS);\n\t\t\tbreak;\n\t\tcase GIZ_SITE_PRODUCTKEY_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_SITE_PRODUCTKEY_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_SITE_DATAPOINTS_NOT_DEFINED:\n\t\t\terrorString = (String) getText(R.string.GIZ_SITE_DATAPOINTS_NOT_DEFINED);\n\t\t\tbreak;\n\t\tcase GIZ_SITE_DATAPOINTS_NOT_MALFORME:\n\t\t\terrorString = (String) getText(R.string.GIZ_SITE_DATAPOINTS_NOT_MALFORME);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_MAC_ALREADY_REGISTERED:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_MAC_ALREADY_REGISTERED);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_PRODUCT_KEY_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_PRODUCT_KEY_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_APPID_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_APPID_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_TOKEN_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_TOKEN_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_USER_NOT_EXIST:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_USER_NOT_EXIST);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_TOKEN_EXPIRED:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_TOKEN_EXPIRED);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_M2M_ID_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_M2M_ID_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_SERVER_ERROR:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_SERVER_ERROR);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_CODE_EXPIRED:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_CODE_EXPIRED);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_CODE_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_CODE_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_SANDBOX_SCALE_QUOTA_EXHAUSTED:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_SANDBOX_SCALE_QUOTA_EXHAUSTED);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_PRODUCTION_SCALE_QUOTA_EXHAUSTED:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_PRODUCTION_SCALE_QUOTA_EXHAUSTED);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_PRODUCT_HAS_NO_REQUEST_SCALE:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_PRODUCT_HAS_NO_REQUEST_SCALE);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_DEVICE_NOT_FOUND:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_DEVICE_NOT_FOUND);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_FORM_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_FORM_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_DID_PASSCODE_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_DID_PASSCODE_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_DEVICE_NOT_BOUND:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_DEVICE_NOT_BOUND);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_PHONE_UNAVALIABLE:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_PHONE_UNAVALIABLE);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_USERNAME_UNAVALIABLE:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_USERNAME_UNAVALIABLE);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_USERNAME_PASSWORD_ERROR:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_USERNAME_PASSWORD_ERROR);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_SEND_COMMAND_FAILED:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_SEND_COMMAND_FAILED);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_EMAIL_UNAVALIABLE:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_EMAIL_UNAVALIABLE);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_DEVICE_DISABLED:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_DEVICE_DISABLED);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_FAILED_NOTIFY_M2M:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_FAILED_NOTIFY_M2M);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_ATTR_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_ATTR_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_USER_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_USER_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_FIRMWARE_NOT_FOUND:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_FIRMWARE_NOT_FOUND);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_JD_PRODUCT_NOT_FOUND:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_JD_PRODUCT_NOT_FOUND);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_DATAPOINT_DATA_NOT_FOUND:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_DATAPOINT_DATA_NOT_FOUND);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_SCHEDULER_NOT_FOUND:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_SCHEDULER_NOT_FOUND);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_QQ_OAUTH_KEY_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_QQ_OAUTH_KEY_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_OTA_SERVICE_OK_BUT_IN_IDLE:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_OTA_SERVICE_OK_BUT_IN_IDLE);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_BT_FIRMWARE_UNVERIFIED:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_BT_FIRMWARE_UNVERIFIED);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_BT_FIRMWARE_NOTHING_TO_UPGRADE:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_SAVE_KAIROSDB_ERROR);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_SAVE_KAIROSDB_ERROR:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_SAVE_KAIROSDB_ERROR);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_EVENT_NOT_DEFINED:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_EVENT_NOT_DEFINED);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_SEND_SMS_FAILED:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_SEND_SMS_FAILED);\n\t\t\tbreak;\n\t\t// case GIZ_OPENAPI_APPLICATION_AUTH_INVALID:\n\t\t// errorString= (String)\n\t\t// getText(R.string.GIZ_OPENAPI_APPLICATION_AUTH_INVALID);\n\t\t// break;\n\t\tcase GIZ_OPENAPI_NOT_ALLOWED_CALL_API:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_NOT_ALLOWED_CALL_API);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_BAD_QRCODE_CONTENT:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_BAD_QRCODE_CONTENT);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_REQUEST_THROTTLED:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_REQUEST_THROTTLED);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_DEVICE_OFFLINE:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_DEVICE_OFFLINE);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_TIMESTAMP_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_TIMESTAMP_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_SIGNATURE_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_SIGNATURE_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_DEPRECATED_API:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_DEPRECATED_API);\n\t\t\tbreak;\n\t\tcase GIZ_OPENAPI_RESERVED:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_RESERVED);\n\t\t\tbreak;\n\t\tcase GIZ_PUSHAPI_BODY_JSON_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_PUSHAPI_BODY_JSON_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_PUSHAPI_DATA_NOT_EXIST:\n\t\t\terrorString = (String) getText(R.string.GIZ_PUSHAPI_DATA_NOT_EXIST);\n\t\t\tbreak;\n\t\tcase GIZ_PUSHAPI_NO_CLIENT_CONFIG:\n\t\t\terrorString = (String) getText(R.string.GIZ_PUSHAPI_NO_CLIENT_CONFIG);\n\t\t\tbreak;\n\t\tcase GIZ_PUSHAPI_NO_SERVER_DATA:\n\t\t\terrorString = (String) getText(R.string.GIZ_PUSHAPI_NO_SERVER_DATA);\n\t\t\tbreak;\n\t\tcase GIZ_PUSHAPI_GIZWITS_APPID_EXIST:\n\t\t\terrorString = (String) getText(R.string.GIZ_PUSHAPI_GIZWITS_APPID_EXIST);\n\t\t\tbreak;\n\t\tcase GIZ_PUSHAPI_PARAM_ERROR:\n\t\t\terrorString = (String) getText(R.string.GIZ_PUSHAPI_PARAM_ERROR);\n\t\t\tbreak;\n\t\tcase GIZ_PUSHAPI_AUTH_KEY_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_PUSHAPI_AUTH_KEY_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_PUSHAPI_APPID_OR_TOKEN_ERROR:\n\t\t\terrorString = (String) getText(R.string.GIZ_PUSHAPI_APPID_OR_TOKEN_ERROR);\n\t\t\tbreak;\n\t\tcase GIZ_PUSHAPI_TYPE_PARAM_ERROR:\n\t\t\terrorString = (String) getText(R.string.GIZ_PUSHAPI_TYPE_PARAM_ERROR);\n\t\t\tbreak;\n\t\tcase GIZ_PUSHAPI_ID_PARAM_ERROR:\n\t\t\terrorString = (String) getText(R.string.GIZ_PUSHAPI_ID_PARAM_ERROR);\n\t\t\tbreak;\n\t\tcase GIZ_PUSHAPI_APPKEY_SECRETKEY_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_PUSHAPI_APPKEY_SECRETKEY_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_PUSHAPI_CHANNELID_ERROR_INVALID:\n\t\t\terrorString = (String) getText(R.string.GIZ_PUSHAPI_CHANNELID_ERROR_INVALID);\n\t\t\tbreak;\n\t\tcase GIZ_PUSHAPI_PUSH_ERROR:\n\t\t\terrorString = (String) getText(R.string.GIZ_PUSHAPI_PUSH_ERROR);\n\t\t\tbreak;\n\n\t\tcase GIZ_OPENAPI_REGISTER_IS_BUSY:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_REGISTER_IS_BUSY);\n\t\t\tbreak;\n\n\t\tcase GIZ_OPENAPI_CANNOT_SHARE_TO_SELF:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_CANNOT_SHARE_TO_SELF);\n\t\t\tbreak;\n\n\t\tcase GIZ_OPENAPI_ONLY_OWNER_CAN_SHARE:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_ONLY_OWNER_CAN_SHARE);\n\t\t\tbreak;\n\n\t\tcase GIZ_OPENAPI_NOT_FOUND_GUEST:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_NOT_FOUND_GUEST);\n\t\t\tbreak;\n\n\t\tcase GIZ_OPENAPI_GUEST_ALREADY_BOUND:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_GUEST_ALREADY_BOUND);\n\t\t\tbreak;\n\n\t\tcase GIZ_OPENAPI_NOT_FOUND_SHARING_INFO:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_NOT_FOUND_SHARING_INFO);\n\t\t\tbreak;\n\n\t\tcase GIZ_OPENAPI_NOT_FOUND_THE_MESSAGE:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_NOT_FOUND_THE_MESSAGE);\n\t\t\tbreak;\n\n\t\tcase GIZ_OPENAPI_SHARING_IS_WAITING_FOR_ACCEPT:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_SHARING_IS_WAITING_FOR_ACCEPT);\n\t\t\tbreak;\n\n\t\tcase GIZ_OPENAPI_SHARING_IS_COMPLETED:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_SHARING_IS_COMPLETED);\n\t\t\tbreak;\n\n\t\tcase GIZ_OPENAPI_INVALID_SHARING_BECAUSE_UNBINDING:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_INVALID_SHARING_BECAUSE_UNBINDING);\n\t\t\tbreak;\n\n\t\tcase GIZ_OPENAPI_ONLY_OWNER_CAN_BIND:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_ONLY_OWNER_CAN_BIND);\n\t\t\tbreak;\n\n\t\tcase GIZ_OPENAPI_ONLY_OWNER_CAN_OPERATE:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_ONLY_OWNER_CAN_OPERATE);\n\t\t\tbreak;\n\n\t\tcase GIZ_OPENAPI_SHARING_ALREADY_CANCELLED:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_SHARING_ALREADY_CANCELLED);\n\t\t\tbreak;\n\n\t\tcase GIZ_OPENAPI_OWNER_CANNOT_UNBIND_SELF:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_OWNER_CANNOT_UNBIND_SELF);\n\t\t\tbreak;\n\n\t\tcase GIZ_OPENAPI_ONLY_GUEST_CAN_CHECK_QRCODE:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_ONLY_GUEST_CAN_CHECK_QRCODE);\n\t\t\tbreak;\n\n\t\tcase GIZ_OPENAPI_MESSAGE_ALREADY_DELETED:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_MESSAGE_ALREADY_DELETED);\n\t\t\tbreak;\n\n\t\tcase GIZ_OPENAPI_BINDING_NOTIFY_FAILED:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_BINDING_NOTIFY_FAILED);\n\t\t\tbreak;\n\n\t\tcase GIZ_OPENAPI_ONLY_SELF_CAN_MODIFY_ALIAS:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_ONLY_SELF_CAN_MODIFY_ALIAS);\n\t\t\tbreak;\n\n\t\tcase GIZ_OPENAPI_ONLY_RECEIVER_CAN_MARK_MESSAGE:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_ONLY_RECEIVER_CAN_MARK_MESSAGE);\n\t\t\tbreak;\n\n\t\tcase GIZ_OPENAPI_SHARING_IS_EXPIRED:\n\t\t\terrorString = (String) getText(R.string.GIZ_OPENAPI_SHARING_IS_EXPIRED);\n\t\t\tbreak;\n\n\t\tcase GIZ_SDK_NO_AVAILABLE_DEVICE:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_NO_AVAILABLE_DEVICE);\n\t\t\tbreak;\n\n\t\tcase GIZ_SDK_HTTP_SERVER_NOT_SUPPORT_API:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_HTTP_SERVER_NOT_SUPPORT_API);\n\t\t\tbreak;\n\n\t\tcase GIZ_SDK_ADD_SUBDEVICE_FAILED:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_ADD_SUBDEVICE_FAILED);\n\t\t\tbreak;\n\n\t\tcase GIZ_SDK_DELETE_SUBDEVICE_FAILED:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_DELETE_SUBDEVICE_FAILED);\n\t\t\tbreak;\n\n\t\tcase GIZ_SDK_GET_SUBDEVICES_FAILED:\n\t\t\terrorString = (String) getText(R.string.GIZ_SDK_GET_SUBDEVICES_FAILED);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\terrorString = (String) getText(R.string.UNKNOWN_ERROR);\n\t\t\tbreak;\n\t\t}\n\t\treturn errorString;\n\t}\n\n\t/**\n\t * NoID 提示\n\t * \n\t * @param context\n\t * 当前上下文\n\t * @param alertTextID\n\t * 提示内容\n\t */\n\tpublic static void noIDAlert(Context context, int alertTextID) {\n\t\tfinal Dialog dialog = new AlertDialog.Builder(context).setView(new EditText(context)).create();\n\t\tdialog.setCanceledOnTouchOutside(false);\n\t\tdialog.show();\n\n\t\tWindow window = dialog.getWindow();\n\t\twindow.setContentView(R.layout.alert_gos_no_id);\n\n\t\tLinearLayout llSure;\n\t\tTextView tvAlert;\n\t\tllSure = (LinearLayout) window.findViewById(R.id.llSure);\n\t\ttvAlert = (TextView) window.findViewById(R.id.tvAlert);\n\t\ttvAlert.setText(alertTextID);\n\n\t\tllSure.setOnClickListener(new OnClickListener() {\n\n\t\t\t@Override\n\t\t\tpublic void onClick(View v) {\n\t\t\t\tdialog.cancel();\n\t\t\t}\n\t\t});\n\t}\n\n\n}",
"public class GosDeploy {\n\n\tstatic Context context;\n\n\tpublic static HashMap<String, Object> infoMap;\n\n\t// 配置文件名称\n\tprivate static final String fileName = \"UIConfig.json\";\n\n\t// 输出json的路径\n\tpublic static String fileOutName = null;\n\n\tpublic GosDeploy(Context context) {\n\t\tsuper();\n\t\tGosDeploy.context = context;\n\n\t\tfileOutName = (context.getFilesDir().getAbsolutePath() + fileName);\n\t\tcopyJson();\n\t\treadJSON();\n\t}\n\n\t/*\n\t * ======================================================================\n\t * 以下Key值用来对应JSON文件中的个配置信息的名称,用于配置App主要参数\n\t * ======================================================================\n\t */\n\n\t/** The App_ID Key */\n\tprivate static final String App_ID_Key = \"app_id\";\n\n\t/** The App_Secret Key */\n\tprivate static final String App_Secret_Key = \"app_secret\";\n\n\t/** The Product_Key_List Key */\n\tprivate static final String Product_Key_List_Key = \"product_key\";\n\n\t/** The Module_Select_Switch Key */\n\tprivate static final String Module_Select_On_Key = \"wifi_type_select\";\n\n\t/** The UsingTabSet_Switch Key */\n\tprivate static final String UsingTabSet = \"UsingTabSet\";\n\n\t/** The Tencent_App_ID Key */\n\tprivate static final String Tencent_App_ID_Key = \"tencent_app_id\";\n\n\t/** The Wechat_App_ID Key */\n\tprivate static final String Wechat_App_ID_Key = \"wechat_app_id\";\n\n\t/** The Wechat_App_Secret Key\" */\n\tprivate static final String Wechat_App_Secret_Key = \"wechat_app_secret\";\n\n\t/** The Push_Type Key */\n\tprivate static final String Push_Type_Key = \"push_type\";\n\n\t// /** The Jpush_App_Key Key */\n\t// private static final String Jpush_App_Key = \"jpush_app_key\";\n\n\t/** The Bpush_App_Key Key */\n\tprivate static final String Bpush_App_Key = \"bpush_app_key\";\n\n\t/** The API_URL Key */\n\tprivate static final String API_URL_Key = \"openAPI_URL\";\n\n\t/** The Site_URL Key */\n\tprivate static final String SITE_URL_Key = \"site_URL\";\n\n\t/** The GDMS_URL Key */\n\tprivate static final String GDMS_URL_Key = \"push_URL\";\n\n\t/** The ButtonColor Key */\n\tprivate static final String ButtonColor_Key = \"buttonColor\";\n\n\t/** The ButtonTextColor Key */\n\tprivate static final String ButtonTextColor_Key = \"buttonTextColor\";\n\n\t/** The NavigationBarColor Key */\n\tprivate static final String NavigationBarColor_Key = \"navigationBarColor\";\n\n\t/** The NavigationBarTextColor Key */\n\tprivate static final String NavigationBarTextColor_Key = \"navigationBarTextColor\";\n\n\t/** The ConfigProgressViewColor Key */\n\tprivate static final String ConfigProgressViewColor_Key = \"configProgressViewColor\";\n\n\t/** The AddDeviceTitle Key */\n\tprivate static final String AddDeviceTitle_Key = \"addDeviceTitle\";\n\n\t/** The QQ Key */\n\tprivate static final String QQ = \"qq\";\n\n\t/** The Wechat Key */\n\tprivate static final String Wechat = \"wechat\";\n\n\t/** The AnonymousLogin Key */\n\tprivate static final String AnonymousLogin = \"anonymousLogin\";\n\n\t/** The StatusBarStyle Key */\n\t// private static final String StatusBarStyle_Key = \"statusBarStyle\";\n\n\t/*\n\t * ===================================================================\n\t * 以下是解析配置文件后,对各配置信息赋值的方法。\n\t * ===================================================================\n\t */\n\n\t/**\n\t * 设置SDK参数--AppID(必填)\n\t * \n\t * @return\n\t */\n\tpublic static String setAppID() {\n\n\t\treturn infoMap.get(App_ID_Key).toString();\n\t}\n\n\t/**\n\t * 设置SDK参数--AppSecret(必填且必须与上述AppKey匹配)\n\t * \n\t * @return\n\t */\n\tpublic static String setAppSecret() {\n\n\t\treturn infoMap.get(App_Secret_Key).toString();\n\t}\n\n\t/**\n\t * 用来判断是否需要打开QQ登录\n\t * \n\t * @return boolean\n\t */\n\tpublic static boolean setQQ() {\n\t\treturn (Boolean) infoMap.get(QQ);\n\t}\n\n\t/**\n\t * 用来判断是否需要打开Wechat登录\n\t * \n\t * @return boolean\n\t */\n\tpublic static boolean setWechat() {\n\t\treturn (Boolean) infoMap.get(Wechat);\n\t}\n\n\t/**\n\t * 用来判断是否需要打开匿名登录\n\t * \n\t * @return boolean\n\t */\n\tpublic static boolean setAnonymousLogin() {\n\t\treturn (Boolean) infoMap.get(AnonymousLogin);\n\t}\n\n\t/**\n\t * 设置ProductKey\n\t * \n\t * @return\n\t */\n\tpublic static List<String> setProductKeyList() {\n\t\tList<String> productKeyList = new ArrayList<String>();\n\t\tJSONArray jsonArray = (JSONArray) infoMap.get(Product_Key_List_Key);\n\n\t\tfor (int i = 0; i < jsonArray.length(); i++) {\n\t\t\ttry {\n\t\t\t\tproductKeyList.add(jsonArray.getString(i));\n\t\t\t\tLog.i(\"Apptest\", jsonArray.getString(i));\n\t\t\t} catch (JSONException e) {\n\t\t\t\te.printStackTrace();\n\t\t\t}\n\t\t}\n\n\t\treturn productKeyList;\n\t}\n\n\t/**\n\t * 设置模组类型开关\n\t * \n\t * @return\n\t */\n\tpublic static int setModuleSelectOn() {\n\t\tint modeOnOff = View.INVISIBLE;\n\n\t\tString moduleSelectOn = infoMap.get(Module_Select_On_Key).toString();\n\t\tif (Boolean.parseBoolean(moduleSelectOn)) {\n\t\t\tmodeOnOff = View.VISIBLE;\n\t\t}\n\n\t\treturn modeOnOff;\n\t}\n\n\t/**\n\t * 设置模组类型开关\n\t * \n\t * @return\n\t */\n\tpublic static int setUsingTabSetOn() {\n\t\tint modeOnOff = View.GONE;\n\n\t\tString moduleSelectOn = infoMap.get(UsingTabSet).toString();\n\t\tif (Boolean.parseBoolean(moduleSelectOn)) {\n\t\t\tmodeOnOff = View.VISIBLE;\n\t\t}\n\n\t\treturn modeOnOff;\n\t}\n\n\t/**\n\t * 设置TencentID\n\t * \n\t * @return\n\t */\n\tpublic static String setTencentAppID() {\n\n\t\treturn infoMap.get(Tencent_App_ID_Key).toString();\n\t}\n\n\t/**\n\t * 设置WechatAppID\n\t * \n\t * @return\n\t */\n\tpublic static String setWechatAppID() {\n\n\t\treturn infoMap.get(Wechat_App_ID_Key).toString();\n\t}\n\n\t/**\n\t * 设置WeChatAppSecret\n\t * \n\t * @return\n\t */\n\tpublic static String setWechatAppSecret() {\n\n\t\treturn infoMap.get(Wechat_App_Secret_Key).toString();\n\t}\n\n\t/**\n\t * 设置推送类型开关(0:不开启,1:极光推送,2:百度推送。默认为0)\n\t * \n\t * @return\n\t */\n\tpublic static int setPushType() {\n\t\tint pushType = 0;\n\n\t\tint PushType_FromMap = Integer.parseInt(infoMap.get(Push_Type_Key).toString());\n\t\tif (PushType_FromMap == 1) {\n\n\t\t\tToast.makeText(context, context.getResources().getString(R.string.push_type_string), 1).show();\n\t\t\tpushType = PushType_FromMap;\n\t\t} else if (PushType_FromMap == 2) {\n\t\t\tToast.makeText(context, context.getResources().getString(R.string.push_type_string), 1).show();\n\t\t\tpushType = PushType_FromMap;\n\t\t}\n\n\t\treturn pushType;\n\t}\n\n\t/**\n\t * 设置BaiDuPushApp\n\t * \n\t * @return\n\t */\n\tpublic static String setBaiDuPushAppKey() {\n\n\t\treturn infoMap.get(Bpush_App_Key).toString();\n\t}\n\n\t/**\n\t * 设置openAPI_URL\n\t * \n\t * @return\n\t */\n\tpublic static String[] setApiURL() {\n\t\tString[] apiURL = { \"\", \"\" };\n\n\t\tString apiURL_FromMap = infoMap.get(API_URL_Key).toString();\n\n\t\tif (!TextUtils.isEmpty(apiURL_FromMap)) {\n\t\t\tString[] strings = apiURL_FromMap.split(\":\");\n\t\t\tif (strings.length == 2) {\n\t\t\t\tapiURL = strings;\n\t\t\t} else if (strings.length == 1) {\n\t\t\t\tapiURL[0] = strings[0];\n\t\t\t\tapiURL[1] = \"80\";\n\t\t\t}\n\t\t}\n\n\t\treturn apiURL;\n\t}\n\n\t/**\n\t * 设置SITE_URL\n\t * \n\t * @return\n\t */\n\n\tpublic static String[] setSiteURL() {\n\t\tString[] siteURL = { \"\", \"\" };\n\n\t\tString siteURL_FromMap = infoMap.get(SITE_URL_Key).toString();\n\n\t\tif (!TextUtils.isEmpty(siteURL_FromMap)) {\n\t\t\tString[] strings = siteURL_FromMap.split(\":\");\n\t\t\tif (strings.length == 2) {\n\t\t\t\tsiteURL = strings;\n\t\t\t} else if (strings.length == 1) {\n\t\t\t\tsiteURL[0] = strings[0];\n\t\t\t\tsiteURL[1] = \"80\";\n\t\t\t}\n\t\t}\n\n\t\treturn siteURL;\n\t}\n\n\t/**\n\t * 设置GDMS_URL\n\t * \n\t * @return\n\t */\n\tpublic static String[] setGDMSURL() {\n\t\tString[] gdmsURL = { \"\", \"\" };\n\n\t\tString gdmsURL_FromMap = infoMap.get(GDMS_URL_Key).toString();\n\n\t\tif (!TextUtils.isEmpty(gdmsURL_FromMap)) {\n\t\t\tString[] strings = gdmsURL_FromMap.split(\":\");\n\t\t\tif (strings.length == 2) {\n\t\t\t\tgdmsURL = strings;\n\t\t\t} else if (strings.length == 1) {\n\t\t\t\tgdmsURL[0] = strings[0];\n\t\t\t\tgdmsURL[1] = \"80\";\n\t\t\t}\n\t\t}\n\n\t\treturn gdmsURL;\n\t}\n\n\t/**\n\t * 设置cloudService\n\t * \n\t * @return\n\t */\n\tpublic static ConcurrentHashMap<String, String> setCloudService() {\n\t\tString[] apiURl, siteURL, pushUrl;\n\t\tapiURl = setApiURL();\n\t\tsiteURL = setSiteURL();\n\t\tpushUrl = setGDMSURL();\n\t\tConcurrentHashMap<String, String> cloudServiceMap = new ConcurrentHashMap<String, String>();\n\n\t\tif (!TextUtils.isEmpty(apiURl[0])) {\n\t\t\tcloudServiceMap.put(\"openAPIDomain\", apiURl[0]);\n\t\t\tcloudServiceMap.put(\"openAPIPort\", apiURl[1]);\n\t\t}\n\n\t\tif (!TextUtils.isEmpty(siteURL[0])) {\n\t\t\tcloudServiceMap.put(\"siteDomain\", siteURL[0]);\n\t\t\tcloudServiceMap.put(\"sitePort\", siteURL[1]);\n\t\t}\n\n\t\tif (!TextUtils.isEmpty(pushUrl[0])) {\n\t\t\tcloudServiceMap.put(\"pushDomain\", pushUrl[0]);\n\t\t\tcloudServiceMap.put(\"pushPort\", pushUrl[1]);\n\t\t}\n\n\t\treturn cloudServiceMap;\n\t}\n\n\t/**\n\t * 设置Button背景颜色\n\t * \n\t * @return\n\t */\n\tpublic static Drawable setButtonBackgroundColor() {\n\t\tGradientDrawable drawable = new GradientDrawable();\n\t\tdrawable.setShape(GradientDrawable.RECTANGLE);\n\t\tdrawable.setCornerRadius(100);\n\n\t\tString ButtonColor_FromMap = infoMap.get(ButtonColor_Key).toString();\n\t\tif (!TextUtils.isEmpty(ButtonColor_FromMap)) {\n\t\t\tdrawable.setColor(Color.parseColor(\"#\" + ButtonColor_FromMap));\n\t\t} else {\n\t\t\tdrawable.setColor(context.getResources().getColor(R.color.yellow));\n\t\t}\n\n\t\treturn drawable;\n\t}\n\n\t/**\n\t * 设置Button文字颜色\n\t * \n\t * @return\n\t */\n\tpublic static int setButtonTextColor() {\n\t\tint buttonTextcolor = context.getResources().getColor(R.color.black);\n\t\tString ButtonTextColor_FromMap = infoMap.get(ButtonTextColor_Key).toString();\n\t\tif (!TextUtils.isEmpty(ButtonTextColor_FromMap)) {\n\t\t\tbuttonTextcolor = Color.parseColor(\"#\" + ButtonTextColor_FromMap);\n\t\t}\n\n\t\treturn buttonTextcolor;\n\t}\n\n\t/**\n\t * 设置导航栏背景颜色\n\t * \n\t * @return\n\t */\n\tpublic static Drawable setNavigationBarColor() {\n\t\tGradientDrawable drawable = new GradientDrawable();\n\t\tdrawable.setShape(GradientDrawable.RECTANGLE);\n\n\t\tint navigationBarColor = context.getResources().getColor(R.color.yellow);\n\n\t\tString NavigationBarColor_FromMap = infoMap.get(NavigationBarColor_Key).toString();\n\t\tif (!TextUtils.isEmpty(NavigationBarColor_FromMap)) {\n\t\t\tnavigationBarColor = Color.parseColor(\"#\" + NavigationBarColor_FromMap);\n\t\t}\n\t\tdrawable.setColor(navigationBarColor);\n\n\t\treturn drawable;\n\t}\n\n\t/**\n\t * 设置导航栏文字颜色\n\t * \n\t * @return\n\t */\n\tpublic static int setNavigationBarTextColor() {\n\t\tint navigationBarTextColor = context.getResources().getColor(R.color.black);\n\t\tString NavigationBarTextColor_FromMap = infoMap.get(NavigationBarTextColor_Key).toString();\n\t\tif (!TextUtils.isEmpty(NavigationBarTextColor_FromMap)) {\n\t\t\tnavigationBarTextColor = Color.parseColor(\"#\" + NavigationBarTextColor_FromMap);\n\t\t}\n\t\treturn navigationBarTextColor;\n\t}\n\n\t/**\n\t * 设置ConfigProgressView颜色\n\t * \n\t * @return\n\t */\n\tpublic static int setConfigProgressViewColor() {\n\t\tint configProgressViewColor = context.getResources().getColor(R.color.black);\n\n\t\tString ConfigProgressViewColor_FromMap = infoMap.get(ConfigProgressViewColor_Key).toString();\n\t\tif (!TextUtils.isEmpty(ConfigProgressViewColor_FromMap)) {\n\t\t\tconfigProgressViewColor = Color.parseColor(\"#\" + ConfigProgressViewColor_FromMap);\n\t\t}\n\n\t\treturn configProgressViewColor;\n\t}\n\n\t/**\n\t * 设置添加设备标题\n\t * \n\t * @return\n\t */\n\tpublic static String setAddDeviceTitle() {\n\n\t\tString addDeviceTitle = context.getResources().getString(R.string.addDeviceTitle);\n\t\tString AddDeviceTitle_FromMap = infoMap.get(AddDeviceTitle_Key).toString();\n\t\tif (!TextUtils.isEmpty(AddDeviceTitle_FromMap)) {\n\t\t\taddDeviceTitle = AddDeviceTitle_FromMap;\n\t\t}\n\n\t\treturn addDeviceTitle;\n\n\t}\n\n\t/**\n\t * 读取本地的JSON文件\n\t */\n\tprivate void readJSON() {\n\t\ttry {\n\t\t\tFileInputStream input = new FileInputStream(fileOutName);\n\t\t\tInputStreamReader inputStreamReader = new InputStreamReader(input, \"UTF-8\");\n\t\t\tBufferedReader bufferedReader = new BufferedReader(inputStreamReader);\n\t\t\tString line;\n\t\t\tStringBuilder stringBuilder = new StringBuilder();\n\t\t\twhile ((line = bufferedReader.readLine()) != null) {\n\t\t\t\tstringBuilder.append(line);\n\t\t\t}\n\t\t\tbufferedReader.close();\n\t\t\tinputStreamReader.close();\n\t\t\t// 加载JSON数据到Map\n\t\t\tsetMap(stringBuilder);\n\t\t} catch (UnsupportedEncodingException e) {\n\t\t\te.printStackTrace();\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\t@SuppressWarnings(\"rawtypes\")\n\tprivate void setMap(StringBuilder stringBuilder) {\n\t\tinfoMap = new HashMap<String, Object>();\n\t\ttry {\n\t\t\tJSONObject root = new JSONObject(stringBuilder.toString());\n\t\t\tIterator actions = root.keys();\n\t\t\twhile (actions.hasNext()) {\n\t\t\t\tString param = actions.next().toString();\n\n\t\t\t\tif (param.equals(\"product_key\")) {\n\t\t\t\t\tJSONArray myarray = (JSONArray) root.get(param);\n\t\t\t\t\tinfoMap.put(param, myarray);\n\t\t\t\t} else {\n\t\t\t\t\tObject value = root.get(param);\n\t\t\t\t\tinfoMap.put(param, value);\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t} catch (JSONException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\n\t}\n\n\t// 拷贝json文件\n\tprivate void copyJson() {\n\t\ttry {\n\t\t\tAssetsUtils.assetsDataToSD(fileOutName, fileName, context);\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\n\t}\n}",
"public class TipsDialog extends Dialog implements\n\t\tandroid.view.View.OnClickListener {\n\n\tprivate Button btnSure;\n\tprivate TextView tvTips;\n\n\tpublic TipsDialog(Context context) {\n\t\tsuper(context);\n\t\trequestWindowFeature(Window.FEATURE_NO_TITLE);\n\t\tgetWindow().setBackgroundDrawableResource(R.drawable.shape_button2);\n\t\tsetContentView(R.layout.dialog_tips);\n\t\tinitView();\n\t\tsetCancelable(false);\n\t\t\n\t}\n\n\tpublic TipsDialog(Context context, String txt) {\n\t\tthis(context);\n\n\t\ttvTips.setText(txt);\n\t}\n\n\tpublic TipsDialog(Context context, int res) {\n\t\tthis(context);\n\n\t\ttvTips.setText(res);\n\t}\n\t\n\t\n\t\n\n\tprivate void initView() {\n\t\tbtnSure = (Button) findViewById(R.id.btnSure);\n\t\ttvTips = (TextView) findViewById(R.id.tvTips);\n\n\t\tbtnSure.setOnClickListener(this);\n\t}\n\n\t@Override\n\tpublic void onClick(View v) {\n\t\tswitch (v.getId()) {\n\t\tcase R.id.btnSure:\n\t\t\tcancel();\n\t\t\tbreak;\n\t\t}\n\t}\n}",
"@SuppressLint(\"HandlerLeak\")\npublic class GosDeviceListActivity extends GosDeviceModuleBaseActivity implements OnClickListener, OnRefreshListener {\n\n\t/** The ll NoDevice */\n\tprivate ScrollView llNoDevice;\n\n\t/** The img NoDevice */\n\tprivate ImageView imgNoDevice;\n\n\t/** The btn NoDevice */\n\tprivate Button btnNoDevice;\n\n\t/** The ic BoundDevices */\n\tprivate View icBoundDevices;\n\n\t/** The ic FoundDevices */\n\tprivate View icFoundDevices;\n\n\t/** The ic OfflineDevices */\n\tprivate View icOfflineDevices;\n\n\t/** The tv BoundDevicesListTitle */\n\tprivate TextView tvBoundDevicesListTitle;\n\n\t/** The tv FoundDevicesListTitle */\n\tprivate TextView tvFoundDevicesListTitle;\n\n\t/** The tv OfflineDevicesListTitle */\n\tprivate TextView tvOfflineDevicesListTitle;\n\n\t/** The ll NoBoundDevices */\n\tprivate LinearLayout llNoBoundDevices;\n\n\t/** The ll NoFoundDevices */\n\tprivate LinearLayout llNoFoundDevices;\n\n\t/** The ll NoOfflineDevices */\n\tprivate LinearLayout llNoOfflineDevices;\n\n\t/** The slv BoundDevices */\n\tprivate SlideListView2 slvBoundDevices;\n\n\t/** The slv FoundDevices */\n\tprivate SlideListView2 slvFoundDevices;\n\n\t/** The slv OfflineDevices */\n\tprivate SlideListView2 slvOfflineDevices;\n\n\t/** The sv ListGroup */\n\tprivate ScrollView svListGroup;\n\n\t/** 适配器 */\n\tGosDeviceListAdapter myadapter;\n\n\t/** 设备列表分类 */\n\tList<GizWifiDevice> boundDevicesList, foundDevicesList, offlineDevicesList;\n\n\t/** 设备热点名称列表 */\n\tArrayList<String> softNameList;\n\n\t/** 与APP绑定的设备的ProductKey */\n\tprivate List<String> ProductKeyList;\n\n\tIntent intent;\n\n\tString softssid, uid, token;\n\n\tboolean isItemClicked = false;\n\n\tpublic static List<String> boundMessage;\n\n\tboolean isFrist = true;\n\n\t// boolean isLogout = false;\n\t//\n\t// public static boolean isAnonymousLoging = false;\n\n\t/**\n\t * 判断用户登录状态 0:未登录 1:实名用户登录 2:匿名用户登录 3:匿名用户登录中 4:匿名用户登录中断\n\t */\n\tpublic static int loginStatus;\n\n\tint threeSeconds = 3;\n\n\t/** 获取设备列表 */\n\tprotected static final int GETLIST = 0;\n\n\t/** 刷新设备列表 */\n\tprotected static final int UPDATALIST = 1;\n\n\t/** 订阅成功前往控制页面 */\n\tprotected static final int TOCONTROL = 2;\n\n\t/** 通知 */\n\tprotected static final int TOAST = 3;\n\n\t/** 设备绑定 */\n\tprotected static final int BOUND = 9;\n\n\t/** 设备解绑 */\n\tprotected static final int UNBOUND = 99;\n\n\t/** 新设备提醒 */\n\tprotected static final int SHOWDIALOG = 999;\n\n\tprivate static final int PULL_TO_REFRESH = 888;\n\n\tprivate VerticalSwipeRefreshLayout mSwipeLayout;\n\n\tprivate VerticalSwipeRefreshLayout mSwipeLayout1;\n\n\tHandler handler = new Handler() {\n\t\tprivate AlertDialog myDialog;\n\t\tprivate TextView dialog_name;\n\n\t\tpublic void handleMessage(android.os.Message msg) {\n\t\t\tsuper.handleMessage(msg);\n\t\t\tswitch (msg.what) {\n\t\t\tcase GETLIST:\n\n\t\t\t\tif (!uid.isEmpty() && !token.isEmpty()) {\n\t\t\t\t\tGizWifiSDK.sharedInstance().getBoundDevices(uid, token, ProductKeyList);\n\t\t\t\t}\n\n\t\t\t\tif (loginStatus == 0 && GosDeploy.setAnonymousLogin()) {\n\t\t\t\t\tloginStatus = 3;\n\t\t\t\t\tGizWifiSDK.sharedInstance().userLoginAnonymous();\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\n\t\t\tcase UPDATALIST:\n\t\t\t\tif (progressDialog.isShowing()) {\n\t\t\t\t\tprogressDialog.cancel();\n\t\t\t\t}\n\t\t\t\tUpdateUI();\n\t\t\t\tbreak;\n\n\t\t\tcase BOUND:\n\n\t\t\t\tbreak;\n\n\t\t\tcase UNBOUND:\n\t\t\t\tprogressDialog.show();\n\t\t\t\tGizWifiSDK.sharedInstance().unbindDevice(uid, token, msg.obj.toString());\n\t\t\t\tbreak;\n\n\t\t\tcase TOCONTROL:\n\t\t\t\tintent = new Intent(GosDeviceListActivity.this, GosDeviceControlActivity.class);\n\t\t\t\tBundle bundle = new Bundle();\n\t\t\t\tbundle.putParcelable(\"GizWifiDevice\", (GizWifiDevice) msg.obj);\n\t\t\t\tintent.putExtras(bundle);\n\t\t\t\t// startActivity(intent);\n\t\t\t\tstartActivityForResult(intent, 1);\n\t\t\t\tbreak;\n\n\t\t\tcase TOAST:\n\n\t\t\t\tToast.makeText(GosDeviceListActivity.this, msg.obj.toString(), 2000).show();\n\t\t\t\tbreak;\n\n\t\t\tcase PULL_TO_REFRESH:\n\t\t\t\thandler.sendEmptyMessage(GETLIST);\n\t\t\t\tmSwipeLayout.setRefreshing(false);\n\t\t\t\tmSwipeLayout1.setRefreshing(false);\n\n\t\t\t\tbreak;\n\n\t\t\tcase SHOWDIALOG:\n\n\t\t\t\tif (!softNameList.toString()\n\t\t\t\t\t\t.contains(GosMessageHandler.getSingleInstance().getNewDeviceList().toString())) {\n\t\t\t\t\tAlertDialog.Builder builder = new AlertDialog.Builder(GosDeviceListActivity.this);\n\t\t\t\t\tView view = View.inflate(GosDeviceListActivity.this, R.layout.alert_gos_new_device, null);\n\t\t\t\t\tButton diss = (Button) view.findViewById(R.id.diss);\n\t\t\t\t\tButton ok = (Button) view.findViewById(R.id.ok);\n\t\t\t\t\tdialog_name = (TextView) view.findViewById(R.id.dialog_name);\n\t\t\t\t\tString foundOneDevice, foundManyDevices;\n\t\t\t\t\tfoundOneDevice = (String) getText(R.string.not_text);\n\t\t\t\t\tfoundManyDevices = (String) getText(R.string.found_many_devices);\n\t\t\t\t\tif (GosMessageHandler.getSingleInstance().getNewDeviceList().size() < 1) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tif (GosMessageHandler.getSingleInstance().getNewDeviceList().size() == 1) {\n\t\t\t\t\t\tString ssid = GosMessageHandler.getSingleInstance().getNewDeviceList().get(0);\n\t\t\t\t\t\tif (!TextUtils.isEmpty(ssid)\n\t\t\t\t\t\t\t\t&& ssid.equalsIgnoreCase(NetUtils.getCurentWifiSSID(GosDeviceListActivity.this))) {\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (softNameList.toString().contains(ssid)) {\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tsoftNameList.add(ssid);\n\t\t\t\t\t\tdialog_name.setText(ssid + foundOneDevice);\n\t\t\t\t\t\tsoftssid = ssid;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfor (String s : GosMessageHandler.getSingleInstance().getNewDeviceList()) {\n\t\t\t\t\t\t\tif (!softNameList.toString().contains(s)) {\n\t\t\t\t\t\t\t\tsoftNameList.add(s);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdialog_name.setText(foundManyDevices);\n\t\t\t\t\t}\n\t\t\t\t\tmyDialog = builder.create();\n\t\t\t\t\tWindow window = myDialog.getWindow();\n\t\t\t\t\tmyDialog.setView(view);\n\t\t\t\t\tmyDialog.show();\n\t\t\t\t\twindow.setGravity(Gravity.BOTTOM);\n\t\t\t\t\tok.setOnClickListener(new OnClickListener() {\n\t\t\t\t\t\t@Override\n\t\t\t\t\t\tpublic void onClick(View v) {\n\t\t\t\t\t\t\tif (GosMessageHandler.getSingleInstance().getNewDeviceList().size() == 1) {\n\t\t\t\t\t\t\t\tIntent intent = new Intent(GosDeviceListActivity.this,\n\t\t\t\t\t\t\t\t\t\tGosCheckDeviceWorkWiFiActivity.class);\n\t\t\t\t\t\t\t\tintent.putExtra(\"softssid\", softssid);\n\t\t\t\t\t\t\t\tstartActivity(intent);\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tIntent intent = new Intent(GosDeviceListActivity.this,\n\t\t\t\t\t\t\t\t\t\tGosCheckDeviceWorkWiFiActivity.class);\n\t\t\t\t\t\t\t\tstartActivity(intent);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tmyDialog.cancel();\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t\tdiss.setOnClickListener(new OnClickListener() {\n\t\t\t\t\t\t@Override\n\t\t\t\t\t\tpublic void onClick(View v) {\n\t\t\t\t\t\t\tmyDialog.cancel();\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t};\n\t};\n\n\t@Override\n\tprotected void onCreate(Bundle savedInstanceState) {\n\t\tsuper.onCreate(savedInstanceState);\n\t\tsetContentView(R.layout.activity_gos_device_list);\n\t\t// 设置ActionBar\n\t\t// setActionBar(true, true, R.string.devicelist_title);\n\t\t// actionBar.setIcon(R.drawable.button_refresh);\n\n\t\thandler.sendEmptyMessage(GETLIST);\n\t\tGosMessageHandler.getSingleInstance().StartLooperWifi(this);\n\t\tsoftNameList = new ArrayList<String>();\n\t\tinitData();\n\t\tinitView();\n\t\tinitEvent();\n\n\t}\n\n\t/*\n\t * @Override public void onWindowFocusChanged(boolean hasFocus) {\n\t * super.onWindowFocusChanged(hasFocus); if (hasFocus && isFrist) {\n\t * progressDialog.show();\n\t * \n\t * isFrist = false; } }\n\t */\n\n\t@Override\n\tprotected void onResume() {\n\t\tsuper.onResume();\n\t\tGizDeviceSharing.setListener(new GizDeviceSharingListener() {\n\n\t\t\t@Override\n\t\t\tpublic void didCheckDeviceSharingInfoByQRCode(GizWifiErrorCode result, String userName, String productName,\n\t\t\t\t\tString deviceAlias, String expiredAt) {\n\t\t\t\t// TODO Auto-generated method stub\n\t\t\t\tsuper.didCheckDeviceSharingInfoByQRCode(result, userName, productName, deviceAlias, expiredAt);\n\n\t\t\t\tif (progressDialog != null && progressDialog.isShowing()) {\n\t\t\t\t\tprogressDialog.dismiss();\n\t\t\t\t}\n\t\t\t\tint errorcode = result.ordinal();\n\n\t\t\t\tif (8041 <= errorcode && errorcode <= 8050 || errorcode == 8308) {\n\t\t\t\t\tToast.makeText(GosDeviceListActivity.this, getResources().getString(R.string.sorry), 1).show();\n\t\t\t\t} else if (errorcode != 0) {\n\t\t\t\t\tToast.makeText(GosDeviceListActivity.this, getResources().getString(R.string.verysorry), 1).show();\n\t\t\t\t} else {\n\t\t\t\t\tIntent tent = new Intent(GosDeviceListActivity.this, gosZxingDeviceSharingActivity.class);\n\n\t\t\t\t\ttent.putExtra(\"userName\", userName);\n\t\t\t\t\ttent.putExtra(\"productName\", productName);\n\t\t\t\t\ttent.putExtra(\"deviceAlias\", deviceAlias);\n\t\t\t\t\ttent.putExtra(\"expiredAt\", expiredAt);\n\t\t\t\t\ttent.putExtra(\"code\", boundMessage.get(2));\n\n\t\t\t\t\tstartActivity(tent);\n\n\t\t\t\t}\n\t\t\t}\n\n\t\t});\n\t\tGosDeviceModuleBaseActivity.deviceslist = GizWifiSDK.sharedInstance().getDeviceList();\n\t\tUpdateUI();\n\t\t// TODO GosMessageHandler.getSingleInstance().SetHandler(handler);\n\t\tif (boundMessage.size() != 0) {\n\t\t\tprogressDialog.show();\n\t\t\tif (boundMessage.size() == 2) {\n\t\t\t\tGizWifiSDK.sharedInstance().bindDevice(uid, token, boundMessage.get(0), boundMessage.get(1), null);\n\t\t\t} else if (boundMessage.size() == 1) {\n\t\t\t\tGizWifiSDK.sharedInstance().bindDeviceByQRCode(uid, token, boundMessage.get(0));\n\t\t\t} else if (boundMessage.size() == 3) {\n\n\t\t\t\tGizDeviceSharing.checkDeviceSharingInfoByQRCode(spf.getString(\"Token\", \"\"), boundMessage.get(2));\n\t\t\t} else {\n\t\t\t\tLog.i(\"Apptest\", \"ListSize:\" + boundMessage.size());\n\t\t\t}\n\t\t}\n\n\t\t\n\n\t}\n\n\t@Override\n\tpublic void onPause() {\n\t\tsuper.onPause();\n\t\tboundMessage.clear();\n\t\t// TODO GosMessageHandler.getSingleInstance().SetHandler(null);\n\n\t}\n\n\tprivate void initView() {\n\t\tsvListGroup = (ScrollView) findViewById(R.id.svListGroup);\n\t\tllNoDevice = (ScrollView) findViewById(R.id.llNoDevice);\n\t\timgNoDevice = (ImageView) findViewById(R.id.imgNoDevice);\n\t\tbtnNoDevice = (Button) findViewById(R.id.btnNoDevice);\n\n\t\ticBoundDevices = findViewById(R.id.icBoundDevices);\n\t\ticFoundDevices = findViewById(R.id.icFoundDevices);\n\t\ticOfflineDevices = findViewById(R.id.icOfflineDevices);\n\n\t\tslvBoundDevices = (SlideListView2) icBoundDevices.findViewById(R.id.slideListView1);\n\t\tslvFoundDevices = (SlideListView2) icFoundDevices.findViewById(R.id.slideListView1);\n\t\tslvOfflineDevices = (SlideListView2) icOfflineDevices.findViewById(R.id.slideListView1);\n\n\t\tllNoBoundDevices = (LinearLayout) icBoundDevices.findViewById(R.id.llHaveNotDevice);\n\t\tllNoFoundDevices = (LinearLayout) icFoundDevices.findViewById(R.id.llHaveNotDevice);\n\t\tllNoOfflineDevices = (LinearLayout) icOfflineDevices.findViewById(R.id.llHaveNotDevice);\n\n\t\ttvBoundDevicesListTitle = (TextView) icBoundDevices.findViewById(R.id.tvListViewTitle);\n\t\ttvFoundDevicesListTitle = (TextView) icFoundDevices.findViewById(R.id.tvListViewTitle);\n\t\ttvOfflineDevicesListTitle = (TextView) icOfflineDevices.findViewById(R.id.tvListViewTitle);\n\n\t\tString boundDevicesListTitle = (String) getText(R.string.bound_divices);\n\t\ttvBoundDevicesListTitle.setText(boundDevicesListTitle);\n\t\tString foundDevicesListTitle = (String) getText(R.string.found_devices);\n\t\ttvFoundDevicesListTitle.setText(foundDevicesListTitle);\n\t\tString offlineDevicesListTitle = (String) getText(R.string.offline_devices);\n\t\ttvOfflineDevicesListTitle.setText(offlineDevicesListTitle);\n\n\t\t// 下拉刷新\n\n\t\tmSwipeLayout = (VerticalSwipeRefreshLayout) findViewById(R.id.id_swipe_ly);\n\n\t\tmSwipeLayout.setOnRefreshListener(this);\n\t\tmSwipeLayout.setColorScheme(android.R.color.holo_blue_bright, android.R.color.holo_green_light,\n\t\t\t\tandroid.R.color.holo_orange_light, android.R.color.holo_red_light);\n\n\t\tmSwipeLayout1 = (VerticalSwipeRefreshLayout) findViewById(R.id.id_swipe_ly1);\n\t\tmSwipeLayout1.setOnRefreshListener(this);\n\t\tmSwipeLayout1.setColorScheme(android.R.color.holo_blue_bright, android.R.color.holo_green_light,\n\t\t\t\tandroid.R.color.holo_orange_light, android.R.color.holo_red_light);\n\n\t}\n\n\tprivate void initEvent() {\n\n\t\timgNoDevice.setOnClickListener(this);\n\t\tbtnNoDevice.setOnClickListener(this);\n\n\t\tslvFoundDevices.setOnItemClickListener(new OnItemClickListener() {\n\t\t\t@Override\n\t\t\tpublic void onItemClick(AdapterView<?> parent, final View view, int position, long id) {\n\t\t\t\tprogressDialog.show();\n\t\t\t\tslvFoundDevices.setEnabled(false);\n\t\t\t\tslvFoundDevices.postDelayed(new Runnable() {\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void run() {\n\t\t\t\t\t\tslvFoundDevices.setEnabled(true);\n\t\t\t\t\t}\n\t\t\t\t}, 3000);\n\t\t\t\tGizWifiDevice device = foundDevicesList.get(position);\n\t\t\t\tdevice.setListener(getGizWifiDeviceListener());\n\n\t\t\t\tString productKey = device.getProductKey();\n\t\t\t\tif (productKey.equals(\"ac102d79bbb346389e1255eafca0cfd2\")) {\n\t\t\t\t\tdevice.setSubscribe(\"b83feefa750740f6862380043c0f78fb\", true);\n\t\t\t\t} else {\n\t\t\t\t\tdevice.setSubscribe(true);\n\t\t\t\t}\n\n\t\t\t}\n\t\t});\n\n\t\tslvBoundDevices.setOnItemClickListener(new OnItemClickListener() {\n\t\t\t@Override\n\t\t\tpublic void onItemClick(AdapterView<?> parent, final View view, int position, long id) {\n\t\t\t\tprogressDialog.show();\n\t\t\t\tslvBoundDevices.setEnabled(false);\n\t\t\t\tslvBoundDevices.postDelayed(new Runnable() {\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void run() {\n\t\t\t\t\t\tslvBoundDevices.setEnabled(true);\n\t\t\t\t\t}\n\t\t\t\t}, 3000);\n\t\t\t\tGizWifiDevice device = boundDevicesList.get(position);\n\t\t\t\tdevice.setListener(getGizWifiDeviceListener());\n\t\t\t\tString productKey = device.getProductKey();\n\t\t\t\tif (productKey.equals(\"ac102d79bbb346389e1255eafca0cfd2\")) {\n\t\t\t\t\tdevice.setSubscribe(\"b83feefa750740f6862380043c0f78fb\", true);\n\t\t\t\t} else {\n\t\t\t\t\tdevice.setSubscribe(true);\n\t\t\t\t}\n\n\t\t\t}\n\t\t});\n\n\t\tslvBoundDevices.initSlideMode(SlideListView2.MOD_RIGHT);\n\t\tslvOfflineDevices.initSlideMode(SlideListView2.MOD_RIGHT);\n\t}\n\n\tprivate void initData() {\n\t\tboundMessage = new ArrayList<String>();\n\t\tProductKeyList = GosDeploy.setProductKeyList();\n\t\tuid = spf.getString(\"Uid\", \"\");\n\t\ttoken = spf.getString(\"Token\", \"\");\n\n\t\tif (uid.isEmpty() && token.isEmpty()) {\n\t\t\tloginStatus = 0;\n\t\t}\n\t}\n\n\tprotected void didDiscovered(GizWifiErrorCode result, java.util.List<GizWifiDevice> deviceList) {\n\t\tGosDeviceModuleBaseActivity.deviceslist.clear();\n\t\tfor (GizWifiDevice gizWifiDevice : deviceList) {\n\t\t\tGosDeviceModuleBaseActivity.deviceslist.add(gizWifiDevice);\n\t\t}\n\t\thandler.sendEmptyMessage(UPDATALIST);\n\n\t}\n\n\tprotected void didUserLogin(GizWifiErrorCode result, java.lang.String uid, java.lang.String token) {\n\n\t\tif (GizWifiErrorCode.GIZ_SDK_SUCCESS == result) {\n\t\t\tloginStatus = 2;\n\t\t\tthis.uid = uid;\n\t\t\tthis.token = token;\n\t\t\tspf.edit().putString(\"Uid\", this.uid).commit();\n\t\t\tspf.edit().putString(\"Token\", this.token).commit();\n\t\t\thandler.sendEmptyMessage(GETLIST);\n\t\t\t// TODO 绑定推送\n\t\t\tGosPushManager.pushBindService(token);\n\t\t} else {\n\t\t\tloginStatus = 0;\n\t\t\tif (GosDeploy.setAnonymousLogin()) {\n\t\t\t\ttryUserLoginAnonymous();\n\t\t\t}\n\n\t\t}\n\t}\n\n\tprotected void didUnbindDevice(GizWifiErrorCode result, java.lang.String did) {\n\t\tprogressDialog.cancel();\n\t\tif (GizWifiErrorCode.GIZ_SDK_SUCCESS != result) {\n\t\t\t// String unBoundFailed = (String) getText(R.string.unbound_failed);\n\t\t\tToast.makeText(this, toastError(result), 2000).show();\n\t\t}\n\t}\n\n\t@Override\n\tprotected void didSetSubscribe(GizWifiErrorCode result, GizWifiDevice device, boolean isSubscribed) {\n\t\t// TODO 控制页面跳转\n\t\tprogressDialog.cancel();\n\t\tMessage msg = new Message();\n\t\tif (GizWifiErrorCode.GIZ_SDK_SUCCESS == result) {\n\t\t\tmsg.what = TOCONTROL;\n\t\t\tmsg.obj = device;\n\t\t} else {\n\t\t\tif (device.isBind()) {\n\t\t\t\tmsg.what = TOAST;\n\t\t\t\t// String setSubscribeFail = (String)\n\t\t\t\t// getText(R.string.setsubscribe_failed);\n\t\t\t\tmsg.obj = toastError(result);// setSubscribeFail + \"\\n\" + arg0;\n\t\t\t}\n\t\t}\n\t\thandler.sendMessage(msg);\n\t}\n\n\t/**\n\t * 推送绑定回调\n\t * \n\t * @param result\n\t */\n\t@Override\n\tprotected void didChannelIDBind(GizWifiErrorCode result) {\n\t\tLog.i(\"Apptest\", result.toString());\n\t\tif (GizWifiErrorCode.GIZ_SDK_SUCCESS != result) {\n\t\t\tToast.makeText(this, toastError(result), 2000).show();\n\t\t}\n\t}\n\n\t/**\n\t * 设备绑定回调(旧)\n\t * \n\t * @param error\n\t * @param errorMessage\n\t * @param did\n\t */\n\tprotected void didBindDevice(int error, String errorMessage, String did) {\n\t\tprogressDialog.cancel();\n\t\tif (error != 0) {\n\n\t\t\tString toast = getResources().getString(R.string.bound_failed) + \"\\n\" + errorMessage;\n\t\t\tToast.makeText(this, toast, 2000).show();\n\t\t\t// Toast.makeText(this, R.string.bound_failed + \"\\n\" + errorMessage,\n\t\t\t// 2000).show();\n\t\t} else {\n\n\t\t\tToast.makeText(this, R.string.bound_successful, 2000).show();\n\t\t}\n\n\t};\n\n\t/**\n\t * 设备绑定回调\n\t * \n\t * @param result\n\t * @param did\n\t */\n\tprotected void didBindDevice(GizWifiErrorCode result, java.lang.String did) {\n\t\tprogressDialog.cancel();\n\t\tif (result != GizWifiErrorCode.GIZ_SDK_SUCCESS) {\n\t\t\tToast.makeText(this, toastError(result), 2000).show();\n\t\t} else {\n\n\t\t\tToast.makeText(this, R.string.add_successful, 2000).show();\n\t\t}\n\t}\n\n\t@Override\n\tpublic boolean onCreateOptionsMenu(Menu menu) {\n\t\t// Inflate the menu; this adds items to the action bar if it is present.\n\n\t\tif (!TextUtils.isEmpty(spf.getString(\"UserName\", \"\")) && !TextUtils.isEmpty(spf.getString(\"PassWord\", \"\"))) {\n\t\t\tgetMenuInflater().inflate(R.menu.devicelist_logout, menu);\n\t\t} else {\n\t\t\tif (getIntent().getBooleanExtra(\"ThredLogin\", false)) {\n\t\t\t\tgetMenuInflater().inflate(R.menu.devicelist_logout, menu);\n\t\t\t} else {\n\t\t\t\tgetMenuInflater().inflate(R.menu.devicelist_login, menu);\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t@Override\n\tpublic boolean onOptionsItemSelected(MenuItem item) {\n\t\tsuper.onOptionsItemSelected(item);\n\t\tswitch (item.getItemId()) {\n\t\tcase android.R.id.home:\n\t\t\tif (checkNetwork(GosDeviceListActivity.this)) {\n\t\t\t\tprogressDialog.show();\n\t\t\t\thandler.sendEmptyMessage(GETLIST);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase R.id.action_QR_code:\n\t\t\tintent = new Intent(GosDeviceListActivity.this, CaptureActivity.class);\n\t\t\tstartActivity(intent);\n\t\t\tbreak;\n\t\tcase R.id.action_change_user:\n\t\t\tif (item.getTitle() == getText(R.string.login)) {\n\t\t\t\tlogoutToClean();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tfinal Dialog dialog = new AlertDialog.Builder(this).setView(new EditText(this)).create();\n\t\t\tdialog.show();\n\n\t\t\tWindow window = dialog.getWindow();\n\t\t\twindow.setContentView(R.layout.alert_gos_logout);\n\n\t\t\tLinearLayout llNo, llSure;\n\t\t\tllNo = (LinearLayout) window.findViewById(R.id.llNo);\n\t\t\tllSure = (LinearLayout) window.findViewById(R.id.llSure);\n\n\t\t\tllNo.setOnClickListener(new OnClickListener() {\n\n\t\t\t\t@Override\n\t\t\t\tpublic void onClick(View v) {\n\t\t\t\t\tdialog.cancel();\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tllSure.setOnClickListener(new OnClickListener() {\n\n\t\t\t\t@Override\n\t\t\t\tpublic void onClick(View v) {\n\t\t\t\t\tlogoutToClean();\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tbreak;\n\t\tcase R.id.action_addDevice:\n\t\t\tif (!checkNetwork(GosDeviceListActivity.this)) {\n\t\t\t\tToast.makeText(GosDeviceListActivity.this, R.string.network_error, 2000).show();\n\t\t\t} else {\n\t\t\t\tintent = new Intent(GosDeviceListActivity.this, GosAirlinkChooseDeviceWorkWiFiActivity.class);\n\t\t\t\t/*\n\t\t\t\t * intent = new Intent(GosDeviceListActivity.this,\n\t\t\t\t * GosChooseDeviceActivity.class);\n\t\t\t\t */\n\t\t\t\tstartActivity(intent);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase R.id.action_site:\n\t\t\tintent = new Intent(GosDeviceListActivity.this, GosSettiingsActivity.class);\n\t\t\tstartActivityForResult(intent, 600);\n\t\t\tbreak;\n\t\t}\n\t\treturn super.onOptionsItemSelected(item);\n\t}\n\n\tprivate void UpdateUI() {\n\t\tif (GosDeviceModuleBaseActivity.deviceslist.isEmpty()) {\n\t\t\tsvListGroup.setVisibility(View.GONE);\n\t\t\tllNoDevice.setVisibility(View.VISIBLE);\n\t\t\tmSwipeLayout1.setVisibility(View.VISIBLE);\n\t\t\treturn;\n\t\t} else {\n\t\t\tllNoDevice.setVisibility(View.GONE);\n\t\t\tmSwipeLayout1.setVisibility(View.GONE);\n\t\t\tsvListGroup.setVisibility(View.VISIBLE);\n\t\t}\n\n\t\tboundDevicesList = new ArrayList<GizWifiDevice>();\n\t\tfoundDevicesList = new ArrayList<GizWifiDevice>();\n\t\tofflineDevicesList = new ArrayList<GizWifiDevice>();\n\n\t\tfor (GizWifiDevice gizWifiDevice : GosDeviceModuleBaseActivity.deviceslist) {\n\t\t\tif (GizWifiDeviceNetStatus.GizDeviceOnline == gizWifiDevice.getNetStatus()\n\t\t\t\t\t|| GizWifiDeviceNetStatus.GizDeviceControlled == gizWifiDevice.getNetStatus()) {\n\t\t\t\tif (gizWifiDevice.isBind()) {\n\t\t\t\t\tboundDevicesList.add(gizWifiDevice);\n\t\t\t\t} else {\n\t\t\t\t\tfoundDevicesList.add(gizWifiDevice);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tofflineDevicesList.add(gizWifiDevice);\n\t\t\t}\n\t\t}\n\n\t\tif (boundDevicesList.isEmpty()) {\n\t\t\tslvBoundDevices.setVisibility(View.GONE);\n\t\t\tllNoBoundDevices.setVisibility(View.VISIBLE);\n\t\t} else {\n\t\t\tmyadapter = new GosDeviceListAdapter(this, boundDevicesList);\n\t\t\tmyadapter.setHandler(handler);\n\t\t\tslvBoundDevices.setAdapter(myadapter);\n\t\t\tllNoBoundDevices.setVisibility(View.GONE);\n\t\t\tslvBoundDevices.setVisibility(View.VISIBLE);\n\t\t}\n\n\t\tif (foundDevicesList.isEmpty()) {\n\t\t\tslvFoundDevices.setVisibility(View.GONE);\n\t\t\tllNoFoundDevices.setVisibility(View.VISIBLE);\n\t\t} else {\n\t\t\tmyadapter = new GosDeviceListAdapter(this, foundDevicesList);\n\t\t\tslvFoundDevices.setAdapter(myadapter);\n\t\t\tllNoFoundDevices.setVisibility(View.GONE);\n\t\t\tslvFoundDevices.setVisibility(View.VISIBLE);\n\t\t}\n\n\t\tif (offlineDevicesList.isEmpty()) {\n\t\t\tslvOfflineDevices.setVisibility(View.GONE);\n\t\t\tllNoOfflineDevices.setVisibility(View.VISIBLE);\n\t\t} else {\n\t\t\tmyadapter = new GosDeviceListAdapter(this, offlineDevicesList);\n\t\t\tmyadapter.setHandler(handler);\n\t\t\tslvOfflineDevices.setAdapter(myadapter);\n\t\t\tllNoOfflineDevices.setVisibility(View.GONE);\n\t\t\tslvOfflineDevices.setVisibility(View.VISIBLE);\n\t\t}\n\n\t}\n\n\t@Override\n\tpublic void onClick(View v) {\n\t\tswitch (v.getId()) {\n\t\tcase R.id.imgNoDevice:\n\t\tcase R.id.btnNoDevice:\n\t\t\tif (!checkNetwork(GosDeviceListActivity.this)) {\n\t\t\t\tToast.makeText(GosDeviceListActivity.this, R.string.network_error, 2000).show();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tintent = new Intent(GosDeviceListActivity.this, GosAirlinkChooseDeviceWorkWiFiActivity.class);\n\t\t\tstartActivity(intent);\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tprivate void tryUserLoginAnonymous() {\n\t\tthreeSeconds = 3;\n\t\tfinal Timer tsTimer = new Timer();\n\t\ttsTimer.schedule(new TimerTask() {\n\n\t\t\t@Override\n\t\t\tpublic void run() {\n\t\t\t\tthreeSeconds--;\n\t\t\t\tif (threeSeconds <= 0) {\n\t\t\t\t\ttsTimer.cancel();\n\t\t\t\t\thandler.sendEmptyMessage(GETLIST);\n\t\t\t\t} else {\n\t\t\t\t\tif (loginStatus == 4) {\n\t\t\t\t\t\ttsTimer.cancel();\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}, 1000, 1000);\n\t}\n\n\t/**\n\t * 菜单、返回键响应\n\t */\n\t@Override\n\tpublic boolean onKeyDown(int keyCode, KeyEvent event) {\n\t\tif (keyCode == KeyEvent.KEYCODE_BACK) {\n\t\t\texitBy2Click(); // 调用双击退出函数\n\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * 双击退出函数\n\t */\n\tprivate static Boolean isExit = false;\n\n\tpublic void exitBy2Click() {\n\t\tTimer tExit = null;\n\t\tif (isExit == false) {\n\t\t\tisExit = true; // 准备退出;\n\t\t\tString doubleClick;\n\t\t\tif (!TextUtils.isEmpty(spf.getString(\"UserName\", \"\"))\n\t\t\t\t\t&& !TextUtils.isEmpty(spf.getString(\"PassWord\", \"\"))) {\n\t\t\t\tdoubleClick = (String) getText(R.string.doubleclick_logout);\n\t\t\t} else {\n\t\t\t\tif (getIntent().getBooleanExtra(\"ThredLogin\", false)) {\n\t\t\t\t\tdoubleClick = (String) getText(R.string.doubleclick_logout);\n\t\t\t\t} else {\n\t\t\t\t\tdoubleClick = (String) getText(R.string.doubleclick_back);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tToast.makeText(this, doubleClick, 2000).show();\n\t\t\ttExit = new Timer();\n\t\t\ttExit.schedule(new TimerTask() {\n\t\t\t\t@Override\n\t\t\t\tpublic void run() {\n\t\t\t\t\tisExit = false; // 取消退出\n\t\t\t\t}\n\t\t\t}, 2000); // 如果2秒钟内没有按下返回键,则启动定时器取消掉刚才执行的任务\n\n\t\t} else {\n\t\t\tlogoutToClean();\n\t\t}\n\t}\n\n\t/** 注销函数 */\n\tvoid logoutToClean() {\n\t\tspf.edit().putString(\"UserName\", \"\").commit();\n\t\tspf.edit().putString(\"PassWord\", \"\").commit();\n\t\tspf.edit().putString(\"Uid\", \"\").commit();\n\t\tspf.edit().putString(\"Token\", \"\").commit();\n\t\tGosPushManager.pushUnBindService(token);\n\t\tfinish();\n\t\tif (loginStatus == 1) {\n\t\t\tloginStatus = 0;\n\t\t} else {\n\t\t\tloginStatus = 4;\n\t\t}\n\n\t}\n\n\t@Override\n\tprotected void onActivityResult(int requestCode, int resultCode, Intent data) {\n\t\tif (resultCode == 666) {\n\t\t\tfinish();\n\t\t} else if (resultCode == 98765) {\n\t\t\tTipsDialog dialog = new TipsDialog(GosDeviceListActivity.this,\n\t\t\t\t\tgetResources().getString(R.string.devicedisconnected));\n\n\t\t\tdialog.show();\n\t\t}\n\t}\n\n\tpublic Handler getMyHandler() {\n\n\t\treturn handler;\n\n\t}\n\n\t@Override\n\tpublic void onRefresh() {\n\t\thandler.sendEmptyMessageDelayed(PULL_TO_REFRESH, 2000);\n\n\t}\n\n\t\n\n}",
"public class GosMainActivity extends GosDeviceModuleBaseActivity {\n\n\tContext context = null;\n\t@SuppressWarnings(\"deprecation\")\n\tLocalActivityManager manager = null;\n\tNoScrollViewPager pager = null;\n\tTabHost tabHost = null;\n\tLinearLayout t1, t2, t3;\n\n\tString softssid, uid, token;\n\n\tprivate int offset = 0;// 动画偏移量\n\tprivate int currIndex = 0;// 当前页卡编号\n\tprivate int bmpW;// 动画图片宽度\n\tprivate ImageView cursor;// 动画图片\n\n\t/** 获取设备列表 */\n\tprotected static final int GETLIST = 0;\n\n\t/** 刷新设备列表 */\n\tprotected static final int UPDATALIST = 1;\n\tprivate Handler myHandler;\n\tprivate GosDeviceListActivity activity;\n\n\tprivate int viewPagerSelected = 0;\n\tprivate Intent intent;\n\tprivate messageCenterActivity center;\n\n\tpublic static Activity instance = null;\n\tprivate ImageView img1;\n\tprivate ImageView img2;\n\tprivate ImageView img3;\n\tprivate TextView tx1;\n\tprivate TextView tx2;\n\tprivate TextView tx3;\n\n\t@SuppressWarnings(\"deprecation\")\n\t@Override\n\tpublic void onCreate(Bundle savedInstanceState) {\n\t\tsuper.onCreate(savedInstanceState);\n\t\tsetContentView(R.layout.activity_gos_main);\n\n\t\tcontext = GosMainActivity.this;\n\t\tmanager = new LocalActivityManager(this, true);\n\t\tmanager.dispatchCreate(savedInstanceState);\n\t\tinstance = this;\n\t\tInitImageView();\n\t\tinitTextView();\n\t\tinitPagerViewer();\n\t\tinitHandler();\n\t\t\n\t\t\n\t\t\n\t\n\n\t}\n\n\t@SuppressWarnings(\"deprecation\")\n\tprivate void initHandler() {\n\t\tactivity = (GosDeviceListActivity) manager.getActivity(\"A\");\n\t\tcenter = (messageCenterActivity) manager.getActivity(\"B\");\n\t\tmyHandler = activity.getMyHandler();\n\t}\n\n\t@Override\n\tprotected void onResume() {\n\t\t\n\t\t// TODO Auto-generated method stub\n\t\tsuper.onResume();\n\t\tswitch (viewPagerSelected) {\n\t\tcase 0:\n\t\t\tactivity.onResume();\n\t\t\tbreak;\n\n\t\tcase 1:\n\t\t\tcenter.onResume();\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\n\t}\n\n\t@Override\n\tpublic void onPause() {\n\t\tsuper.onPause();\n\t\tactivity.onPause();\n\t}\n\n\t/**\n\t * 初始化标题\n\t */\n\tprivate void initTextView() {\n\t\tt1 = (LinearLayout) findViewById(R.id.text1);\n\t\tt2 = (LinearLayout) findViewById(R.id.text2);\n\t\tt3 = (LinearLayout) findViewById(R.id.text3);\n\n\t\timg1 = (ImageView) findViewById(R.id.img1);\n\t\timg2 = (ImageView) findViewById(R.id.img2);\n\t\timg3 = (ImageView) findViewById(R.id.img3);\n\n\t\ttx1 = (TextView) findViewById(R.id.tx1);\n\t\ttx2 = (TextView) findViewById(R.id.tx2);\n\t\ttx3 = (TextView) findViewById(R.id.tx3);\n\n\t\tt1.setOnClickListener(new MyOnClickListener(0));\n\t\tt2.setOnClickListener(new MyOnClickListener(1));\n\t\tt3.setOnClickListener(new MyOnClickListener(2));\n\n\t}\n\n\t/**\n\t * 初始化PageViewer\n\t */\n\tprivate void initPagerViewer() {\n\t\tpager = (NoScrollViewPager) findViewById(R.id.viewpage);\n\n\t\tpager.setNoScroll(true);\n\t\tfinal ArrayList<View> list = new ArrayList<View>();\n\n\t\tIntent intent = new Intent(context, GosDeviceListActivity.class);\n\t\tlist.add(getView(\"A\", intent));\n\t\tIntent intent2 = new Intent(context, messageCenterActivity.class);\n\t\tlist.add(getView(\"B\", intent2));\n\t\tIntent intent3 = new Intent(context, GosSettiingsActivity.class);\n\t\tlist.add(getView(\"C\", intent3));\n\n\t\tpager.setAdapter(new MyPagerAdapter(list));\n\t\tpager.setCurrentItem(0);\n\t\t// t1.setBackgroundColor(getResources().getColor(R.color.gray));\n\t\t// t2.setBackgroundColor(getResources().getColor(R.color.white));\n\t\t// t3.setBackgroundColor(getResources().getColor(R.color.white));\n\n\t\timg1.setBackgroundResource(R.drawable.grid);\n\t\timg2.setBackgroundResource(R.drawable.message_grey);\n\t\timg3.setBackgroundResource(R.drawable.user_grey);\n\n\t\ttx1.setTextColor(getResources().getColor(R.color.black));\n\t\ttx2.setTextColor(getResources().getColor(R.color.gray));\n\t\ttx3.setTextColor(getResources().getColor(R.color.gray));\n\t\tsetActionBar(false, false, R.string.devicelist_title);\n\t\t\n\t\t\n\t\tpager.setOnPageChangeListener(new MyOnPageChangeListener());\n\t}\n\n\t/**\n\t * 初始化动画\n\t */\n\t@SuppressWarnings(\"deprecation\")\n\tprivate void InitImageView() {\n\t\tcursor = (ImageView) findViewById(R.id.cursor);\n\t\tbmpW = BitmapFactory.decodeResource(getResources(), R.drawable.roller).getWidth();// 获取图片宽度\n\t\tDisplayMetrics dm = new DisplayMetrics();\n\t\tgetWindowManager().getDefaultDisplay().getMetrics(dm);\n\t\tint screenW = dm.widthPixels;// 获取分辨率宽度\n\t\toffset = (screenW / 3 - bmpW) / 2;// 计算偏移量\n\t\tMatrix matrix = new Matrix();\n\t\tmatrix.postTranslate(offset, 0);\n\t\tcursor.setImageMatrix(matrix);// 设置动画初始位置\n\n\t\tLinearLayout myll = (LinearLayout) findViewById(R.id.linearLayout1);\n\t\t\n\t\tmyll.setVisibility(GosDeploy.setUsingTabSetOn());\n\t\t\n\t\tmyll.setBackgroundDrawable(GosDeploy.setNavigationBarColor());\n\t}\n\n\t@Override\n\tpublic boolean onCreateOptionsMenu(Menu menu) {\n\n\t\tswitch (viewPagerSelected) {\n\t\tcase 0:\n\t\t\tgetMenuInflater().inflate(R.menu.devicelist_logout, menu);\n\t\t\tbreak;\n\n\t\tcase 1:\n\n\t\t\tbreak;\n\n\t\tcase 2:\n\n\t\t\tbreak;\n\n\t\tdefault:\n\t\t\tbreak;\n\t\t}\n\n\t\treturn true;\n\n\t}\n\n\t@Override\n\tpublic boolean onOptionsItemSelected(MenuItem item) {\n\t\tswitch (item.getItemId()) {\n\t\tcase android.R.id.home:\n\t\t\t// activity.logoutToClean();\n\n\t\t\t// finish();\n\t\t\tbreak;\n\t\tcase R.id.action_QR_code:\n\t\t\tintent = new Intent(GosMainActivity.this, CaptureActivity.class);\n\t\t\tstartActivity(intent);\n\t\t\tbreak;\n\t\tcase R.id.action_addDevice:\n\t\t\tif (!checkNetwork(GosMainActivity.this)) {\n\t\t\t\tToast.makeText(GosMainActivity.this, R.string.network_error, 2000).show();\n\t\t\t} else {\n\t\t\t\tintent = new Intent(GosMainActivity.this, GosAirlinkChooseDeviceWorkWiFiActivity.class);\n\t\t\t\tstartActivity(intent);\n\t\t\t}\n\t\t\tbreak;\n\n\t\t}\n\n\t\treturn super.onOptionsItemSelected(item);\n\t}\n\n\t/**\n\t * 通过activity获取视图\n\t * \n\t * @param id\n\t * @param intent\n\t * @return\n\t */\n\t@SuppressWarnings(\"deprecation\")\n\tprivate View getView(String id, Intent intent) {\n\t\treturn manager.startActivity(id, intent).getDecorView();\n\t}\n\n\t/**\n\t * Pager适配器\n\t */\n\tpublic class MyPagerAdapter extends PagerAdapter {\n\t\tList<View> list = new ArrayList<View>();\n\n\t\tpublic MyPagerAdapter(ArrayList<View> list) {\n\t\t\tthis.list = list;\n\t\t}\n\n\t\t@Override\n\t\tpublic void destroyItem(ViewGroup container, int position, Object object) {\n\t\t\tViewPager pViewPager = ((ViewPager) container);\n\t\t\tpViewPager.removeView(list.get(position));\n\t\t}\n\n\t\t@Override\n\t\tpublic boolean isViewFromObject(View arg0, Object arg1) {\n\t\t\treturn arg0 == arg1;\n\t\t}\n\n\t\t@Override\n\t\tpublic int getCount() {\n\t\t\treturn list.size();\n\t\t}\n\n\t\t@Override\n\t\tpublic Object instantiateItem(View arg0, int arg1) {\n\t\t\tViewPager pViewPager = ((ViewPager) arg0);\n\t\t\tpViewPager.addView(list.get(arg1));\n\t\t\treturn list.get(arg1);\n\t\t}\n\n\t\t@Override\n\t\tpublic void restoreState(Parcelable arg0, ClassLoader arg1) {\n\n\t\t}\n\n\t\t@Override\n\t\tpublic Parcelable saveState() {\n\t\t\treturn null;\n\t\t}\n\n\t\t@Override\n\t\tpublic void startUpdate(View arg0) {\n\t\t}\n\t}\n\n\t/**\n\t * 页卡切换监听\n\t */\n\tpublic class MyOnPageChangeListener implements OnPageChangeListener {\n\n\t\tint one = offset * 2 + bmpW;// 页卡1 -> 页卡2 偏移量\n\t\tint two = one * 2;// 页卡1 -> 页卡3 偏移量\n\n\t\t@Override\n\t\tpublic void onPageSelected(int arg0) {\n\n\t\t\tviewPagerSelected = arg0;\n\n\t\t\trefreshMenu();\n\t\t\tAnimation animation = null;\n\t\t\tswitch (arg0) {\n\t\t\tcase 0:\n\n\t\t\t\tif (currIndex == 1) {\n\n\t\t\t\t\tanimation = new TranslateAnimation(one, 0, 0, 0);\n\t\t\t\t} else if (currIndex == 2) {\n\t\t\t\t\tanimation = new TranslateAnimation(two, 0, 0, 0);\n\t\t\t\t}\n\n\t\t\t\tsetActionBar(false, false, R.string.devicelist_title);\n\t\t\t\tactivity.onResume();\n\t\t\t\tbreak;\n\t\t\tcase 1:\n\n\t\t\t\tif (currIndex == 0) {\n\t\t\t\t\tanimation = new TranslateAnimation(offset, one, 0, 0);\n\t\t\t\t} else if (currIndex == 2) {\n\t\t\t\t\tanimation = new TranslateAnimation(two, one, 0, 0);\n\t\t\t\t}\n\t\t\t\tsetActionBar(false, false, R.string.messagecenter);\n\t\t\t\tactivity.onPause();\n\t\t\t\tcenter.onResume();\n\t\t\t\tbreak;\n\n\t\t\tcase 2:\n\t\t\t\tactivity.onPause();\n\t\t\t\tif (currIndex == 0) {\n\t\t\t\t\tanimation = new TranslateAnimation(offset, two, 0, 0);\n\t\t\t\t} else if (currIndex == 1) {\n\t\t\t\t\tanimation = new TranslateAnimation(one, two, 0, 0);\n\t\t\t\t}\n\t\t\t\tsetActionBar(false, false, R.string.personal_center);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcurrIndex = arg0;\n\t\t\tanimation.setFillAfter(true);// True 图片停在动画结束位置\n\t\t\tanimation.setDuration(300);\n\t\t\tcursor.startAnimation(animation);\n\t\t}\n\n\t\t@Override\n\t\tpublic void onPageScrollStateChanged(int arg0) {\n\n\t\t}\n\n\t\t@Override\n\t\tpublic void onPageScrolled(int arg0, float arg1, int arg2) {\n\n\t\t}\n\t}\n\n\t/**\n\t * 图标点击监听\n\t */\n\tpublic class MyOnClickListener implements View.OnClickListener {\n\t\tprivate int index = 0;\n\n\t\tpublic MyOnClickListener(int i) {\n\t\t\tindex = i;\n\n\t\t}\n\n\t\t@Override\n\t\tpublic void onClick(View v) {\n\t\t\tpager.setCurrentItem(index);\n\n\t\t\tswitch (index) {\n\t\t\tcase 0:\n\t\t\t\t// t1.setBackgroundColor(getResources().getColor(R.color.gray));\n\t\t\t\t// t2.setBackgroundColor(getResources().getColor(R.color.white));\n\t\t\t\t// t3.setBackgroundColor(getResources().getColor(R.color.white));\n\n\t\t\t\timg1.setBackgroundResource(R.drawable.grid);\n\t\t\t\timg2.setBackgroundResource(R.drawable.message_grey);\n\t\t\t\timg3.setBackgroundResource(R.drawable.user_grey);\n\n\t\t\t\ttx1.setTextColor(getResources().getColor(R.color.black));\n\t\t\t\ttx2.setTextColor(getResources().getColor(R.color.gray));\n\t\t\t\ttx3.setTextColor(getResources().getColor(R.color.gray));\n\t\t\t\tbreak;\n\n\t\t\tcase 1:\n\t\t\t\t// t1.setBackgroundColor(getResources().getColor(R.color.white));\n\t\t\t\t// t2.setBackgroundColor(getResources().getColor(R.color.gray));\n\t\t\t\t// t3.setBackgroundColor(getResources().getColor(R.color.white));\n\n\t\t\t\timg1.setBackgroundResource(R.drawable.grid_grey);\n\t\t\t\timg2.setBackgroundResource(R.drawable.message);\n\t\t\t\timg3.setBackgroundResource(R.drawable.user_grey);\n\n\t\t\t\ttx1.setTextColor(getResources().getColor(R.color.gray));\n\t\t\t\ttx2.setTextColor(getResources().getColor(R.color.black));\n\t\t\t\ttx3.setTextColor(getResources().getColor(R.color.gray));\n\t\t\t\tbreak;\n\n\t\t\tcase 2:\n\t\t\t\t// t1.setBackgroundColor(getResources().getColor(R.color.white));\n\t\t\t\t// t2.setBackgroundColor(getResources().getColor(R.color.white));\n\t\t\t\t// t3.setBackgroundColor(getResources().getColor(R.color.gray));\n\n\t\t\t\timg1.setBackgroundResource(R.drawable.grid_grey);\n\t\t\t\timg2.setBackgroundResource(R.drawable.message_grey);\n\t\t\t\timg3.setBackgroundResource(R.drawable.user);\n\n\t\t\t\ttx1.setTextColor(getResources().getColor(R.color.gray));\n\t\t\t\ttx2.setTextColor(getResources().getColor(R.color.gray));\n\t\t\t\ttx3.setTextColor(getResources().getColor(R.color.black));\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t};\n\n\t// 刷新menu的方法\n\tprivate void refreshMenu() {\n\t\t// 核心是Activity这个方法\n\t\tsupportInvalidateOptionsMenu();\n\t}\n\n\t// @SuppressWarnings(\"deprecation\")\n\t// protected void didDiscovered(GizWifiErrorCode result,\n\t// java.util.List<GizWifiDevice> deviceList) {\n\t// GosDeviceModuleBaseActivity.deviceslist.clear();\n\t// for (GizWifiDevice gizWifiDevice : deviceList) {\n\t// GosDeviceModuleBaseActivity.deviceslist.add(gizWifiDevice);\n\t// }\n\t// // handler.sendEmptyMessage(UPDATALIST);\n\t//\n\t// myHandler.sendEmptyMessage(UPDATALIST);\n\t//\n\t// }\n\t//\n\t// protected void didUserLogin(GizWifiErrorCode result, java.lang.String\n\t// uid, java.lang.String token) {\n\t//\n\t// if (GizWifiErrorCode.GIZ_SDK_SUCCESS == result) {\n\t// GosDeviceListActivity.loginStatus = 2;\n\t// this.uid = uid;\n\t// this.token = token;\n\t// spf.edit().putString(\"Uid\", this.uid).commit();\n\t// spf.edit().putString(\"Token\", this.token).commit();\n\t// myHandler.sendEmptyMessage(GETLIST);\n\t// // TODO 绑定推送\n\t// GosPushManager.pushBindService(token);\n\t// } else {\n\t// GosDeviceListActivity.loginStatus = 0;\n\t// if (GosDeploy.setAnonymousLogin()) {\n\t// //tryUserLoginAnonymous();\n\t// }\n\t//\n\t// }\n\t// }\n\t//\n\t//\n\t// protected void didUnbindDevice(GizWifiErrorCode result, java.lang.String\n\t// did) {\n\t// progressDialog.cancel();\n\t// if (GizWifiErrorCode.GIZ_SDK_SUCCESS != result) {\n\t// // String unBoundFailed = (String) getText(R.string.unbound_failed);\n\t// Toast.makeText(this, toastError(result), 2000).show();\n\t// }\n\t// }\n\t//\n\n\t/**\n\t * 菜单、返回键响应\n\t */\n\t@Override\n\tpublic boolean onKeyDown(int keyCode, KeyEvent event) {\n\t\tif (keyCode == KeyEvent.KEYCODE_BACK) {\n\t\t\texitBy2Click();\n\t\t}\n\t\treturn false;\n\t}\n\n\t@Override\n\tprotected void onActivityResult(int requestCode, int resultCode, Intent data) {\n\t\tif (resultCode == 666) {\n\t\t\tfinish();\n\t\t} else if (resultCode == 98765) {\n\t\t\tTipsDialog dialog = new TipsDialog(GosMainActivity.this,\n\t\t\t\t\tgetResources().getString(R.string.devicedisconnected));\n\n\t\t\tdialog.show();\n\t\t}\n\n\t}\n\n\tpublic void finishMe() {\n\t\tfinish();\n\t}\n\n\tpublic void exitBy2Click() {\n\t\tTimer tExit = null;\n\t\tif (isExit == false) {\n\t\t\tisExit = true; // 准备退出;\n\t\t\tString doubleClick;\n\t\t\tif (!TextUtils.isEmpty(spf.getString(\"UserName\", \"\"))\n\t\t\t\t\t&& !TextUtils.isEmpty(spf.getString(\"PassWord\", \"\"))) {\n\t\t\t\tdoubleClick = (String) getText(R.string.doubleclick_logout);\n\t\t\t} else {\n\t\t\t\tif (getIntent().getBooleanExtra(\"ThredLogin\", false)) {\n\t\t\t\t\tdoubleClick = (String) getText(R.string.doubleclick_logout);\n\t\t\t\t} else {\n\t\t\t\t\tdoubleClick = (String) getText(R.string.doubleclick_back);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tToast.makeText(this, doubleClick, 2000).show();\n\t\t\ttExit = new Timer();\n\t\t\ttExit.schedule(new TimerTask() {\n\t\t\t\t@Override\n\t\t\t\tpublic void run() {\n\t\t\t\t\tisExit = false; // 取消退出\n\t\t\t\t}\n\t\t\t}, 2000); // 如果2秒钟内没有按下返回键,则启动定时器取消掉刚才执行的任务\n\n\t\t} else {\n\t\t\tlogoutToClean();\n\t\t}\n\t}\n\n\t/** 注销函数 */\n\tvoid logoutToClean() {\n\t\tspf.edit().putString(\"UserName\", \"\").commit();\n\t\tspf.edit().putString(\"PassWord\", \"\").commit();\n\t\tspf.edit().putString(\"Uid\", \"\").commit();\n\t\tspf.edit().putString(\"thirdUid\", \"\").commit();\n\n\t\tGosPushManager.pushUnBindService(spf.getString(\"Token\", \"\"));\n\t\tspf.edit().putString(\"Token\", \"\").commit();\n\n\t\tfinish();\n\t\tif (GosDeviceListActivity.loginStatus == 1) {\n\t\t\tGosDeviceListActivity.loginStatus = 0;\n\t\t} else {\n\t\t\tGosDeviceListActivity.loginStatus = 4;\n\t\t}\n\n\t}\n\n\t/**\n\t * 双击退出函数\n\t */\n\tprivate static Boolean isExit = false;\n}",
"public class GosPushManager {\n\n\tstatic GizPushType gizPushType;\n\n\tstatic Context context;\n\n\tpublic GosPushManager(int PushType, Context context) {\n\t\tsuper();\n\t\tGosPushManager.context = context;\n\t\tif (PushType == 1) {\n\t\t\tGosPushManager.gizPushType = GizPushType.GizPushJiGuang;\n\t\t\tjPush();\n\t\t} else if (PushType == 2) {\n\t\t\tGosPushManager.gizPushType = GizPushType.GizPushBaiDu;\n\t\t\tbDPush();\n\t\t} else {\n\n\t\t}\n\n\t}\n\n\t/** Channel_ID */\n\tpublic static String Channel_ID;\n\n\t/**\n\t * 此方法完成了初始化JPush SDK等功能 但仍需在MainActivity的onResume和onPause添加相应方法\n\t * JPushInterface.onResume(context); JPushInterface.onPause(context);\n\t * \n\t * @param context\n\t */\n\tpublic void jPush() {\n\t\t// 设置JPush调试模式\n\t\tJPushInterface.setDebugMode(true);\n\n\t\t// 初始化JPushSDK\n\t\tJPushInterface.init(context);\n\n\t}\n\n\tpublic void bDPush() {\n\t\tfinal String BDPushAppKey = GosDeploy.setBaiDuPushAppKey();\n\t\tif (TextUtils.isEmpty(BDPushAppKey) || BDPushAppKey.contains(\"your_bpush_api_key\")) {\n\t\t\tGosBaseActivity.noIDAlert(context, R.string.BDPushAppID_Toast);\n\t\t} else {\n\n\t\t\tPushManager.startWork(context, PushConstants.LOGIN_TYPE_API_KEY, BDPushAppKey);\n\t\t\tPushSettings.enableDebugMode(context, true);\n\n\t\t}\n\n\t}\n\n\t/**\n\t * 向云端绑定推送\n\t * \n\t * @param Token\n\t * @param Channel_ID\n\t * @param gizPushType\n\t */\n\tpublic static void pushBindService(String token) {\n\n\t\tif (GizPushType.GizPushJiGuang == gizPushType) {\n\t\t\t// 获取JPush的RegistrationID,即Channel_ID\n\t\t\tChannel_ID = JPushInterface.getRegistrationID(context);\n\n\t\t\t// 设定JPush类型\n\t\t\tJPushInterface.setAlias(context, Channel_ID, new TagAliasCallback() {\n\t\t\t\t@Override\n\t\t\t\tpublic void gotResult(int arg0, String arg1, Set<String> arg2) {\n\t\t\t\t\tif (arg0 == 0) {\n\t\t\t\t\t\tLog.i(\"Apptest\", \"Alias: \" + arg1);\n\t\t\t\t\t} else {\n\t\t\t\t\t\tLog.e(\"Apptest\", \"Result: \" + arg0);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t});\n\n\t\t} else if (GizPushType.GizPushBaiDu == gizPushType) {\n\t\t\t// 获取BDPush的Channel_ID\n\t\t\tChannel_ID = BaiDuPushReceiver.BaiDuPush_Channel_ID;\n\t\t} else {\n\t\t\treturn;\n\t\t}\n\n\t\t// TODO 绑定推送\n\t\tLog.i(\"Apptest\", Channel_ID + \"\\n\" + gizPushType.toString() + \"\\n\" + token);\n\t\tGizWifiSDK.sharedInstance().channelIDBind(token, Channel_ID, gizPushType);\n\t}\n\n\tpublic static void pushUnBindService(String token) {\n\n\t\tif (token.isEmpty()) {\n\t\t\treturn;\n\t\t}\n\n\t\tif (GizPushType.GizPushJiGuang == gizPushType) {\n\t\t\t// 获取JPush的RegistrationID,即Channel_ID\n\t\t\tChannel_ID = JPushInterface.getRegistrationID(context);\n\t\t} else if (GizPushType.GizPushBaiDu == gizPushType) {\n\t\t\t// 获取BDPush的Channel_ID\n\t\t\tChannel_ID = BaiDuPushReceiver.BaiDuPush_Channel_ID;\n\t\t} else {\n\t\t\treturn;\n\t\t}\n\t\t// TODO 绑定推送\n\t\tLog.i(\"Apptest\", Channel_ID + \"\\n\" + gizPushType.toString() + \"\\n\" + token);\n\t\tGizWifiSDK.sharedInstance().channelIDUnBind(token, Channel_ID);\n\t}\n}",
"public class DotView extends View {\n\tprivate Paint p;\n\tprivate int width;\n\tprivate int height;\n\tprivate int dash;\n\t\n\tpublic DotView(Context context, AttributeSet attrs) {\n\t\tsuper(context, attrs);\n\t\tinit(context);\n\t}\n\n\tpublic DotView(Context context) {\n\t\tsuper(context);\n\t\tinit(context);\n\t}\n\tprivate void init(Context context){\n\t\tp = new Paint(Paint.ANTI_ALIAS_FLAG); \n\t\tp.setStyle(Style.FILL); \n\t\tp.setColor(context.getResources().getColor(R.color.line_gray)); \n\t\t\n\t\tfinal float scale = context.getResources().getDisplayMetrics().density;\n\t\tdash=(int) (3 * scale + 0.5f);\n\t}\n\t@Override\n\tprotected void onDraw(Canvas canvas) {\n\t\t\n\t\tif(width>10){\n\t\t\tfor(int i=0;i<width;i+=dash){\n\t\t\t\tcanvas.drawLine(i, 0, i+=dash, 0, p);\n\t\t\t}\n\t\t}\n\t\tsuper.onDraw(canvas);\n\t}\n\t\n\t@Override \n public void onSizeChanged(int w, int h, int oldw, int oldh) { \n super.onSizeChanged(w, h, oldw, oldh); \n width=w;\n height=h;\n p.setStrokeWidth(height); \n this.postInvalidate();\n } \n\t\n\t\n\t\n\n}"
] | import java.util.Timer;
import java.util.TimerTask;
import org.json.JSONException;
import org.json.JSONObject;
import com.gizwits.gizwifisdk.api.GizWifiSDK;
import com.gizwits.gizwifisdk.enumration.GizEventType;
import com.gizwits.gizwifisdk.enumration.GizThirdAccountType;
import com.gizwits.gizwifisdk.enumration.GizWifiErrorCode;
import com.gizwits.opensource.appkit.GosApplication;
import com.gizwits.opensource.appkit.R;
import com.gizwits.opensource.appkit.CommonModule.GosBaseActivity;
import com.gizwits.opensource.appkit.CommonModule.GosDeploy;
import com.gizwits.opensource.appkit.CommonModule.TipsDialog;
import com.gizwits.opensource.appkit.DeviceModule.GosDeviceListActivity;
import com.gizwits.opensource.appkit.DeviceModule.GosMainActivity;
import com.gizwits.opensource.appkit.PushModule.GosPushManager;
import com.gizwits.opensource.appkit.ThirdAccountModule.BaseUiListener;
import com.gizwits.opensource.appkit.view.DotView;
import com.tencent.mm.sdk.modelmsg.SendAuth;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.jpush.android.api.JPushInterface; | package com.gizwits.opensource.appkit.UserModule;
@SuppressLint("HandlerLeak")
public class GosUserLoginActivity extends GosUserModuleBaseActivity implements OnClickListener {
GosPushManager gosPushManager;
/** The et Name */
private static EditText etName;
/** The et Psw */
private static EditText etPsw;
/** The btn Login */
private Button btnLogin;
/** The tv Register */
private TextView tvRegister;
/** The tv Forget */
private TextView tvForget;
/** The tv Pass */
private TextView tvPass;
/** The cb Laws */
private CheckBox cbLaws;
/** The ll QQ */
private LinearLayout llQQ;
/** The ll Wechat */
private LinearLayout llWechat;
/** The Tencent */
private Tencent mTencent;
/** The Wechat */
public static IWXAPI mIwxapi;
/** The Scope */
private String Scope = "get_user_info,add_t";
/** The IUiListener */
IUiListener listener;
Intent intent;
/** The GizThirdAccountType */
public static GizThirdAccountType gizThirdAccountType;
/** The THRED_LOGIN UID&TOKEN */
public static String thirdUid, thirdToken;
public static enum handler_key {
/** 登录 */
LOGIN,
/** 自动登录 */
AUTO_LOGIN,
/** 第三方登录 */
THRED_LOGIN,
}
/** 与WXEntryActivity共用Handler */
private Handler baseHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
super.handleMessage(msg);
handler_key key = handler_key.values()[msg.what];
switch (key) {
// 登录
case LOGIN:
progressDialog.show();
GosDeviceListActivity.loginStatus = 0;
GizWifiSDK.sharedInstance().userLogin(etName.getText().toString(), etPsw.getText().toString());
break;
// 自动登录
case AUTO_LOGIN:
progressDialog.show();
GosDeviceListActivity.loginStatus = 0;
GizWifiSDK.sharedInstance().userLogin(spf.getString("UserName", ""), spf.getString("PassWord", ""));
break;
// 第三方登录
case THRED_LOGIN:
progressDialog.show();
GosDeviceListActivity.loginStatus = 0;
GizWifiSDK.sharedInstance().loginWithThirdAccount(gizThirdAccountType, thirdUid, thirdToken);
spf.edit().putString("thirdUid", thirdUid).commit();
break;
}
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(R.style.AppTheme);
if (!this.isTaskRoot()) {// 判断此activity是不是任务控件的源Activity,“非”也就是说是被系统重新实例化出来的
Intent mainIntent = getIntent();
String action = mainIntent.getAction();
if (mainIntent.hasCategory(Intent.CATEGORY_LAUNCHER) && action.equals(Intent.ACTION_MAIN)) {
finish();
return;
}
} | if (GosApplication.flag != 0) { | 0 |
MizzleDK/Mizuu | app/src/main/java/com/miz/filesources/UpnpMovie.java | [
"public abstract class MovieFileSource<T> extends AbstractFileSource<T> {\n\n\tprotected List<DbMovie> mDbMovies = new ArrayList<DbMovie>();\n\n\tpublic MovieFileSource(Context context, FileSource fileSource, boolean clearLibrary) {\n\t\tmContext = context;\n\t\tmFileSource = fileSource;\n\t\tmClearLibrary = clearLibrary;\n\n\t\tmFileSizeLimit = MizLib.getFileSizeLimit(getContext());\n\n\t\tsetFolder(getRootFolder());\n\t}\n\n\tprivate void setupDbMovies() {\n\t\tmDbMovies.clear();\n\t\t\n\t\t// Fetch all the movies from the database\n\t\tDbAdapterMovies db = MizuuApplication.getMovieAdapter();\n\n\t\tColumnIndexCache cache = new ColumnIndexCache();\n\t\tCursor tempCursor = db.fetchAllMovies(DbAdapterMovies.KEY_TITLE + \" ASC\");\n\t\ttry {\n\t\t\twhile (tempCursor.moveToNext()) {\n\t\t\t\tmDbMovies.add(new DbMovie(getContext(),\n\t\t\t\t\t\tMizuuApplication.getMovieMappingAdapter().getFirstFilepathForMovie(tempCursor.getString(cache.getColumnIndex(tempCursor, DbAdapterMovieMappings.KEY_TMDB_ID))),\n\t\t\t\t\t\ttempCursor.getString(cache.getColumnIndex(tempCursor, DbAdapterMovies.KEY_TMDB_ID)),\n\t\t\t\t\t\ttempCursor.getString(cache.getColumnIndex(tempCursor, DbAdapterMovies.KEY_RUNTIME)),\n\t\t\t\t\t\ttempCursor.getString(cache.getColumnIndex(tempCursor, DbAdapterMovies.KEY_RELEASEDATE)),\n\t\t\t\t\t\ttempCursor.getString(cache.getColumnIndex(tempCursor, DbAdapterMovies.KEY_GENRES)),\n\t\t\t\t\t\ttempCursor.getString(cache.getColumnIndex(tempCursor, DbAdapterMovies.KEY_TITLE))));\n\t\t\t}\n\t\t} catch (NullPointerException e) {\n\t\t} finally {\n\t\t\ttempCursor.close();\n\t\t\tcache.clear();\n\t\t}\n\t}\n\t\n\tpublic List<DbMovie> getDbMovies() {\n\t\tif (mDbMovies.size() == 0)\n\t\t\tsetupDbMovies();\n\t\treturn mDbMovies;\n\t}\n\n}",
"public class DbAdapterMovieMappings extends AbstractDbAdapter {\n\n\tpublic static final String KEY_FILEPATH = \"filepath\";\n\tpublic static final String KEY_TMDB_ID = \"tmdbid\";\n\tpublic static final String KEY_IGNORED = \"ignored\";\n\n\tpublic static final String DATABASE_TABLE = \"moviemap\";\n\n\tpublic static final String[] ALL_COLUMNS = new String[]{KEY_FILEPATH, KEY_TMDB_ID, KEY_IGNORED};\n\n\tpublic DbAdapterMovieMappings(Context context) {\n\t\tsuper(context);\n\t}\n\n\tpublic long createFilepathMapping(String filepath, String tmdbId) {\n // We only want to create a filepath mapping if\n // the filepath doesn't already exist\n\t\tif (!filepathExists(tmdbId, filepath)) {\n\t\t\t// Add values to a ContentValues object\n\t\t\tContentValues values = new ContentValues();\n\t\t\tvalues.put(KEY_FILEPATH, filepath);\n\t\t\tvalues.put(KEY_TMDB_ID, tmdbId);\n\t\t\tvalues.put(KEY_IGNORED, 0);\n\n\t\t\t// Insert into database\n return mDatabase.insert(DATABASE_TABLE, null, values);\n\t\t}\n\t\treturn -1;\n\t}\n\n\tpublic Cursor getAllFilepaths(boolean includeRemoved) {\n\t\treturn mDatabase.query(DATABASE_TABLE, ALL_COLUMNS, includeRemoved ? null : \"NOT(\" + KEY_IGNORED + \" = '1')\", null, null, null, null);\n\t}\n\n\tpublic Cursor getAllUnidentifiedFilepaths() {\n\t\treturn mDatabase.query(DATABASE_TABLE, ALL_COLUMNS, \"NOT(\" + KEY_IGNORED + \" = '1') AND \" + KEY_TMDB_ID + \"='\" + DbAdapterMovies.UNIDENTIFIED_ID + \"'\", null, null, null, null);\n\t}\n\t\n\tpublic boolean deleteAllUnidentifiedFilepaths() {\n\t\treturn mDatabase.delete(DATABASE_TABLE, KEY_TMDB_ID + \" = ?\", new String[]{DbAdapterMovies.UNIDENTIFIED_ID}) > 0;\n\t}\n\n\tpublic String getFirstFilepathForMovie(String tmdbId) {\n\t\tCursor cursor = mDatabase.query(DATABASE_TABLE, new String[]{KEY_TMDB_ID, KEY_FILEPATH}, KEY_TMDB_ID + \" = ?\", new String[]{tmdbId}, null, null, null);\n\t\tString filepath = \"\";\n\n\t\tif (cursor != null) {\n\t\t\ttry {\n\t\t\t\tif (cursor.moveToFirst()) {\n\t\t\t\t\tfilepath = cursor.getString(cursor.getColumnIndex(KEY_FILEPATH));\n\t\t\t\t}\n\t\t\t} catch (Exception e) {\n\t\t\t} finally {\n\t\t\t\tcursor.close();\n\t\t\t}\n\t\t}\n\n\t\treturn filepath;\n\t}\n\n\tpublic boolean updateTmdbId(String filepath, String currentId, String newId) {\n\t\tContentValues values = new ContentValues();\n\t\tvalues.put(KEY_TMDB_ID, newId);\n\n\t\treturn mDatabase.update(DATABASE_TABLE, values, KEY_FILEPATH + \" = ? AND \" + KEY_TMDB_ID + \" = ?\", new String[]{filepath, currentId}) > 0;\n\t}\n\n public boolean updateTmdbId(String filepath, String newId) {\n ContentValues values = new ContentValues();\n values.put(KEY_TMDB_ID, newId);\n\n return mDatabase.update(DATABASE_TABLE, values, KEY_FILEPATH + \" = ?\", new String[]{filepath}) > 0;\n }\n\n\tpublic boolean exists(String tmdbId) {\n\t\tCursor cursor = mDatabase.query(DATABASE_TABLE, ALL_COLUMNS, KEY_TMDB_ID + \" = ?\", new String[]{tmdbId}, null, null, null);\n\t\tboolean result = false;\n\n\t\tif (cursor != null) {\n\t\t\ttry {\n\t\t\t\tif (cursor.getCount() > 0)\n\t\t\t\t\tresult = true;\n\t\t\t} catch (Exception e) {\n\t\t\t} finally {\n\t\t\t\tcursor.close();\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tpublic boolean filepathExists(String tmdbId, String filepath) {\n\t\tString[] selectionArgs = new String[]{tmdbId, filepath};\n\t\tCursor cursor = mDatabase.query(DATABASE_TABLE, ALL_COLUMNS, KEY_TMDB_ID + \" = ? AND \" + KEY_FILEPATH + \" = ?\", selectionArgs, null, null, null);\n\t\tboolean result = false;\n\n\t\tif (cursor != null) {\n\t\t\ttry {\n\t\t\t\tif (cursor.getCount() > 0)\n\t\t\t\t\tresult = true;\n\t\t\t} catch (Exception e) {\n\t\t\t} finally {\n\t\t\t\tcursor.close();\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tpublic boolean deleteMovie(String tmdbId) {\n\t\treturn mDatabase.delete(DATABASE_TABLE, KEY_TMDB_ID + \" = ?\", new String[]{tmdbId}) > 0;\n\t}\n\n\tpublic boolean deleteAllMovies() {\n\t\treturn mDatabase.delete(DATABASE_TABLE, null, null) > 0;\n\t}\n\n\tpublic boolean hasMultipleFilepaths(String tmdbId) {\n\t\tCursor cursor = mDatabase.query(DATABASE_TABLE, ALL_COLUMNS, KEY_TMDB_ID + \" = ?\", new String[]{tmdbId}, null, null, null);\n\t\tboolean result = false;\n\n\t\tif (cursor != null) {\n\t\t\ttry {\n\t\t\t\tif (cursor.getCount() > 1)\n\t\t\t\t\tresult = true;\n\t\t\t} catch (Exception e) {\n\t\t\t} finally {\n\t\t\t\tcursor.close();\n\t\t\t}\n\t\t}\n\n\t\treturn result;\n\t}\n\n /**\n * Gets all un-ignored filepaths mapped to a given movie ID\n * @param tmdbId\n * @return\n */\n\tpublic ArrayList<String> getMovieFilepaths(String tmdbId) {\n if (TextUtils.isEmpty(tmdbId))\n return new ArrayList<>();\n\n\t\tCursor cursor = mDatabase.query(DATABASE_TABLE, ALL_COLUMNS, KEY_TMDB_ID + \" = ? AND \" + KEY_IGNORED + \" = '0'\", new String[]{tmdbId}, null, null, null);\n\t\tArrayList<String> paths = new ArrayList<String>();\n\n\t\tif (cursor != null) {\n\t\t\ttry {\n\t\t\t\twhile (cursor.moveToNext()) {\n\t\t\t\t\tpaths.add(cursor.getString(cursor.getColumnIndex(DbAdapterMovieMappings.KEY_FILEPATH)));\n\t\t\t\t}\n\t\t\t} catch (Exception e) {\t\n\t\t\t} finally {\n\t\t\t\tcursor.close();\n\t\t\t}\n\t\t}\n\n\t\treturn paths;\n\t}\n\n\tpublic String getIdForFilepath(String filepath) {\n\t\tString[] selectionArgs = new String[]{filepath};\n\t\tCursor cursor = mDatabase.query(DATABASE_TABLE, new String[]{KEY_TMDB_ID, KEY_FILEPATH}, KEY_FILEPATH + \" = ?\", selectionArgs, null, null, null);\n\t\tString id = \"\";\n\n\t\tif (cursor != null) {\n\t\t\ttry {\n\t\t\t\tif (cursor.moveToFirst()) {\n\t\t\t\t\tid = cursor.getString(cursor.getColumnIndex(KEY_TMDB_ID));\n\t\t\t\t}\n\t\t\t} catch (Exception e) {\n\t\t\t} finally {\n\t\t\t\tcursor.close();\n\t\t\t}\n\t\t}\n\n\t\treturn id;\n\t}\n\n /**\n * Used for unit testing\n * @return\n */\n public int count() {\n Cursor c = mDatabase.query(DATABASE_TABLE, new String[]{KEY_FILEPATH}, null, null, null, null, null);\n int count = c.getCount();\n c.close();\n return count;\n }\n}",
"@SuppressLint(\"NewApi\")\npublic class MizLib {\n\n public static final String TYPE = \"type\";\n public static final String MOVIE = \"movie\";\n public static final String TV_SHOW = \"tvshow\";\n public static final String FILESOURCE = \"filesource\";\n public static final String USER = \"user\";\n public static final String PASSWORD = \"password\";\n public static final String DOMAIN = \"domain\";\n public static final String SERVER = \"server\";\n public static final String SERIAL_NUMBER = \"serial_number\";\n\n public static final String allFileTypes = \".3gp.aaf.mp4.ts.webm.m4v.mkv.divx.xvid.rec.avi.flv.f4v.moi.mpeg.mpg.mts.m2ts.ogv.rm.rmvb.mov.wmv.iso.vob.ifo.wtv.pyv.ogm.img\";\n public static final String IMAGE_CACHE_DIR = \"thumbs\";\n public static final String CHARACTER_REGEX = \"[^\\\\w\\\\s]\";\n public static final String[] prefixes = new String[]{\"the \", \"a \", \"an \"};\n\n public static final int SECOND = 1000;\n public static final int MINUTE = 60 * SECOND;\n public static final int HOUR = 60 * MINUTE;\n public static final int DAY = 24 * HOUR;\n public static final int WEEK = 7 * DAY;\n\n private MizLib() {} // No instantiation\n\n public static String getTmdbApiKey(Context context) {\n String key = context.getString(R.string.tmdb_api_key);\n if (TextUtils.isEmpty(key) || key.equals(\"add_your_own\"))\n throw new RuntimeException(\"You need to add a TMDb API key!\");\n return key;\n }\n\n public static String getTvdbApiKey(Context context) {\n String key = context.getString(R.string.tvdb_api_key);\n if (TextUtils.isEmpty(key) || key.equals(\"add_your_own\"))\n throw new RuntimeException(\"You need to add a TVDb API key!\");\n return key;\n }\n\n public static boolean isVideoFile(String s) {\n String[] fileTypes = new String[]{\".3gp\",\".aaf.\",\"mp4\",\".ts\",\".webm\",\".m4v\",\".mkv\",\".divx\",\".xvid\",\".rec\",\".avi\",\".flv\",\".f4v\",\".moi\",\".mpeg\",\".mpg\",\".mts\",\".m2ts\",\".ogv\",\".rm\",\".rmvb\",\".mov\",\".wmv\",\".iso\",\".vob\",\".ifo\",\".wtv\",\".pyv\",\".ogm\",\".img\"};\n int count = fileTypes.length;\n for (int i = 0; i < count; i++)\n if (s.endsWith(fileTypes[i]))\n return true;\n return false;\n }\n\n /**\n * Converts the first character of a String to upper case.\n * @param s (input String)\n * @return Input String with first character in upper case.\n */\n public static String toCapitalFirstChar(String s) {\n if (TextUtils.isEmpty(s))\n return \"\";\n\n return s.substring(0, 1).toUpperCase(Locale.ENGLISH) + s.substring(1, s.length());\n }\n\n /**\n * Converts the first character of all words (separated by space)\n * in the String to upper case.\n * @param s (input String)\n * @return Input string with first character of all words in upper case.\n */\n public static String toCapitalWords(String s) {\n if (TextUtils.isEmpty(s))\n return \"\";\n\n StringBuilder result = new StringBuilder();\n String[] split = s.split(\"\\\\s\");\n int count = split.length;\n for (int i = 0; i < count; i++)\n result.append(toCapitalFirstChar(split[i])).append(\" \");\n return result.toString().trim();\n }\n\n /**\n * Adds spaces between capital characters.\n * @param s (input String)\n * @return Input string with spaces between capital characters.\n */\n public static String addSpaceByCapital(String s) {\n if (TextUtils.isEmpty(s))\n return \"\";\n\n StringBuilder result = new StringBuilder();\n char[] chars = s.toCharArray();\n for (int i = 0; i < chars.length; i++)\n if (chars.length > (i+1))\n if (Character.isUpperCase(chars[i]) && (Character.isLowerCase(chars[i+1]) && !Character.isSpaceChar(chars[i+1])))\n result.append(\" \").append(chars[i]);\n else\n result.append(chars[i]);\n else\n result.append(chars[i]);\n return result.toString().trim();\n }\n\n /**\n * Returns any digits (numbers) in a String\n * @param s (Input string)\n * @return A string with any digits from the input string\n */\n public static String getNumbersInString(String s) {\n if (TextUtils.isEmpty(s))\n return \"\";\n\n StringBuilder result = new StringBuilder();\n char[] charArray = s.toCharArray();\n int count = charArray.length;\n for (int i = 0; i < count; i++)\n if (Character.isDigit(charArray[i]))\n result.append(charArray[i]);\n\n return result.toString();\n }\n\n public static int getCharacterCountInString(String source, char c) {\n int result = 0;\n if (!TextUtils.isEmpty(source))\n for (int i = 0; i < source.length(); i++)\n if (source.charAt(i) == c)\n result++;\n return result;\n }\n\n /**\n * Determines if the application is running on a tablet\n * @param c - Context of the application\n * @return True if running on a tablet, false if on a smartphone\n */\n public static boolean isTablet(Context c) {\n return (c.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;\n }\n\n /**\n * Determines if the application is running on a xlarge tablet\n * @param c - Context of the application\n * @return True if running on a xlarge tablet, false if on a smaller device\n */\n public static boolean isXlargeTablet(Context c) {\n return (c.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_XLARGE;\n }\n\n /**\n * Determines if the device is in portrait mode\n * @param c - Context of the application\n * @return True if portrait mode, false if landscape mode\n */\n public static boolean isPortrait(Context c) {\n return c != null && (c.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT);\n }\n\n /**\n * Determines if the device is currently connected to a network\n * @param c - Context of the application\n * @return True if connected to a network, else false\n */\n public static boolean isOnline(Context c) {\n ConnectivityManager cm = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);\n NetworkInfo[] netInfo = cm.getAllNetworkInfo();\n int count = netInfo.length;\n for (int i = 0; i < count; i++)\n if (netInfo[i] != null && netInfo[i].isConnected()) return true;\n return false;\n }\n\n /**\n * Determines if the device is currently connected to a WiFi or Ethernet network\n * @param c - Context of the application\n * @return True if connected to a network, else false\n */\n public static boolean isWifiConnected(Context c) {\n if (c!= null) {\n ConnectivityManager connManager = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);\n NetworkInfo[] connections = connManager.getAllNetworkInfo();\n int count = connections.length;\n for (int i = 0; i < count; i++)\n if (connections[i]!= null && connections[i].getType() == ConnectivityManager.TYPE_WIFI && connections[i].isConnectedOrConnecting() ||\n connections[i]!= null && connections[i].getType() == ConnectivityManager.TYPE_ETHERNET && connections[i].isConnectedOrConnecting())\n return true;\n }\n return false;\n }\n\n /**\n * Returns a custom theme background image as Bitmap.\n * @param height\n * @param width\n * @return Bitmap with the background image\n */\n public static Bitmap getCustomThemeBackground(int height, int width, String url) {\n try {\n BitmapFactory.Options options = new BitmapFactory.Options();\n options.inPreferredConfig = Config.RGB_565;\n options.inDither = true;\n\n Bitmap bm = BitmapFactory.decodeFile(url, options);\n\n float scaleWidth = bm.getWidth() / ((float) width);\n float scaleHeight = bm.getHeight() / ((float) height);\n\n if (scaleWidth > scaleHeight) bm = Bitmap.createScaledBitmap(bm, (int)(bm.getWidth() / scaleHeight), (int)(bm.getHeight() / scaleHeight), true);\n else bm = Bitmap.createScaledBitmap(bm, (int)(bm.getWidth() / scaleWidth), (int)(bm.getHeight() / scaleWidth), true);\n\n bm = Bitmap.createBitmap(bm, (bm.getWidth() - width) / 2, (bm.getHeight() - height) / 2, width, height);\n return bm;\n } catch (Exception e) {\n return null;\n }\n }\n\n public static final long GB = 1000 * 1000 * 1000;\n public static final long MB = 1000 * 1000;\n public static final long KB = 1000;\n\n /**\n * Returns the input file size as a string in either KB, MB or GB\n * @param size (as bytes)\n * @return Size as readable string\n */\n public static String filesizeToString(long size) {\n if ((size / GB) >= 1) return substring(String.valueOf(((double) size / (double) GB)), 4) + \" GB\"; // GB\n else if ((size / MB) >= 1) return (size / MB) + \" MB\"; // MB\n else return (size / KB) + \" KB\"; // KB\n }\n\n /**\n * Returns a string with a length trimmed to the specified max length\n * @param s\n * @param maxLength\n * @return String with a length of the specified max length\n */\n public static String substring(String s, int maxLength) {\n if (s.length() >= maxLength) return s.substring(0, maxLength);\n else return s;\n }\n\n /**\n * Add a padding with a height of the ActionBar to the top of a given View\n * @param c\n * @param v\n */\n public static void addActionBarPadding(Context c, View v) {\n int mActionBarHeight = 0;\n TypedValue tv = new TypedValue();\n if (c.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true))\n mActionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, c.getResources().getDisplayMetrics());\n else\n mActionBarHeight = 0; // No ActionBar style (pre-Honeycomb or ActionBar not in theme)\n\n v.setPadding(0, mActionBarHeight, 0, 0);\n }\n\n /**\n * Add a padding with a combined height of the ActionBar and Status bar to the top of a given View\n * @param c\n * @param v\n */\n public static void addActionBarAndStatusBarPadding(Context c, View v) {\n int mActionBarHeight = 0, mStatusBarHeight = 0;\n TypedValue tv = new TypedValue();\n if (c.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true))\n mActionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, c.getResources().getDisplayMetrics());\n else\n mActionBarHeight = 0; // No ActionBar style (pre-Honeycomb or ActionBar not in theme)\n\n if (hasKitKat())\n mStatusBarHeight = convertDpToPixels(c, 25);\n\n v.setPadding(0, mActionBarHeight + mStatusBarHeight, 0, 0);\n }\n\n /**\n * Add a padding with a height of the ActionBar to the bottom of a given View\n * @param c\n * @param v\n */\n public static void addActionBarPaddingBottom(Context c, View v) {\n int mActionBarHeight = 0;\n TypedValue tv = new TypedValue();\n if (c.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true))\n mActionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, c.getResources().getDisplayMetrics());\n else\n mActionBarHeight = 0; // No ActionBar style (pre-Honeycomb or ActionBar not in theme)\n\n v.setPadding(0, 0, 0, mActionBarHeight);\n }\n\n /**\n * Add a margin with a height of the ActionBar to the top of a given View contained in a FrameLayout\n * @param c\n * @param v\n */\n public static void addActionBarMargin(Context c, View v) {\n int mActionBarHeight = 0;\n TypedValue tv = new TypedValue();\n if (c.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true))\n mActionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, c.getResources().getDisplayMetrics());\n else\n mActionBarHeight = 0; // No ActionBar style (pre-Honeycomb or ActionBar not in theme)\n\n FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);\n params.setMargins(0, mActionBarHeight, 0, 0);\n v.setLayoutParams(params);\n }\n\n /**\n * Add a margin with a combined height of the ActionBar and Status bar to the top of a given View contained in a FrameLayout\n * @param c\n * @param v\n */\n public static void addActionBarAndStatusBarMargin(Context c, View v) {\n int mActionBarHeight = 0, mStatusBarHeight = 0;\n TypedValue tv = new TypedValue();\n if (c.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true))\n mActionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, c.getResources().getDisplayMetrics());\n else\n mActionBarHeight = 0; // No ActionBar style (pre-Honeycomb or ActionBar not in theme)\n\n if (hasKitKat())\n mStatusBarHeight = convertDpToPixels(c, 25);\n\n FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);\n params.setMargins(0, mActionBarHeight + mStatusBarHeight, 0, 0);\n\n v.setLayoutParams(params);\n }\n\n /**\n * Add a margin with a combined height of the ActionBar and Status bar to the top of a given View contained in a FrameLayout\n * @param c\n * @param v\n */\n public static void addActionBarAndStatusBarMargin(Context c, View v, FrameLayout.LayoutParams layoutParams) {\n int mActionBarHeight = 0, mStatusBarHeight = 0;\n TypedValue tv = new TypedValue();\n if (c.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true))\n mActionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, c.getResources().getDisplayMetrics());\n else\n mActionBarHeight = 0; // No ActionBar style (pre-Honeycomb or ActionBar not in theme)\n\n if (hasKitKat())\n mStatusBarHeight = convertDpToPixels(c, 25);\n\n FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);\n params.setMargins(0, mActionBarHeight + mStatusBarHeight, 0, 0);\n params.gravity = layoutParams.gravity;\n v.setLayoutParams(params);\n }\n\n /**\n * Add a margin with a height of the ActionBar to the top of a given View contained in a FrameLayout\n * @param c\n * @param v\n */\n public static void addActionBarMarginBottom(Context c, View v) {\n int mActionBarHeight = 0;\n TypedValue tv = new TypedValue();\n if (c.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true))\n mActionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, c.getResources().getDisplayMetrics());\n else\n mActionBarHeight = 0; // No ActionBar style (pre-Honeycomb or ActionBar not in theme)\n\n FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);\n params.setMargins(0, 0, 0, mActionBarHeight);\n v.setLayoutParams(params);\n }\n\n public static void addNavigationBarPadding(Context c, View v) {\n v.setPadding(0, 0, 0, getNavigationBarHeight(c));\n }\n\n public static void addNavigationBarMargin(Context c, View v) {\n FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);\n params.setMargins(0, 0, 0, getNavigationBarHeight(c));\n v.setLayoutParams(params);\n }\n\n public static boolean hasICSMR1() {\n return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1;\n }\n\n public static boolean hasJellyBean() {\n return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;\n }\n\n public static boolean hasJellyBeanMR1() {\n return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1;\n }\n\n public static boolean hasJellyBeanMR2() {\n return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2;\n }\n\n public static boolean hasKitKat() {\n return Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;\n }\n\n public static boolean isKitKat() {\n return Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT;\n }\n\n public static boolean hasLollipop() {\n return Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP;\n }\n\n public static int getThumbnailNotificationSize(Context c) {\n Resources r = c.getResources();\n return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 64, r.getDisplayMetrics());\n }\n\n public static int getLargeNotificationWidth(Context c) {\n Resources r = c.getResources();\n return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 360, r.getDisplayMetrics());\n }\n\n public static int convertDpToPixels(Context c, int dp) {\n Resources r = c.getResources();\n return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics());\n }\n\n public static int getActionBarHeight(Context c) {\n int actionBarHeight = 0;\n TypedValue tv = new TypedValue();\n if (c.getTheme().resolveAttribute(R.attr.actionBarSize, tv, true))\n actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, c.getResources().getDisplayMetrics());\n else\n actionBarHeight = 0; // No ActionBar style (pre-Honeycomb or ActionBar not in theme)\n\n return actionBarHeight;\n }\n\n public static int getActionBarAndStatusBarHeight(Context c) {\n int actionBarHeight = getActionBarHeight(c);\n int statusBarHeight = ViewUtils.getStatusBarHeight(c);\n\n // We're only interested in returning the combined\n // height, if we're running on KitKat or above\n return hasKitKat() ?\n actionBarHeight + statusBarHeight : actionBarHeight;\n }\n\n public static String md5(final String s) {\n try {\n // Create MD5 Hash\n MessageDigest digest = java.security.MessageDigest\n .getInstance(\"MD5\");\n digest.update(s.getBytes());\n byte messageDigest[] = digest.digest();\n\n // Create Hex String\n StringBuffer hexString = new StringBuffer();\n for (int i = 0; i < messageDigest.length; i++) {\n String h = Integer.toHexString(0xFF & messageDigest[i]);\n while (h.length() < 2)\n h = \"0\" + h;\n hexString.append(h);\n }\n return hexString.toString();\n\n } catch (NoSuchAlgorithmException e) {\n e.printStackTrace();\n }\n return \"\";\n }\n\n public static int getThumbnailSize(Context c) {\n final int mImageThumbSize = c.getResources().getDimensionPixelSize(R.dimen.image_thumbnail_size);\n final int mImageThumbSpacing = c.getResources().getDimensionPixelSize(R.dimen.image_thumbnail_spacing);\n\n WindowManager window = (WindowManager) c.getSystemService(Context.WINDOW_SERVICE);\n Display d = window.getDefaultDisplay();\n\n Point size = new Point();\n d.getSize(size);\n\n final int numColumns = (int) Math.floor(Math.max(size.x, size.y) / (mImageThumbSize + mImageThumbSpacing));\n\n if (numColumns > 0) {\n final int columnWidth = (Math.max(size.x, size.y) / numColumns) - mImageThumbSpacing;\n\n if (columnWidth > 320)\n return 440;\n else if (columnWidth > 240)\n return 320;\n else if (columnWidth > 180)\n return 240;\n }\n\n return 180;\n }\n\n public static void resizeBitmapFileToCoverSize(Context c, String filepath) {\n\n final int mImageThumbSize = c.getResources().getDimensionPixelSize(R.dimen.image_thumbnail_size);\n final int mImageThumbSpacing = c.getResources().getDimensionPixelSize(R.dimen.image_thumbnail_spacing);\n\n WindowManager window = (WindowManager) c.getSystemService(Context.WINDOW_SERVICE);\n Display d = window.getDefaultDisplay();\n\n Point size = new Point();\n d.getSize(size);\n\n final int numColumns = (int) Math.floor(Math.max(size.x, size.y) / (mImageThumbSize + mImageThumbSpacing));\n\n if (numColumns > 0) {\n final int columnWidth = (Math.max(size.x, size.y) / numColumns) - mImageThumbSpacing;\n\n int imageWidth = 0;\n\n if (columnWidth > 300)\n imageWidth = 500;\n else if (columnWidth > 240)\n imageWidth = 320;\n else if (columnWidth > 180)\n imageWidth = 240;\n else\n imageWidth = 180;\n\n if (new File(filepath).exists())\n try {\n Bitmap bm = decodeSampledBitmapFromFile(filepath, imageWidth, (int) (imageWidth * 1.5));\n bm = Bitmap.createScaledBitmap(bm, imageWidth, (int) (imageWidth * 1.5), true);\n FileOutputStream out = new FileOutputStream(filepath);\n bm.compress(Bitmap.CompressFormat.JPEG, 90, out);\n out.close();\n bm.recycle();\n } catch (Exception e) {}\n }\n }\n\n public static String getImageUrlSize(Context c) {\n final int mImageThumbSize = c.getResources().getDimensionPixelSize(R.dimen.image_thumbnail_size);\n final int mImageThumbSpacing = c.getResources().getDimensionPixelSize(R.dimen.image_thumbnail_spacing);\n\n WindowManager window = (WindowManager) c.getSystemService(Context.WINDOW_SERVICE);\n Display d = window.getDefaultDisplay();\n\n Point size = new Point();\n d.getSize(size);\n\n final int numColumns = (int) Math.floor(Math.max(size.x, size.y) / (mImageThumbSize + mImageThumbSpacing));\n\n if (numColumns > 0) {\n final int columnWidth = (Math.max(size.x, size.y) / numColumns) - mImageThumbSpacing;\n\n if (columnWidth > 300)\n return \"w500\";\n else if (columnWidth > 185)\n return \"w300\";\n }\n\n return \"w185\";\n }\n\n public static String getBackdropUrlSize(Context c) {\n WindowManager window = (WindowManager) c.getSystemService(Context.WINDOW_SERVICE);\n Display d = window.getDefaultDisplay();\n\n Point size = new Point();\n d.getSize(size);\n\n final int width = Math.max(size.x, size.y);\n\n if (width > 1280 && isTablet(c)) // We only want to download full size images on tablets, as these are the only devices where you can see the difference\n return \"original\";\n else if (width > 780)\n return \"w1280\";\n return \"w780\";\n }\n\n public static String getBackdropThumbUrlSize(Context c) {\n WindowManager window = (WindowManager) c.getSystemService(Context.WINDOW_SERVICE);\n Display d = window.getDefaultDisplay();\n\n Point size = new Point();\n d.getSize(size);\n\n final int width = Math.min(size.x, size.y);\n\n if (width >= 780)\n return \"w780\";\n if (width >= 400)\n return \"w500\";\n return \"w300\";\n }\n\n public static String getActorUrlSize(Context c) {\n final int mImageThumbSize = c.getResources().getDimensionPixelSize(R.dimen.image_thumbnail_size);\n final int mImageThumbSpacing = c.getResources().getDimensionPixelSize(R.dimen.image_thumbnail_spacing);\n\n WindowManager window = (WindowManager) c.getSystemService(Context.WINDOW_SERVICE);\n Display d = window.getDefaultDisplay();\n\n Point size = new Point();\n d.getSize(size);\n\n final int numColumns = (int) Math.floor(Math.max(size.x, size.y) / (mImageThumbSize + mImageThumbSpacing));\n\n if (numColumns > 0) {\n final int columnWidth = (Math.max(size.x, size.y) / numColumns) - mImageThumbSpacing;\n\n if (columnWidth > 400)\n return \"h632\";\n\n if (columnWidth >= 300)\n return \"w300\";\n }\n\n return \"w185\";\n }\n\n public static boolean checkFileTypes(String file) {\n // We don't want to include files that start with ._ or .DS_Store\n if (file.matches(\"(?i).*[/][\\\\.](?:_|DS_Store).*[\\\\.].*$\"))\n return false;\n\n if (file.contains(\".\")) { // Must have a file type\n String type = file.substring(file.lastIndexOf(\".\"));\n String[] filetypes = allFileTypes.split(\"\\\\.\");\n int count = filetypes.length;\n for (int i = 0; i < count; i++)\n if (type.toLowerCase(Locale.ENGLISH).equals(\".\" + filetypes[i]))\n return true;\n }\n return false;\n }\n\n public static String removeExtension(String filepath) {\n final int lastPeriodPos = filepath.lastIndexOf('.');\n if (lastPeriodPos <= 0) {\n return filepath;\n } else {\n // Remove the last period and everything after it\n return filepath.substring(0, lastPeriodPos);\n }\n }\n\n public static String convertToGenericNfo(String filepath) {\n final int lastPeriodPos = filepath.lastIndexOf('/');\n if (lastPeriodPos <= 0) {\n return filepath;\n } else {\n // Remove the last period and everything after it\n return filepath.substring(0, lastPeriodPos) + \"/movie.nfo\";\n }\n }\n\n /**\n * Returns a blurred bitmap. It uses a RenderScript to blur the bitmap very fast.\n * @param context\n * @param originalBitmap\n * @param radius\n * @return\n */\n public static Bitmap fastBlur(Context context, Bitmap originalBitmap, int radius) {\n final RenderScript rs = RenderScript.create(context);\n\n final Allocation input = Allocation.createFromBitmap(rs, originalBitmap);\n final Allocation output = Allocation.createTyped(rs, input.getType());\n final ScriptIntrinsicBlur script = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));\n script.setRadius(radius);\n script.setInput(input);\n script.forEach(output);\n output.copyTo(originalBitmap);\n\n return originalBitmap;\n }\n\n public static boolean downloadFile(String url, String savePath) {\n if (TextUtils.isEmpty(url))\n return false;\n\n InputStream in = null;\n OutputStream fileos = null;\n\n try {\n int bufferSize = 8192;\n byte[] retVal = null;\n\n Request request = new Request.Builder()\n .url(url)\n .build();\n\n Response response = MizuuApplication.getOkHttpClient().newCall(request).execute();\n if (!response.isSuccessful())\n return false;\n\n fileos = new BufferedOutputStream(new FileOutputStream(savePath));\n in = new BufferedInputStream(response.body().byteStream(), bufferSize);\n\n retVal = new byte[bufferSize];\n int length = 0;\n while((length = in.read(retVal)) > -1) {\n fileos.write(retVal, 0, length);\n }\n } catch(Exception e) {\n // The download failed, so let's delete whatever was downloaded\n deleteFile(new File(savePath));\n\n return false;\n } finally {\n if (fileos != null) {\n try {\n fileos.flush();\n fileos.close();\n } catch (IOException e) {}\n }\n\n if (in != null) {\n try {\n in.close();\n } catch (IOException e) {}\n }\n }\n\n return true;\n }\n\n public static JSONObject getJSONObject(Context context, String url) {\n final OkHttpClient client = MizuuApplication.getOkHttpClient();\n\n Request request = new Request.Builder()\n .url(url)\n .get()\n .build();\n\n try {\n Response response = client.newCall(request).execute();\n\n if (response.code() >= 429) {\n // HTTP error 429 and above means that we've exceeded the query limit\n // for TMDb. Sleep for 5 seconds and try again.\n Thread.sleep(5000);\n response = client.newCall(request).execute();\n }\n return new JSONObject(response.body().string());\n } catch (Exception e) { // IOException and JSONException\n return new JSONObject();\n }\n }\n\n public static String getStringFromJSONObject(JSONObject json, String name, String fallback) {\n try {\n String s = json.getString(name);\n if (s.equals(\"null\"))\n return fallback;\n return s;\n } catch (Exception e) {\n return fallback;\n }\n }\n\n public static int getInteger(String number) {\n try {\n return Integer.valueOf(number);\n } catch (NumberFormatException nfe) {\n return 0;\n }\n }\n\n public static int getInteger(double number) {\n try {\n return (int) number;\n } catch (Exception e) {\n return 0;\n }\n }\n\n public static String removeIndexZero(String s) {\n if (!TextUtils.isEmpty(s))\n try {\n return String.valueOf(Integer.parseInt(s));\n } catch (NumberFormatException e) {}\n return s;\n }\n\n public static String addIndexZero(String s) {\n if (TextUtils.isEmpty(s))\n return \"00\";\n try {\n return String.format(Locale.ENGLISH, \"%02d\", Integer.parseInt(s));\n } catch (NumberFormatException e) {\n return \"00\";\n }\n }\n\n public static String addIndexZero(int number) {\n try {\n return String.format(Locale.ENGLISH, \"%02d\", number);\n } catch (Exception e) {\n return \"00\";\n }\n }\n\n public static String URLEncodeUTF8(String s) {\n return Uri.parse(s).toString();\n }\n\n public static final int TYPE_MOVIE = 0, TYPE_SHOWS = 1;\n\n public static ArrayList<FileSource> getFileSources(int type, boolean onlyNetworkSources) {\n\n ArrayList<FileSource> filesources = new ArrayList<FileSource>();\n DbAdapterSources dbHelperSources = MizuuApplication.getSourcesAdapter();\n\n Cursor c = null;\n if (type == TYPE_MOVIE)\n c = dbHelperSources.fetchAllMovieSources();\n else\n c = dbHelperSources.fetchAllShowSources();\n\n ColumnIndexCache cache = new ColumnIndexCache();\n\n try {\n while (c.moveToNext()) {\n if (onlyNetworkSources) {\n if (c.getInt(cache.getColumnIndex(c, DbAdapterSources.KEY_FILESOURCE_TYPE)) == FileSource.SMB) {\n filesources.add(new FileSource(\n c.getLong(cache.getColumnIndex(c, DbAdapterSources.KEY_ROWID)),\n c.getString(cache.getColumnIndex(c, DbAdapterSources.KEY_FILEPATH)),\n c.getInt(cache.getColumnIndex(c, DbAdapterSources.KEY_FILESOURCE_TYPE)),\n c.getString(cache.getColumnIndex(c, DbAdapterSources.KEY_USER)),\n c.getString(cache.getColumnIndex(c, DbAdapterSources.KEY_PASSWORD)),\n c.getString(cache.getColumnIndex(c, DbAdapterSources.KEY_DOMAIN)),\n c.getString(cache.getColumnIndex(c, DbAdapterSources.KEY_TYPE))\n ));\n }\n } else {\n filesources.add(new FileSource(\n c.getLong(cache.getColumnIndex(c, DbAdapterSources.KEY_ROWID)),\n c.getString(cache.getColumnIndex(c, DbAdapterSources.KEY_FILEPATH)),\n c.getInt(cache.getColumnIndex(c, DbAdapterSources.KEY_FILESOURCE_TYPE)),\n c.getString(cache.getColumnIndex(c, DbAdapterSources.KEY_USER)),\n c.getString(cache.getColumnIndex(c, DbAdapterSources.KEY_PASSWORD)),\n c.getString(cache.getColumnIndex(c, DbAdapterSources.KEY_DOMAIN)),\n c.getString(cache.getColumnIndex(c, DbAdapterSources.KEY_TYPE))\n ));\n }\n }\n } catch (Exception e) {\n } finally {\n c.close();\n cache.clear();\n }\n\n return filesources;\n }\n\n public static SmbLogin getLoginFromFilesource(FileSource source) {\n if (source == null ||\n TextUtils.isEmpty(source.getDomain()) &&\n TextUtils.isEmpty(source.getUser()) &&\n TextUtils.isEmpty(source.getPassword())) {\n return new SmbLogin();\n } else {\n return new SmbLogin(source.getDomain(), source.getUser(), source.getPassword());\n }\n }\n\n public static SmbLogin getLoginFromFilepath(int type, String filepath) {\n\n ArrayList<FileSource> filesources = MizLib.getFileSources(type, true);\n FileSource source = null;\n\n for (int i = 0; i < filesources.size(); i++) {\n if (filepath.contains(filesources.get(i).getFilepath())) {\n source = filesources.get(i);\n break;\n }\n }\n\n return getLoginFromFilesource(source);\n }\n\n public static int COVER = 1, BACKDROP = 2;\n public static SmbFile getCustomCoverArt(String filepath, SmbLogin auth, int type) throws MalformedURLException, UnsupportedEncodingException, SmbException {\n String parentPath = filepath.substring(0, filepath.lastIndexOf(\"/\"));\n if (!parentPath.endsWith(\"/\"))\n parentPath += \"/\";\n\n String filename = filepath.substring(0, filepath.lastIndexOf(\".\")).replaceAll(\"part[1-9]|cd[1-9]\", \"\").trim();\n\n String[] list = MizuuApplication.getCifsFilesList(parentPath);\n\n if (list == null) {\n SmbFile s = new SmbFile(createSmbLoginString(\n auth.getDomain(),\n auth.getUsername(),\n auth.getPassword(),\n parentPath,\n false));\n\n try {\n list = s.list();\n\n MizuuApplication.putCifsFilesList(parentPath, list);\n } catch (Exception e) {\n return null;\n }\n }\n\n String name = \"\", absolutePath = \"\", customCoverArt = \"\";\n\n if (type == COVER) {\n for (int i = 0; i < list.length; i++) {\n name = list[i];\n absolutePath = parentPath + list[i];\n if (name.equalsIgnoreCase(\"poster.jpg\") ||\n name.equalsIgnoreCase(\"poster.jpeg\") ||\n name.equalsIgnoreCase(\"poster.tbn\") ||\n name.equalsIgnoreCase(\"folder.jpg\") ||\n name.equalsIgnoreCase(\"folder.jpeg\") ||\n name.equalsIgnoreCase(\"folder.tbn\") ||\n name.equalsIgnoreCase(\"cover.jpg\") ||\n name.equalsIgnoreCase(\"cover.jpeg\") ||\n name.equalsIgnoreCase(\"cover.tbn\") ||\n absolutePath.equalsIgnoreCase(filename + \"-poster.jpg\") ||\n absolutePath.equalsIgnoreCase(filename + \"-poster.jpeg\") ||\n absolutePath.equalsIgnoreCase(filename + \"-poster.tbn\") ||\n absolutePath.equalsIgnoreCase(filename + \"-folder.jpg\") ||\n absolutePath.equalsIgnoreCase(filename + \"-folder.jpeg\") ||\n absolutePath.equalsIgnoreCase(filename + \"-folder.tbn\") ||\n absolutePath.equalsIgnoreCase(filename + \"-cover.jpg\") ||\n absolutePath.equalsIgnoreCase(filename + \"-cover.jpeg\") ||\n absolutePath.equalsIgnoreCase(filename + \"-cover.tbn\") ||\n absolutePath.equalsIgnoreCase(filename + \".jpg\") ||\n absolutePath.equalsIgnoreCase(filename + \".jpeg\") ||\n absolutePath.equalsIgnoreCase(filename + \".tbn\")) {\n customCoverArt = absolutePath;\n break;\n }\n }\n } else {\n for (int i = 0; i < list.length; i++) {\n name = list[i];\n absolutePath = parentPath + list[i];\n if (name.equalsIgnoreCase(\"fanart.jpg\") ||\n name.equalsIgnoreCase(\"fanart.jpeg\") ||\n name.equalsIgnoreCase(\"fanart.tbn\") ||\n name.equalsIgnoreCase(\"banner.jpg\") ||\n name.equalsIgnoreCase(\"banner.jpeg\") ||\n name.equalsIgnoreCase(\"banner.tbn\") ||\n name.equalsIgnoreCase(\"backdrop.jpg\") ||\n name.equalsIgnoreCase(\"backdrop.jpeg\") ||\n name.equalsIgnoreCase(\"backdrop.tbn\") ||\n absolutePath.equalsIgnoreCase(filename + \"-fanart.jpg\") ||\n absolutePath.equalsIgnoreCase(filename + \"-fanart.jpeg\") ||\n absolutePath.equalsIgnoreCase(filename + \"-fanart.tbn\") ||\n absolutePath.equalsIgnoreCase(filename + \"-banner.jpg\") ||\n absolutePath.equalsIgnoreCase(filename + \"-banner.jpeg\") ||\n absolutePath.equalsIgnoreCase(filename + \"-banner.tbn\") ||\n absolutePath.equalsIgnoreCase(filename + \"-backdrop.jpg\") ||\n absolutePath.equalsIgnoreCase(filename + \"-backdrop.jpeg\") ||\n absolutePath.equalsIgnoreCase(filename + \"-backdrop.tbn\")) {\n customCoverArt = absolutePath;\n break;\n }\n }\n }\n\n if (!TextUtils.isEmpty(customCoverArt))\n return new SmbFile(createSmbLoginString(\n auth.getDomain(),\n auth.getUsername(),\n auth.getPassword(),\n customCoverArt,\n false));\n\n return null;\n }\n\n public static String[] subtitleFormats = new String[]{\".srt\", \".sub\", \".ssa\", \".ssf\", \".smi\", \".txt\", \".usf\", \".ass\", \".stp\", \".idx\", \".aqt\", \".cvd\", \".dks\", \".jss\", \".mpl\", \".pjs\", \".psb\", \".rt\", \".svcd\", \".usf\"};\n\n public static boolean isSubtitleFile(String s) {\n int count = subtitleFormats.length;\n for (int i = 0; i < count; i++)\n if (s.endsWith(subtitleFormats[i]))\n return true;\n return false;\n }\n\n public static List<SmbFile> getSubtitleFiles(String filepath, SmbLogin auth) throws MalformedURLException, UnsupportedEncodingException {\n ArrayList<SmbFile> subs = new ArrayList<SmbFile>();\n\n String fileType = \"\";\n if (filepath.contains(\".\")) {\n fileType = filepath.substring(filepath.lastIndexOf(\".\"));\n }\n\n int count = subtitleFormats.length;\n for (int i = 0; i < count; i++) {\n subs.add(new SmbFile(createSmbLoginString(\n auth.getDomain(),\n auth.getUsername(),\n auth.getPassword(),\n filepath.replace(fileType, subtitleFormats[i]),\n false)));\n }\n\n return subs;\n }\n\n /**\n * A bit of a hack to properly delete files / folders from the OS\n * @param f\n * @return\n */\n public static boolean deleteFile(File f) {\n return f.delete();\n }\n\n public static String createSmbLoginString(String domain, String user, String password, String server, boolean isFolder) {\n // Create the string to fit the following syntax: smb://[[[domain;]username[:password]@]server[:port]/\n StringBuilder sb = new StringBuilder(\"smb://\");\n\n try {\n user = URLEncoder.encode(user, \"utf-8\");\n } catch (UnsupportedEncodingException e) {}\n try {\n password = URLEncoder.encode(password, \"utf-8\");\n } catch (UnsupportedEncodingException e) {}\n try {\n domain = URLEncoder.encode(domain, \"utf-8\");\n } catch (UnsupportedEncodingException e) {}\n\n user = user.replace(\"+\", \"%20\");\n password = password.replace(\"+\", \"%20\");\n domain = domain.replace(\"+\", \"%20\");\n server = server.replace(\"smb://\", \"\");\n\n // Only add domain, username and password details if the username isn't empty\n if (!TextUtils.isEmpty(user)) {\n // Add the domain details\n if (!TextUtils.isEmpty(domain))\n sb.append(domain).append(\";\");\n\n // Add username\n sb.append(user);\n\n // Add password\n if (!TextUtils.isEmpty(password))\n sb.append(\":\").append(password);\n\n sb.append(\"@\");\n }\n\n sb.append(server);\n\n if (isFolder)\n if (!server.endsWith(\"/\"))\n sb.append(\"/\");\n\n return sb.toString();\n }\n\n public static void deleteShow(Context c, TvShow thisShow, boolean showToast) {\n // Create and open database\n DbAdapterTvShows dbHelper = MizuuApplication.getTvDbAdapter();\n boolean deleted = dbHelper.deleteShow(thisShow.getId());\n\n DbAdapterTvShowEpisodes db = MizuuApplication.getTvEpisodeDbAdapter();\n deleted = deleted && db.deleteAllEpisodes(thisShow.getId());\n\n if (deleted) {\n try {\n // Delete cover art image\n File coverArt = thisShow.getCoverPhoto();\n if (coverArt.exists() && coverArt.getAbsolutePath().contains(\"com.miz.mizuu\")) {\n MizLib.deleteFile(coverArt);\n }\n\n // Delete thumbnail image\n File thumbnail = thisShow.getThumbnail();\n if (thumbnail.exists() && thumbnail.getAbsolutePath().contains(\"com.miz.mizuu\")) {\n MizLib.deleteFile(thumbnail);\n }\n\n // Delete backdrop image\n File backdrop = new File(thisShow.getBackdrop());\n if (backdrop.exists() && backdrop.getAbsolutePath().contains(\"com.miz.mizuu\")) {\n MizLib.deleteFile(backdrop);\n }\n\n // Delete episode images\n File dataFolder = MizuuApplication.getTvShowEpisodeFolder(c);\n File[] listFiles = dataFolder.listFiles();\n if (listFiles != null) {\n int count = listFiles.length;\n for (int i = 0; i < count; i++)\n if (listFiles[i].getName().startsWith(thisShow.getId() + \"_S\"))\n MizLib.deleteFile(listFiles[i]);\n }\n } catch (NullPointerException e) {} // No file to delete\n } else {\n if (showToast)\n Toast.makeText(c, c.getString(R.string.failedToRemoveShow), Toast.LENGTH_SHORT).show();\n }\n }\n\n public static String getYouTubeId(String url) {\n String pattern = \"https?:\\\\/\\\\/(?:[0-9A-Z-]+\\\\.)?(?:youtu\\\\.be\\\\/|youtube\\\\.com\\\\S*[^\\\\w\\\\-\\\\s])([\\\\w\\\\-]{11})(?=[^\\\\w\\\\-]|$)(?![?=&+%\\\\w]*(?:['\\\"][^<>]*>|<\\\\/a>))[?=&+%\\\\w]*\";\n\n Pattern compiledPattern = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);\n Matcher matcher = compiledPattern.matcher(url);\n\n if (matcher.find(1))\n return getYTId(matcher.group(1));\n\n if (matcher.find(0))\n return getYTId(matcher.group(0));\n\n return url;\n }\n\n private static String getYTId(String url) {\n String result = url;\n\n if (result.contains(\"v=\")) {\n result = result.substring(result.indexOf(\"v=\") + 2);\n\n if (result.contains(\"&\")) {\n result = result.substring(0, result.indexOf(\"&\"));\n }\n }\n\n if (result.contains(\"youtu.be/\")) {\n result = result.substring(result.indexOf(\"youtu.be/\") + 9);\n\n if (result.contains(\"&\")) {\n result = result.substring(0, result.indexOf(\"&\"));\n }\n }\n\n return result;\n }\n\n private static String convertToHex(byte[] data) {\n StringBuilder buf = new StringBuilder();\n int count = data.length;\n for (int i = 0; i < count; i++) {\n int halfbyte = (data[i] >>> 4) & 0x0F;\n int two_halfs = 0;\n do {\n buf.append((0 <= halfbyte) && (halfbyte <= 9) ? (char) ('0' + halfbyte) : (char) ('a' + (halfbyte - 10)));\n halfbyte = data[i] & 0x0F;\n } while (two_halfs++ < 1);\n }\n return buf.toString();\n }\n\n public static String SHA1(String text) {\n try {\n MessageDigest md = MessageDigest.getInstance(\"SHA-1\");\n md.update(text.getBytes(\"iso-8859-1\"), 0, text.length());\n byte[] sha1hash = md.digest();\n return convertToHex(sha1hash);\n } catch (Exception e) {\n return \"\";\n }\n }\n\n public static Request getJsonPostRequest(String url, JSONObject holder) {\n return new Request.Builder()\n .url(url)\n .addHeader(\"Content-type\", \"application/json\")\n .post(RequestBody.create(MediaType.parse(\"application/json\"), holder.toString()))\n .build();\n }\n\n public static Request getTraktAuthenticationRequest(String url, String username, String password) throws JSONException {\n JSONObject holder = new JSONObject();\n holder.put(\"username\", username);\n holder.put(\"password\", password);\n\n return new Request.Builder()\n .url(url)\n .addHeader(\"Content-type\", \"application/json\")\n .post(RequestBody.create(MediaType.parse(\"application/json\"), holder.toString()))\n .build();\n }\n\n public static boolean isMovieLibraryBeingUpdated(Context c) {\n ActivityManager manager = (ActivityManager) c.getSystemService(Context.ACTIVITY_SERVICE);\n List<RunningServiceInfo> services = manager.getRunningServices(Integer.MAX_VALUE);\n int count = services.size();\n for (int i = 0; i < count; i++) {\n if (MovieLibraryUpdate.class.getName().equals(services.get(i).service.getClassName())) {\n return true;\n }\n }\n return false;\n }\n\n public static boolean isTvShowLibraryBeingUpdated(Context c) {\n ActivityManager manager = (ActivityManager) c.getSystemService(Context.ACTIVITY_SERVICE);\n List<RunningServiceInfo> services = manager.getRunningServices(Integer.MAX_VALUE);\n int count = services.size();\n for (int i = 0; i < count; i++) {\n if (TvShowsLibraryUpdate.class.getName().equals(services.get(i).service.getClassName())) {\n return true;\n }\n }\n return false;\n }\n\n public static final int HEIGHT = 100, WIDTH = 110;\n\n public static int getDisplaySize(Context c, int type) {\n WindowManager wm = (WindowManager) c.getSystemService(Context.WINDOW_SERVICE);\n Display display = wm.getDefaultDisplay();\n\n Point size = new Point();\n display.getSize(size);\n\n return type == HEIGHT ?\n size.y : size.x;\n }\n\n public static int getFileSizeLimit(Context c) {\n return 25 * 1024 * 1024; // 25 MB\n }\n\n public static String getTraktUserName(Context c) {\n SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(c);\n return settings.getString(TRAKT_USERNAME, \"\").trim();\n }\n\n public static String removeWikipediaNotes(String original) {\n original = original.trim().replaceAll(\"(?i)from wikipedia, the free encyclopedia.\", \"\").replaceAll(\"(?i)from wikipedia, the free encyclopedia\", \"\");\n original = original.replaceAll(\"(?m)^[ \\t]*\\r?\\n\", \"\");\n if (original.contains(\"Description above from the Wikipedia\")) {\n original = original.substring(0, original.lastIndexOf(\"Description above from the Wikipedia\"));\n }\n\n return original.trim();\n }\n\n public static String getParentFolder(String filepath) {\n try {\n return filepath.substring(0, filepath.lastIndexOf(\"/\"));\n } catch (Exception e) {\n return \"\";\n }\n }\n\n public static void scheduleMovieUpdate(Context context) {\n SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);\n\n // Check if scheduled updates are enabled, and schedule the next update if this is the case\n if (settings.getInt(SCHEDULED_UPDATES_MOVIE, ScheduledUpdatesFragment.NOT_ENABLED) > ScheduledUpdatesFragment.AT_LAUNCH) {\n ScheduledUpdatesAlarmManager.cancelUpdate(ScheduledUpdatesAlarmManager.MOVIES, context);\n long duration = MizLib.HOUR;\n switch (settings.getInt(SCHEDULED_UPDATES_MOVIE, ScheduledUpdatesFragment.NOT_ENABLED)) {\n case ScheduledUpdatesFragment.EVERY_2_HOURS:\n duration = MizLib.HOUR * 2;\n break;\n case ScheduledUpdatesFragment.EVERY_4_HOURS:\n duration = MizLib.HOUR * 4;\n break;\n case ScheduledUpdatesFragment.EVERY_6_HOURS:\n duration = MizLib.HOUR * 6;\n break;\n case ScheduledUpdatesFragment.EVERY_12_HOURS:\n duration = MizLib.HOUR * 12;\n break;\n case ScheduledUpdatesFragment.EVERY_DAY:\n duration = MizLib.DAY;\n break;\n case ScheduledUpdatesFragment.EVERY_WEEK:\n duration = MizLib.WEEK;\n break;\n }\n ScheduledUpdatesAlarmManager.startUpdate(ScheduledUpdatesAlarmManager.MOVIES, context, duration);\n }\n }\n\n public static void scheduleShowsUpdate(Context context) {\n SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);\n\n // Check if scheduled updates are enabled, and schedule the next update if this is the case\n if (settings.getInt(SCHEDULED_UPDATES_TVSHOWS, ScheduledUpdatesFragment.NOT_ENABLED) > ScheduledUpdatesFragment.AT_LAUNCH) {\n ScheduledUpdatesAlarmManager.cancelUpdate(ScheduledUpdatesAlarmManager.SHOWS, context);\n long duration = MizLib.HOUR;\n switch (settings.getInt(SCHEDULED_UPDATES_TVSHOWS, ScheduledUpdatesFragment.NOT_ENABLED)) {\n case ScheduledUpdatesFragment.EVERY_2_HOURS:\n duration = MizLib.HOUR * 2;\n break;\n case ScheduledUpdatesFragment.EVERY_4_HOURS:\n duration = MizLib.HOUR * 4;\n break;\n case ScheduledUpdatesFragment.EVERY_6_HOURS:\n duration = MizLib.HOUR * 6;\n break;\n case ScheduledUpdatesFragment.EVERY_12_HOURS:\n duration = MizLib.HOUR * 12;\n break;\n case ScheduledUpdatesFragment.EVERY_DAY:\n duration = MizLib.DAY;\n break;\n case ScheduledUpdatesFragment.EVERY_WEEK:\n duration = MizLib.WEEK;\n break;\n }\n ScheduledUpdatesAlarmManager.startUpdate(ScheduledUpdatesAlarmManager.SHOWS, context, duration);\n }\n }\n\n public static int countOccurrences(String haystack, char needle) {\n int count = 0;\n char[] array = haystack.toCharArray();\n for (int i = 0; i < array.length; i++) {\n if (array[i] == needle) {\n ++count;\n }\n }\n return count;\n }\n\n public static String decryptImdbId(String filename) {\n Pattern p = Pattern.compile(\"(tt\\\\d{7})\");\n Matcher m = p.matcher(filename);\n if (m.find())\n return m.group(1);\n return null;\n }\n\n public static String decryptName(String input, String customTags) {\n if (TextUtils.isEmpty(input))\n return \"\";\n\n String output = getNameFromFilename(input);\n output = fixAbbreviations(output);\n\n // Used to remove [SET {title}] from the beginning of filenames\n if (output.startsWith(\"[\") && output.contains(\"]\")) {\n String after = \"\";\n\n if (output.matches(\"(?i)^\\\\[SET .*\\\\].*?\")) {\n try {\n after = output.substring(output.indexOf(\"]\") + 1, output.length());\n } catch (Exception e) {}\n }\n\n if (!TextUtils.isEmpty(after))\n output = after;\n }\n\n output = output.replaceAll(WAREZ_PATTERN + \"|\\\\)|\\\\(|\\\\[|\\\\]|\\\\{|\\\\}|\\\\'|\\\\<|\\\\>|\\\\-\", \"\");\n\n // Improved support for French titles that start with C' or L'\n if (output.matches(\"(?i)^(c|l)(\\\\_|\\\\.)\\\\w.*?\")) {\n StringBuilder sb = new StringBuilder(output);\n sb.replace(1, 2, \"'\");\n output = sb.toString();\n }\n\n if (!TextUtils.isEmpty(customTags)) {\n String[] custom = customTags.split(\"<MiZ>\");\n int count = custom.length;\n for (int i = 0; i < count; i++)\n try {\n output = output.replaceAll(\"(?i)\" + custom[i], \"\");\n } catch (Exception e) {}\n }\n\n output = output.replaceAll(\"\\\\s\\\\-\\\\s|\\\\.|\\\\,|\\\\_\", \" \"); // Remove separators\n output = output.trim().replaceAll(\"(?i)(part)$\", \"\"); // Remove \"part\" in the end of the string\n output = output.trim().replaceAll(\"(?i)(?:s|season[ ._-]*)\\\\d{1,4}.*\", \"\"); // Remove \"season####\" in the end of the string\n\n return output.replaceAll(\" +\", \" \").trim(); // replaceAll() needed to remove all instances of multiple spaces\n }\n\n private final static String YEAR_PATTERN = \"(18|19|20)[0-9][0-9]\";\n private final static String WAREZ_PATTERN = \"(?i)(dvdscreener|dvdscreen|dvdscr|dvdrip|dvd5|dvd|xvid|divx|m\\\\-480p|m\\\\-576p|m\\\\-720p|m\\\\-864p|m\\\\-900p|m\\\\-1080p|m480p|m576p|m720p|m864p|m900p|m1080p|480p|576p|720p|864p|900p|1080p|1080i|720i|mhd|brrip|bdrip|brscreener|brscreen|brscr|aac|x264|bluray|dts|screener|hdtv|ac3|repack|2\\\\.1|5\\\\.1|ac3_6|7\\\\.1|h264|hdrip|ntsc|proper|readnfo|rerip|subbed|vcd|scvd|pdtv|sdtv|hqts|hdcam|multisubs|650mb|700mb|750mb|webdl|web-dl|bts|korrip|webrip|korsub|1link|sample|tvrip|tvr|extended.editions?|directors cut|tfe|unrated|\\\\(.*?torrent.*?\\\\)|\\\\[.*?\\\\]|\\\\(.*?\\\\)|\\\\{.*?\\\\}|part[0-9]|cd[0-9])\";\n private final static String ABBREVIATION_PATTERN = \"(?<=(^|[.])[\\\\S&&\\\\D])[.](?=[\\\\S&&\\\\D]([.]|$))\";\n\n public static String getNameFromFilename(String input) {\n int lastIndex = 0;\n\n Pattern searchPattern = Pattern.compile(YEAR_PATTERN);\n Matcher searchMatcher = searchPattern.matcher(input);\n\n while (searchMatcher.find())\n lastIndex = searchMatcher.end();\n\n if (lastIndex > 0)\n try {\n return input.substring(0, lastIndex - 4);\n } catch (Exception e) {}\n\n return input;\n }\n\n public static String fixAbbreviations(String input) {\n return input.replaceAll(ABBREVIATION_PATTERN, \"\");\n }\n\n public static String decryptYear(String input) {\n String result = \"\";\n Pattern searchPattern = Pattern.compile(YEAR_PATTERN);\n Matcher searchMatcher = searchPattern.matcher(input);\n\n while (searchMatcher.find()) {\n try {\n int lastIndex = searchMatcher.end();\n result = input.substring(lastIndex - 4, lastIndex);\n } catch (Exception e) {}\n }\n\n return result;\n }\n\n /**\n * Decode and sample down a bitmap from a file to the requested width and height.\n *\n * @param filename The full path of the file to decode\n * @param reqWidth The requested width of the resulting bitmap\n * @param reqHeight The requested height of the resulting bitmap\n * @return A bitmap sampled down from the original with the same aspect ratio and dimensions\n * that are equal to or greater than the requested width and height\n */\n public static Bitmap decodeSampledBitmapFromFile(String filename,\n int reqWidth, int reqHeight) {\n\n // First decode with inJustDecodeBounds=true to check dimensions\n final BitmapFactory.Options options = new BitmapFactory.Options();\n options.inJustDecodeBounds = true;\n BitmapFactory.decodeFile(filename, options);\n\n // Calculate inSampleSize\n options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);\n options.inMutable = true;\n options.inPreferredConfig = Config.RGB_565;\n\n // Decode bitmap with inSampleSize set\n options.inJustDecodeBounds = false;\n\n return BitmapFactory.decodeFile(filename, options);\n }\n\n /**\n * Decode and sample down a bitmap from resources to the requested width and height.\n *\n * @param res The resources object containing the image data\n * @param resId The resource id of the image data\n * @param reqWidth The requested width of the resulting bitmap\n * @param reqHeight The requested height of the resulting bitmap\n * @return A bitmap sampled down from the original with the same aspect ratio and dimensions\n * that are equal to or greater than the requested width and height\n */\n public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,\n int reqWidth, int reqHeight) {\n\n // First decode with inJustDecodeBounds=true to check dimensions\n final BitmapFactory.Options options = new BitmapFactory.Options();\n options.inJustDecodeBounds = true;\n BitmapFactory.decodeResource(res, resId, options);\n\n // Calculate inSampleSize\n options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);\n\n // Decode bitmap with inSampleSize set\n options.inJustDecodeBounds = false;\n return BitmapFactory.decodeResource(res, resId, options);\n }\n\n /**\n * Calculate an inSampleSize for use in a {@link BitmapFactory.Options} object when decoding\n * bitmaps using the decode* methods from {@link BitmapFactory}. This implementation calculates\n * the closest inSampleSize that will result in the final decoded bitmap having a width and\n * height equal to or larger than the requested width and height. This implementation does not\n * ensure a power of 2 is returned for inSampleSize which can be faster when decoding but\n * results in a larger bitmap which isn't as useful for caching purposes.\n *\n * @param options An options object with out* params already populated (run through a decode*\n * method with inJustDecodeBounds==true\n * @param reqWidth The requested width of the resulting bitmap\n * @param reqHeight The requested height of the resulting bitmap\n * @return The value to be used for inSampleSize\n */\n public static int calculateInSampleSize(BitmapFactory.Options options,\n int reqWidth, int reqHeight) {\n // Raw height and width of image\n final int height = options.outHeight;\n final int width = options.outWidth;\n int inSampleSize = 1;\n\n if (height > reqHeight || width > reqWidth) {\n\n // Calculate ratios of height and width to requested height and width\n final int heightRatio = Math.round((float) height / (float) reqHeight);\n final int widthRatio = Math.round((float) width / (float) reqWidth);\n\n // Choose the smallest ratio as inSampleSize value, this will guarantee a final image\n // with both dimensions larger than or equal to the requested height and width.\n inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;\n\n // This offers some additional logic in case the image has a strange\n // aspect ratio. For example, a panorama may have a much larger\n // width than height. In these cases the total pixels might still\n // end up being too large to fit comfortably in memory, so we should\n // be more aggressive with sample down the image (=larger inSampleSize).\n\n final float totalPixels = width * height;\n\n // Anything more than 2x the requested pixels we'll sample down further\n final float totalReqPixelsCap = reqWidth * reqHeight * 2;\n\n while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {\n inSampleSize++;\n }\n }\n return inSampleSize;\n }\n\n @SuppressWarnings(\"deprecation\")\n public static long getFreeMemory() {\n StatFs stat = new StatFs(Environment.getDataDirectory().getPath());\n if (hasJellyBeanMR2())\n return stat.getAvailableBlocksLong() * stat.getBlockSizeLong();\n else\n return stat.getAvailableBlocks() * stat.getBlockSize();\n }\n\n private static String[] MEDIA_APPS = new String[]{\"com.imdb.mobile\", \"com.google.android.youtube\", \"com.ted.android\", \"com.google.android.videos\", \"se.mtg.freetv.tv3_dk\", \"tv.twitch.android.viewer\",\n \"com.netflix.mediaclient\", \"com.gotv.crackle.handset\", \"net.flixster.android\", \"com.google.tv.alf\", \"com.viki.android\", \"com.mobitv.client.mobitv\", \"com.hulu.plus.jp\", \"com.hulu.plus\",\n \"com.mobitv.client.tv\", \"air.com.vudu.air.DownloaderTablet\", \"com.hbo.android.app\", \"com.HBO\", \"bbc.iplayer.android\", \"air.uk.co.bbc.android.mediaplayer\", \"com.rhythmnewmedia.tvdotcom\",\n \"com.cnettv.app\", \"com.xfinity.playnow\"};\n\n public static boolean isMediaApp(ApplicationInfo ai) {\n for (int i = 0; i < MEDIA_APPS.length; i++)\n if (MEDIA_APPS[i].equals(ai.packageName))\n return true;\n return false;\n }\n\n private static int mRuntimeInMinutes;\n public static String getRuntimeInMinutesOrHours(String runtime, String hour, String minute) {\n mRuntimeInMinutes = Integer.valueOf(runtime);\n if (mRuntimeInMinutes >= 60) {\n return (mRuntimeInMinutes / 60) + hour;\n }\n return mRuntimeInMinutes + minute;\n }\n\n public static int getPartNumberFromFilepath(String filepath) {\n if (filepath.matches(\".*part[1-9].*\"))\n filepath = filepath.substring(filepath.lastIndexOf(\"part\") + 4, filepath.length());\n else if (filepath.matches(\".*cd[1-9].*\"))\n filepath = filepath.substring(filepath.lastIndexOf(\"cd\") + 2, filepath.length());\n\n filepath = filepath.substring(0, 1);\n\n try {\n return Integer.valueOf(filepath);\n } catch (NumberFormatException nfe) { return 0; }\n }\n\n public static List<String> getSplitParts(String filepath, SmbLogin auth) throws MalformedURLException, UnsupportedEncodingException, SmbException {\n ArrayList<String> parts = new ArrayList<String>();\n\n String fileType = \"\";\n if (filepath.contains(\".\")) {\n fileType = filepath.substring(filepath.lastIndexOf(\".\"));\n }\n\n if (filepath.matches(\".*part[1-9].*\"))\n filepath = filepath.substring(0, filepath.lastIndexOf(\"part\") + 4);\n else if (filepath.matches(\".*cd[1-9].*\"))\n filepath = filepath.substring(0, filepath.lastIndexOf(\"cd\") + 2);\n\n if (auth == null) { // Check if it's a local file\n File temp;\n for (int i = 1; i < 10; i++) {\n temp = new File(filepath + i + fileType);\n if (temp.exists())\n parts.add(temp.getAbsolutePath());\n }\n } else { // It's a network file\n SmbFile temp;\n for (int i = 1; i < 10; i++) {\n temp = new SmbFile(createSmbLoginString(\n auth.getDomain(),\n auth.getUsername(),\n auth.getPassword(),\n filepath + i + fileType,\n false));\n if (temp.exists())\n parts.add(temp.getPath());\n }\n }\n\n return parts;\n }\n\n public static String transformSmbPath(String smbPath) {\n if (smbPath.contains(\"smb\") && smbPath.contains(\"@\"))\n return \"smb://\" + smbPath.substring(smbPath.indexOf(\"@\") + 1);\n return smbPath.replace(\"/smb:/\", \"smb://\");\n }\n\n public static int getNavigationBarHeight(Context context) {\n Resources resources = context.getResources();\n int resourceId = resources.getIdentifier(\"navigation_bar_height\", \"dimen\", \"android\");\n if (resourceId > 0) {\n return resources.getDimensionPixelSize(resourceId);\n }\n return 0;\n }\n\n public static int getNavigationBarWidth(Context context) {\n Resources resources = context.getResources();\n int resourceId = resources.getIdentifier(\"navigation_bar_width\", \"dimen\", \"android\");\n if (resourceId > 0) {\n return resources.getDimensionPixelSize(resourceId);\n }\n return 0;\n }\n\n public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int pixels) {\n Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap\n .getHeight(), Config.ARGB_8888);\n Canvas canvas = new Canvas(output);\n\n final int color = 0xff424242;\n final Paint paint = new Paint();\n final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());\n final RectF rectF = new RectF(rect);\n final float roundPx = pixels;\n\n paint.setAntiAlias(true);\n canvas.drawARGB(0, 0, 0, 0);\n paint.setColor(color);\n canvas.drawRoundRect(rectF, roundPx, roundPx, paint);\n\n paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));\n canvas.drawBitmap(bitmap, rect, rect, paint);\n\n return output;\n }\n\n public static File getRandomBackdropFile(Context c) {\n ArrayList<File> files = new ArrayList<File>();\n\n File[] f = MizuuApplication.getMovieBackdropFolder(c).listFiles();\n if (f != null)\n Collections.addAll(files, f);\n\n f = MizuuApplication.getTvShowBackdropFolder(c).listFiles();\n if (f != null)\n Collections.addAll(files, f);\n\n if (files.size() > 0) {\n Random rndm = new Random();\n return files.get(rndm.nextInt(files.size()));\n }\n\n return new File(\"\");\n }\n\n public static boolean isValidFilename(String name) {\n return !(name.startsWith(\".\") && MizLib.getCharacterCountInString(name, '.') == 1) && !name.startsWith(\"._\");\n }\n\n public static boolean exists(String URLName){\n try {\n HttpURLConnection.setFollowRedirects(false);\n HttpURLConnection con =\n (HttpURLConnection) new URL(URLName).openConnection();\n con.setRequestMethod(\"HEAD\");\n con.setConnectTimeout(10000);\n return (con.getResponseCode() == HttpURLConnection.HTTP_OK);\n }\n catch (Exception e) {\n return false;\n }\n }\n\n /**\n * Determines if the device uses navigation controls as the primary navigation from a number of factors.\n * @param context Application Context\n * @return True if the device uses navigation controls, false otherwise.\n */\n public static boolean usesNavigationControl(Context context) {\n Configuration configuration = context.getResources().getConfiguration();\n if (configuration.navigation == Configuration.NAVIGATION_NONAV) {\n return false;\n } else if (configuration.touchscreen == Configuration.TOUCHSCREEN_FINGER) {\n return false;\n } else if (configuration.navigation == Configuration.NAVIGATION_DPAD) {\n return true;\n } else if (configuration.touchscreen == Configuration.TOUCHSCREEN_NOTOUCH) {\n return true;\n } else if (configuration.touchscreen == Configuration.TOUCHSCREEN_UNDEFINED) {\n return true;\n } else if (configuration.navigationHidden == Configuration.NAVIGATIONHIDDEN_YES) {\n return true;\n } else if (configuration.uiMode == Configuration.UI_MODE_TYPE_TELEVISION) {\n return true;\n }\n return false;\n }\n\n public static int getFileSize(URL url) {\n HttpURLConnection conn = null;\n try {\n conn = (HttpURLConnection) url.openConnection();\n conn.setRequestMethod(\"HEAD\");\n conn.getInputStream();\n return conn.getContentLength();\n } catch (IOException e) {\n return -1;\n } finally {\n conn.disconnect();\n }\n }\n\n public static String getPrettyTime(Context context, int minutes) {\n if (minutes == 0)\n return context.getString(R.string.stringNA);;\n try {\n int hours = (minutes / 60);\n minutes = (minutes % 60);\n String hours_string = hours + \" \" + context.getResources().getQuantityString(R.plurals.hour, hours, hours);\n String minutes_string = minutes + \" \" + context.getResources().getQuantityString(R.plurals.minute, minutes, minutes);\n if (hours > 0) {\n if (minutes == 0)\n return hours_string;\n else\n return hours_string + \" \" + minutes_string;\n } else {\n return minutes_string;\n }\n } catch (Exception e) { // Fall back if something goes wrong\n if (minutes > 0)\n return String.valueOf(minutes);\n return context.getString(R.string.stringNA);\n }\n }\n\n public static String getPrettyRuntime(Context context, int minutes) {\n if (minutes == 0) {\n return context.getString(R.string.stringNA);\n }\n\n int hours = (minutes / 60);\n minutes = (minutes % 60);\n\n if (hours > 0) {\n if (minutes == 0) {\n return hours + \" \" + context.getResources().getQuantityString(R.plurals.hour, hours, hours);\n } else {\n return hours + \" \" + context.getResources().getQuantityString(R.plurals.hour_short, hours, hours) + \" \" + minutes + \" \" + context.getResources().getQuantityString(R.plurals.minute_short, minutes, minutes);\n }\n } else {\n return minutes + \" \" + context.getResources().getQuantityString(R.plurals.minute, minutes, minutes);\n }\n }\n\n public static String getPrettyDate(Context context, String date) {\n if (!TextUtils.isEmpty(date)) {\n try {\n String[] dateArray = date.split(\"-\");\n Calendar cal = Calendar.getInstance();\n cal.set(Integer.parseInt(dateArray[0]), Integer.parseInt(dateArray[1]) - 1, Integer.parseInt(dateArray[2]));\n\n return MizLib.toCapitalFirstChar(cal.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.getDefault()) + \" \" + cal.get(Calendar.YEAR));\n } catch (Exception e) { // Fall back if something goes wrong\n return date;\n }\n } else {\n return context.getString(R.string.stringNA);\n }\n }\n\n public static String getPrettyDatePrecise(Context context, String date) {\n if (!TextUtils.isEmpty(date)) {\n try {\n String[] dateArray = date.split(\"-\");\n Calendar cal = Calendar.getInstance();\n cal.set(Integer.parseInt(dateArray[0]), Integer.parseInt(dateArray[1]) - 1, Integer.parseInt(dateArray[2]));\n\n return DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.getDefault()).format(cal.getTime());\n } catch (Exception e) { // Fall back if something goes wrong\n return date;\n }\n } else {\n return context.getString(R.string.stringNA);\n }\n }\n\n public static String getPrettyDate(Context context, long millis) {\n if (millis > 0) {\n try {\n Calendar cal = Calendar.getInstance();\n cal.setTimeInMillis(millis);\n\n return DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.getDefault()).format(cal.getTime());\n } catch (Exception e) { // Fall back if something goes wrong\n return String.valueOf(millis);\n }\n } else {\n return context.getString(R.string.stringNA);\n }\n }\n\n public static Comparator<WebMovie> getWebMovieDateComparator() {\n return new Comparator<WebMovie>() {\n @Override\n public int compare(WebMovie o1, WebMovie o2) {\n // Dates are always presented as YYYY-MM-DD, so removing\n // the hyphens will easily provide a great way of sorting.\n\n int firstDate = 0, secondDate = 0;\n String first = \"\", second = \"\";\n\n if (o1.getRawDate() != null)\n first = o1.getRawDate().replace(\"-\", \"\");\n\n if (!TextUtils.isEmpty(first))\n firstDate = Integer.valueOf(first);\n\n if (o2.getRawDate() != null)\n second = o2.getRawDate().replace(\"-\", \"\");\n\n if (!TextUtils.isEmpty(second))\n secondDate = Integer.valueOf(second);\n\n // This part is reversed to get the highest numbers first\n if (firstDate < secondDate)\n return 1; // First date is lower than second date - put it second\n else if (firstDate > secondDate)\n return -1; // First date is greater than second date - put it first\n\n return 0; // They're equal\n }\n };\n }\n\n private static String[] mAdultKeywords = new String[]{\"adult\", \"sex\", \"porn\", \"explicit\", \"penis\", \"vagina\", \"asshole\",\n \"blowjob\", \"cock\", \"fuck\", \"dildo\", \"kamasutra\", \"masturbat\", \"squirt\", \"slutty\", \"cum\", \"cunt\"};\n\n public static boolean isAdultContent(Context context, String title) {\n // Check if the user has enabled adult content - if so, nothing should\n // be blocked and the method should return false regardless of the title\n if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean(INCLUDE_ADULT_CONTENT, false))\n return false;\n\n String lowerCase = title.toLowerCase(Locale.getDefault());\n\n // Run through the keywords and check\n for (int i = 0; i < mAdultKeywords.length; i++)\n if (lowerCase.contains(mAdultKeywords[i]))\n return true;\n\n // Certain titles include \"XXX\" (all caps), so test this against the normal-case title as a last check\n return title.contains(\"XXX\");\n }\n\n public static boolean isNumber(String runtime) {\n return TextUtils.isDigitsOnly(runtime);\n }\n\n public static boolean isValidTmdbId(String id) {\n return !TextUtils.isEmpty(id) && !id.equals(DbAdapterMovies.UNIDENTIFIED_ID) && isNumber(id);\n }\n\n /**\n * Helper method to remove a ViewTreeObserver correctly, i.e.\n * avoiding the deprecated method on API level 16+.\n * @param vto\n * @param victim\n */\n @SuppressWarnings(\"deprecation\")\n public static void removeViewTreeObserver(ViewTreeObserver vto, OnGlobalLayoutListener victim) {\n if (MizLib.hasJellyBean()) {\n vto.removeOnGlobalLayoutListener(victim);\n } else {\n vto.removeGlobalOnLayoutListener(victim);\n }\n }\n\n public static String getTmdbImageBaseUrl(Context context) {\n long time = PreferenceManager.getDefaultSharedPreferences(context).getLong(TMDB_BASE_URL_TIME, 0);\n long currentTime = System.currentTimeMillis();\n\n // We store the TMDb base URL for 24 hours\n if (((currentTime - time) < DAY && PreferenceManager.getDefaultSharedPreferences(context).contains(TMDB_BASE_URL)) |\n Looper.getMainLooper().getThread() == Thread.currentThread()) {\n return PreferenceManager.getDefaultSharedPreferences(context).getString(TMDB_BASE_URL, \"\");\n }\n\n try {\n JSONObject configuration = getJSONObject(context, \"https://api.themoviedb.org/3/configuration?api_key=\" + getTmdbApiKey(context));\n String baseUrl = configuration.getJSONObject(\"images\").getString(\"secure_base_url\");\n\n Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();\n editor.putString(TMDB_BASE_URL, baseUrl);\n editor.putLong(TMDB_BASE_URL_TIME, System.currentTimeMillis());\n editor.commit();\n\n return baseUrl;\n } catch (JSONException e) {\n return null;\n }\n }\n\n public static void showSelectFileDialog(Context context, ArrayList<Filepath> paths, final Dialog.OnClickListener listener) {\n String[] items = new String[paths.size()];\n for (int i = 0; i < paths.size(); i++)\n items[i] = paths.get(i).getFilepath();\n\n AlertDialog.Builder builder = new AlertDialog.Builder(context);\n builder.setTitle(context.getString(R.string.selectFile));\n builder.setItems(items, listener);\n builder.show();\n }\n\n public static String getFilenameWithoutExtension(String filename) {\n try {\n return filename.substring(0, filename.lastIndexOf(\".\"));\n } catch (IndexOutOfBoundsException e) {\n return filename;\n }\n }\n\n public static void copyDatabase(Context context) {\n try {\n FileUtils.copyFile(context.getDatabasePath(\"mizuu_data\"), new File(Environment.getExternalStorageDirectory(), \"mizuu_data.db\"));\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n}",
"public class MizuuApplication extends Application {\n\n\tprivate static DbAdapterTvShows sDbTvShow;\n\tprivate static DbAdapterTvShowEpisodes sDbTvShowEpisode;\n\tprivate static DbAdapterTvShowEpisodeMappings sDbTvShowEpisodeMappings;\n\tprivate static DbAdapterSources sDbSources;\n\tprivate static DbAdapterMovies sDbMovies;\n\tprivate static DbAdapterMovieMappings sDbMovieMapping;\n\tprivate static DbAdapterCollections sDbCollections;\n\tprivate static HashMap<String, String[]> sMap = new HashMap<String, String[]>();\n\tprivate static Picasso sPicasso;\n\tprivate static HashMap<String, Typeface> sTypefaces = new HashMap<String, Typeface>();\n\tprivate static HashMap<String, Palette> sPalettes = new HashMap<String, Palette>();\n\tprivate static Bus sBus;\n\tprivate static File sBaseAppFolder, sMovieThumbFolder, sMovieBackdropFolder, sTvShowThumbFolder, sTvShowBackdropFolder, sTvShowEpisodeFolder, sTvShowSeasonFolder, sAvailableOfflineFolder, sCacheFolder;\n\tprivate static Context mInstance;\n\tprivate static ArrayListMultimap<String, String> mMovieFilepaths;\n\tprivate static OkHttpClient mOkHttpClient;\n\n\t@Override\n\tpublic void onCreate() {\n\t\tsuper.onCreate();\n\n\t\tmInstance = this;\n\n\t\tjcifs.Config.setProperty(\"jcifs.smb.client.disablePlainTextPasswords\", \"false\");\n\n\t\t// Initialize the preferences\n\t\tinitializePreferences();\n\n\t\t// Database setup\n\t\tsDbMovies = new DbAdapterMovies(this);\n\t\tsDbMovieMapping = new DbAdapterMovieMappings(this);\n\t\tsDbTvShowEpisode = new DbAdapterTvShowEpisodes(this);\n\t\tsDbTvShow = new DbAdapterTvShows(this);\n\t\tsDbTvShowEpisodeMappings = new DbAdapterTvShowEpisodeMappings(this);\n\t\tsDbSources = new DbAdapterSources(this);\n\t\tsDbCollections = new DbAdapterCollections(this);\n\n\t\tgetMovieThumbFolder(this);\n\t\tgetMovieBackdropFolder(this);\n\t\tgetTvShowThumbFolder(this);\n\t\tgetTvShowBackdropFolder(this);\n\t\tgetTvShowEpisodeFolder(this);\n\t\tgetTvShowSeasonFolder(this);\n\t\tgetAvailableOfflineFolder(this);\n\n\t\ttransitionLocalizationPreference();\n\t}\n\n\t@Override\n\tpublic void onTerminate() {\n\t\tsuper.onTerminate();\n\n\t\tsDbTvShow.close();\n\t\tsDbTvShowEpisode.close();\n\t\tsDbSources.close();\n\t\tsDbMovies.close();\n\t\tsDbMovieMapping.close();\n\t\tsDbCollections.close();\n\t}\n\n\tpublic static Context getContext() {\n\t\treturn mInstance;\n\t}\n\n\tprivate void initializePreferences() {\n\t\tPreferenceManager.setDefaultValues(this, R.xml.advanced_prefs, false);\n\t\tPreferenceManager.setDefaultValues(this, R.xml.general_prefs, false);\n\t\tPreferenceManager.setDefaultValues(this, R.xml.identification_search_prefs, false);\n\t\tPreferenceManager.setDefaultValues(this, R.xml.other_prefs, false);\n\t\tPreferenceManager.setDefaultValues(this, R.xml.user_interface_prefs, false);\n\t}\n\n\tprivate void transitionLocalizationPreference() {\n\t\t// Transition from the old localization preference if such exists\n\t\tString languagePref;\n\t\tboolean oldLocalizedPref = PreferenceManager.getDefaultSharedPreferences(this).getBoolean(\"prefsUseLocalData\", false);\n\t\tif (oldLocalizedPref) {\n\t\t\tlanguagePref = Locale.getDefault().getLanguage();\n\t\t\tPreferenceManager.getDefaultSharedPreferences(this).edit().remove(\"prefsUseLocalData\").commit();\n\t\t} else {\n\t\t\tlanguagePref = PreferenceManager.getDefaultSharedPreferences(this).getString(LANGUAGE_PREFERENCE, \"en\");\n\t\t}\n\n\t\tPreferenceManager.getDefaultSharedPreferences(this).edit().putString(LANGUAGE_PREFERENCE, languagePref).commit();\n\t}\n\n\tpublic static DbAdapterTvShows getTvDbAdapter() {\n\t\treturn sDbTvShow;\n\t}\n\n\tpublic static DbAdapterTvShowEpisodes getTvEpisodeDbAdapter() {\n\t\treturn sDbTvShowEpisode;\n\t}\n\n\tpublic static DbAdapterTvShowEpisodeMappings getTvShowEpisodeMappingsDbAdapter() {\n\t\treturn sDbTvShowEpisodeMappings;\n\t}\n\n\tpublic static DbAdapterSources getSourcesAdapter() {\n\t\treturn sDbSources;\n\t}\n\n\tpublic static DbAdapterMovies getMovieAdapter() {\n\t\treturn sDbMovies;\n\t}\n\n\tpublic static DbAdapterMovieMappings getMovieMappingAdapter() {\n\t\treturn sDbMovieMapping;\n\t}\n\n\tpublic static DbAdapterCollections getCollectionsAdapter() {\n\t\treturn sDbCollections;\n\t}\n\n\tpublic static String[] getCifsFilesList(String parentPath) {\n\t\treturn sMap.get(parentPath);\n\t}\n\n\tpublic static void putCifsFilesList(String parentPath, String[] list) {\n\t\tif (!sMap.containsKey(parentPath))\n\t\t\tsMap.put(parentPath, list);\n\t}\n\n\tpublic static Picasso getPicasso(Context context) {\n\t\tif (sPicasso == null)\n\t\t\tsPicasso = Picasso.with(context);\n\t\treturn sPicasso;\n\t}\n\n\tpublic static Bitmap.Config getBitmapConfig() {\n\t\treturn Bitmap.Config.RGB_565;\n\t}\n\n\tpublic static Typeface getOrCreateTypeface(Context context, String key) {\n\t\tif (!sTypefaces.containsKey(key))\n\t\t\tsTypefaces.put(key, Typeface.createFromAsset(context.getAssets(), key));\n\t\treturn sTypefaces.get(key);\n\t}\n\n\tpublic static Palette getPalette(String key) {\n\t\treturn sPalettes.get(key);\n\t}\n\n\tpublic static void addToPaletteCache(String key, Palette palette) {\n\t\tsPalettes.put(key, palette);\n\t}\n\n\tpublic static void setupTheme(Context context) {\n\t\tcontext.setTheme(R.style.Mizuu_Theme);\n\t}\n\n\tpublic static Bus getBus() {\n\t\tif (sBus == null)\n\t\t\tsBus = new Bus();\n\t\treturn sBus;\n\t}\n\n\tpublic static File getAppFolder(Context c) {\n\t\tif (sBaseAppFolder == null) {\n\t\t\tsBaseAppFolder = c.getExternalFilesDir(null);\n\t\t}\n\t\treturn sBaseAppFolder;\n\t}\n\n\tprivate static File getSubAppFolder(Context c, String foldername) {\n\t\treturn new File(getAppFolder(c), foldername);\n\t}\n\n\t/*\n\t * Please refrain from using this when you need a File object for a specific image.\n\t */\n\tpublic static File getMovieThumbFolder(Context c) {\n\t\tif (sMovieThumbFolder == null) {\n\t\t\tsMovieThumbFolder = getSubAppFolder(c, \"movie-thumbs\");\n\t\t\tsMovieThumbFolder.mkdirs();\n\t\t}\n\t\treturn sMovieThumbFolder;\n\t}\n\n\t/*\n\t * Please refrain from using this when you need a File object for a specific image.\n\t */\n\tpublic static File getMovieBackdropFolder(Context c) {\n\t\tif (sMovieBackdropFolder == null) {\n\t\t\tsMovieBackdropFolder = getSubAppFolder(c, \"movie-backdrops\");\n\t\t\tsMovieBackdropFolder.mkdirs();\n\t\t}\n\t\treturn sMovieBackdropFolder;\n\t}\n\n\t/*\n\t * Please refrain from using this when you need a File object for a specific image.\n\t */\n\tpublic static File getTvShowThumbFolder(Context c) {\n\t\tif (sTvShowThumbFolder == null) {\n\t\t\tsTvShowThumbFolder = getSubAppFolder(c, \"tvshows-thumbs\");\n\t\t\tsTvShowThumbFolder.mkdirs();\n\t\t}\n\t\treturn sTvShowThumbFolder;\n\t}\n\n\t/*\n\t * Please refrain from using this when you need a File object for a specific image.\n\t */\n\tpublic static File getTvShowBackdropFolder(Context c) {\n\t\tif (sTvShowBackdropFolder == null) {\n\t\t\tsTvShowBackdropFolder = getSubAppFolder(c, \"tvshows-backdrops\");\n\t\t\tsTvShowBackdropFolder.mkdirs();\n\t\t}\n\t\treturn sTvShowBackdropFolder;\n\t}\n\n\t/*\n\t * Please refrain from using this when you need a File object for a specific image.\n\t */\n\tpublic static File getTvShowEpisodeFolder(Context c) {\n\t\tif (sTvShowEpisodeFolder == null) {\n\t\t\tsTvShowEpisodeFolder = getSubAppFolder(c, \"tvshows-episodes\");\n\t\t\tsTvShowEpisodeFolder.mkdirs();\n\t\t}\n\t\treturn sTvShowEpisodeFolder;\n\t}\n\n\t/*\n\t * Please refrain from using this when you need a File object for a specific image.\n\t */\n\tpublic static File getTvShowSeasonFolder(Context c) {\n\t\tif (sTvShowSeasonFolder == null) {\n\t\t\tsTvShowSeasonFolder = getSubAppFolder(c, \"tvshows-seasons\");\n\t\t\tsTvShowSeasonFolder.mkdirs();\n\t\t}\n\t\treturn sTvShowSeasonFolder;\n\t}\n\n\t/*\n\t * Please refrain from using this when you need a File object for a specific video.\n\t */\n\tpublic static File getAvailableOfflineFolder(Context c) {\n\t\tif (sAvailableOfflineFolder == null) {\n\t\t\tsAvailableOfflineFolder = getSubAppFolder(c, \"offline_storage\");\n\t\t\tsAvailableOfflineFolder.mkdirs();\n\t\t}\n\t\treturn sAvailableOfflineFolder;\n\t}\n\n\t/*\n\t * Cache folder is used to store videos that are available offline as well\n\t * as user profile photo from Trakt.\n\t */\n\tpublic static File getCacheFolder(Context c) {\n\t\tif (sCacheFolder == null) {\n\t\t\tsCacheFolder = getSubAppFolder(c, \"app_cache\");\n\t\t\tsCacheFolder.mkdirs();\n\t\t}\n\t\treturn sCacheFolder;\n\t}\n\n\tpublic static TvShowApiService getTvShowService(Context context) {\n\t\treturn TMDbTvShowService.getInstance(context);\n\t}\n\n\tpublic static MovieApiService getMovieService(Context context) {\n\t\treturn TMDbMovieService.getInstance(context);\n\t}\n\n\t/**\n\t * This is used as an optimization to loading the movie library view.\n\t * @param filepaths\n\t */\n\tpublic static void setMovieFilepaths(ArrayListMultimap<String, String> filepaths) {\n\t\tmMovieFilepaths = filepaths;\n\t}\n\n\tpublic static List<String> getMovieFilepaths(String id) {\n\t\tif (mMovieFilepaths != null && mMovieFilepaths.containsKey(id))\n\t\t\treturn mMovieFilepaths.get(id);\n\t\treturn null;\n\t}\n\n\t/**\n\t * OkHttpClient singleton with 2 MB cache.\n\t * @return\n\t */\n\tpublic static OkHttpClient getOkHttpClient() {\n\t\tif (mOkHttpClient == null) {\n\t\t\tmOkHttpClient = new OkHttpClient();\n\n\t\t\tFile cacheDir = getContext().getCacheDir();\n\t\t\tCache cache = new Cache(cacheDir, 2 * 1024 * 1024);\n\t\t\tmOkHttpClient.setCache(cache);\n\t\t}\n\n\t\treturn mOkHttpClient;\n\t}\n\n\tpublic static void clearPicassoCache(Context context) {\n\t\tPicassoTools.clearCache(getPicasso(context));\n\t}\n}",
"public class MovieDatabaseUtils {\n\n\tprivate MovieDatabaseUtils() {} // No instantiation\n\n\t/**\n\t * Delete all movies in the various database tables and remove all related image files.\n\t * @param context\n\t */\n\tpublic static void deleteAllMovies(Context context) {\n\t\t// Delete all movies\n\t\tMizuuApplication.getMovieAdapter().deleteAllMovies();\n\t\t\n\t\t// Delete all movie filepath mappings\n\t\tMizuuApplication.getMovieMappingAdapter().deleteAllMovies();\n\t\t\n\t\t// Delete all movie collections\n\t\tMizuuApplication.getCollectionsAdapter().deleteAllCollections();\n\n\t\t// Delete all downloaded image files from the device\n\t\tFileUtils.deleteRecursive(MizuuApplication.getMovieThumbFolder(context), false);\n\t\tFileUtils.deleteRecursive(MizuuApplication.getMovieBackdropFolder(context), false);\n\t}\n\n\tpublic static void removeAllUnidentifiedFiles() {\n\t\tMizuuApplication.getMovieMappingAdapter().deleteAllUnidentifiedFilepaths();\n\t}\n\n public static void deleteMovie(Context context, String tmdbId) {\n if (TextUtils.isEmpty(tmdbId))\n return;\n\n DbAdapterMovies db = MizuuApplication.getMovieAdapter();\n\n // Delete the movie details\n db.deleteMovie(tmdbId);\n\n // When deleting a movie, check if there's other movies\n // linked to the collection - if not, delete the collection entry\n String collectionId = db.getCollectionId(tmdbId);\n if (MizuuApplication.getCollectionsAdapter().getMovieCount(collectionId) == 1)\n MizuuApplication.getCollectionsAdapter().deleteCollection(collectionId);\n\n // Finally, delete all filepath mappings to this movie ID\n MizuuApplication.getMovieMappingAdapter().deleteMovie(tmdbId);\n }\n\n public static void setMoviesFavourite(final Context context,\n final List<MediumMovie> movies,\n boolean favourite) {\n boolean success = true;\n\n for (MediumMovie movie : movies)\n success = success && MizuuApplication.getMovieAdapter().updateMovieSingleItem(movie.getTmdbId(),\n DbAdapterMovies.KEY_FAVOURITE, favourite ? \"1\" : \"0\");\n\n if (success)\n if (favourite)\n Toast.makeText(context, context.getString(R.string.addedToFavs), Toast.LENGTH_SHORT).show();\n else\n Toast.makeText(context, context.getString(R.string.removedFromFavs), Toast.LENGTH_SHORT).show();\n else\n Toast.makeText(context, context.getString(R.string.errorOccured), Toast.LENGTH_SHORT).show();\n\n new Thread() {\n @Override\n public void run() {\n Trakt.moviesFavorite(movies, context);\n }\n }.start();\n }\n\n public static void setMoviesWatched(final Context context,\n final List<MediumMovie> movies,\n boolean watched) {\n boolean success = true;\n\n for (MediumMovie movie : movies)\n success = success && MizuuApplication.getMovieAdapter().updateMovieSingleItem(movie.getTmdbId(),\n DbAdapterMovies.KEY_HAS_WATCHED, watched ? \"1\" : \"0\");\n\n if (success)\n if (watched) {\n Toast.makeText(context, context.getString(R.string.markedAsWatched), Toast.LENGTH_SHORT).show();\n\n setMoviesWatchlist(context, movies, false); // False to remove from watchlist\n } else\n Toast.makeText(context, context.getString(R.string.markedAsUnwatched), Toast.LENGTH_SHORT).show();\n else\n Toast.makeText(context, context.getString(R.string.errorOccured), Toast.LENGTH_SHORT).show();\n\n new Thread() {\n @Override\n public void run() {\n Trakt.markMoviesAsWatched(movies, context);\n }\n }.start();\n }\n\n public static void setMoviesWatchlist(final Context context,\n final List<MediumMovie> movies,\n boolean toWatch) {\n boolean success = true;\n\n for (MediumMovie movie : movies)\n success = success && MizuuApplication.getMovieAdapter().updateMovieSingleItem(movie.getTmdbId(),\n DbAdapterMovies.KEY_TO_WATCH, toWatch ? \"1\" : \"0\");\n\n if (success)\n if (toWatch)\n Toast.makeText(context, context.getString(R.string.addedToWatchList), Toast.LENGTH_SHORT).show();\n else\n Toast.makeText(context, context.getString(R.string.removedFromWatchList), Toast.LENGTH_SHORT).show();\n else\n Toast.makeText(context, context.getString(R.string.errorOccured), Toast.LENGTH_SHORT).show();\n\n new Thread() {\n @Override\n public void run() {\n Trakt.moviesWatchlist(movies, context);\n }\n }.start();\n }\n}"
] | import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.os.IBinder;
import android.text.TextUtils;
import com.miz.abstractclasses.MovieFileSource;
import com.miz.db.DbAdapterMovieMappings;
import com.miz.functions.ColumnIndexCache;
import com.miz.functions.DbMovie;
import com.miz.functions.FileSource;
import com.miz.functions.MizLib;
import com.miz.mizuu.MizuuApplication;
import com.miz.service.WireUpnpService;
import com.miz.utils.MovieDatabaseUtils;
import org.teleal.cling.android.AndroidUpnpService;
import org.teleal.cling.model.action.ActionInvocation;
import org.teleal.cling.model.message.UpnpResponse;
import org.teleal.cling.model.meta.Device;
import org.teleal.cling.model.meta.LocalDevice;
import org.teleal.cling.model.meta.RemoteDevice;
import org.teleal.cling.model.meta.Service;
import org.teleal.cling.model.types.UDAServiceType;
import org.teleal.cling.registry.DefaultRegistryListener;
import org.teleal.cling.registry.Registry;
import org.teleal.cling.support.contentdirectory.callback.Browse;
import org.teleal.cling.support.model.BrowseFlag;
import org.teleal.cling.support.model.DIDLContent;
import org.teleal.cling.support.model.SortCriterion;
import org.teleal.cling.support.model.container.Container;
import org.teleal.cling.support.model.item.Item;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.TreeSet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit; | /*
* Copyright (C) 2014 Michell Bak
*
* 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.miz.filesources;
public class UpnpMovie extends MovieFileSource<String> {
private TreeSet<String> results = new TreeSet<String>();
private HashMap<String, String> existingMovies = new HashMap<String, String>();
private CountDownLatch mLatch = new CountDownLatch(1);
private AndroidUpnpService mUpnpService;
public UpnpMovie(Context context, FileSource fileSource, boolean clearLibrary) {
super(context, fileSource, clearLibrary);
}
@Override
public void removeUnidentifiedFiles() {
List<DbMovie> dbMovies = getDbMovies();
int count = dbMovies.size();
for (int i = 0; i < count; i++) {
if (dbMovies.get(i).isUpnpFile() && dbMovies.get(i).isUnidentified() && MizLib.exists(dbMovies.get(i).getFilepath()))
MovieDatabaseUtils.deleteMovie(mContext, dbMovies.get(i).getTmdbId());
}
}
@Override
public void removeUnavailableFiles() {
List<DbMovie> dbMovies = getDbMovies();
int count = dbMovies.size();
for (int i = 0; i < count; i++) {
if (dbMovies.get(i).isUpnpFile() && !MizLib.exists(dbMovies.get(i).getFilepath())) {
MovieDatabaseUtils.deleteMovie(mContext, dbMovies.get(i).getTmdbId());
}
}
}
@Override
public List<String> searchFolder() { | DbAdapterMovieMappings dbHelper = MizuuApplication.getMovieMappingAdapter(); | 1 |
yangyong915/app | MyApplication/app/src/main/java/com/example/administrator/myapplication/p/NewsPresenter.java | [
"public class Base<T> {\n private boolean result;\n private Object message;\n private T data;\n private String nonce_str;\n private double time_spend;\n\n public boolean isResult() {\n return result;\n }\n\n public void setResult(boolean result) {\n this.result = result;\n }\n\n public Object getMessage() {\n return message;\n }\n\n public void setMessage(Object message) {\n this.message = message;\n }\n\n public String getNonce_str() {\n return nonce_str;\n }\n\n public void setNonce_str(String nonce_str) {\n this.nonce_str = nonce_str;\n }\n\n public T getData() {\n return data;\n }\n\n public void setData(T data) {\n this.data = data;\n }\n\n public double getTime_spend() {\n return time_spend;\n }\n\n public void setTime_spend(double time_spend) {\n this.time_spend = time_spend;\n }\n}",
"public class NewsList implements Serializable {\n private int news_id;\n private String title;\n private String intro;\n private String cover;\n private String source;\n private String datetime;\n private int view_num;\n private int agree_num;\n private int comment_num;\n\n public int getNews_id() {\n return news_id;\n }\n\n public void setNews_id(int news_id) {\n this.news_id = news_id;\n }\n\n public String getTitle() {\n return title;\n }\n\n public void setTitle(String title) {\n this.title = title;\n }\n\n public String getIntro() {\n return intro;\n }\n\n public void setIntro(String intro) {\n this.intro = intro;\n }\n\n public String getCover() {\n return cover;\n }\n\n public void setCover(String cover) {\n this.cover = cover;\n }\n\n public String getSource() {\n return source;\n }\n\n public void setSource(String source) {\n this.source = source;\n }\n\n public String getDatetime() {\n return datetime;\n }\n\n public void setDatetime(String datetime) {\n this.datetime = datetime;\n }\n\n public int getView_num() {\n return view_num;\n }\n\n public void setView_num(int view_num) {\n this.view_num = view_num;\n }\n\n public int getAgree_num() {\n return agree_num;\n }\n\n public void setAgree_num(int agree_num) {\n this.agree_num = agree_num;\n }\n\n public int getComment_num() {\n return comment_num;\n }\n\n public void setComment_num(int comment_num) {\n this.comment_num = comment_num;\n }\n\n @Override\n public String toString() {\n return \"NewsList{\" +\n \"news_id=\" + news_id +\n \", title='\" + title + '\\'' +\n \", intro='\" + intro + '\\'' +\n \", cover='\" + cover + '\\'' +\n \", source='\" + source + '\\'' +\n \", datetime='\" + datetime + '\\'' +\n \", view_num=\" + view_num +\n \", agree_num=\" + agree_num +\n \", comment_num=\" + comment_num +\n '}';\n }\n}",
"public class AesUtil {\n public static String key = Constant.KEY; //密钥\n\n /**\n * 加密\n *\n * @param data\n * @return\n * @throws Exception\n */\n public static String encrypt(String data) throws Exception {\n try {\n Cipher cipher = Cipher.getInstance(\"AES/ECB/NoPadding\");\n int blockSize = cipher.getBlockSize();\n\n byte[] dataBytes = data.getBytes();\n int plaintextLength = dataBytes.length;\n if (plaintextLength % blockSize != 0) {\n plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));\n }\n\n byte[] plaintext = new byte[plaintextLength];\n System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);\n\n SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), \"AES\");\n\n //ECB 模式不使用IV\n //IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());\n\n cipher.init(Cipher.ENCRYPT_MODE, keyspec);\n byte[] encrypted = cipher.doFinal(plaintext);\n return Base64.encodeToString(encrypted, Base64.NO_WRAP);\n // return new sun.misc.BASE64Encoder().encode(encrypted);\n\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n }\n\n /**\n * 聊天加密 ,防止socket粘包\n *\n * @param data\n * @return\n * @throws Exception\n */\n public static String encrypt_chart(String data) throws Exception {\n try {\n Cipher cipher = Cipher.getInstance(\"AES/ECB/NoPadding\");\n int blockSize = cipher.getBlockSize();\n\n byte[] dataBytes = data.getBytes();\n int plaintextLength = dataBytes.length;\n if (plaintextLength % blockSize != 0) {\n plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize));\n }\n\n byte[] plaintext = new byte[plaintextLength];\n System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length);\n\n SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), \"AES\");\n\n //ECB 模式不使用IV\n //IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());\n\n cipher.init(Cipher.ENCRYPT_MODE, keyspec);\n byte[] encrypted = cipher.doFinal(plaintext);\n return \"#\" + Base64.encodeToString(encrypted, Base64.NO_WRAP) + \"#\";\n // return new sun.misc.BASE64Encoder().encode(encrypted);\n\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n }\n\n /**\n * 解密\n *\n * @param data\n * @return String\n * @throws Exception\n */\n public static String desEncrypt(String data) throws Exception {\n try {\n byte[] encrypted1 = Base64.decode(data, Base64.NO_WRAP);\n Cipher cipher = Cipher.getInstance(\"AES/ECB/NoPadding\");\n SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), \"AES\");\n //ECB 模式不使用IV\n //IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes());\n\n cipher.init(Cipher.DECRYPT_MODE, keyspec);\n\n byte[] original = cipher.doFinal(encrypted1);\n\n String originalString = new String(original, \"UTF-8\");\n return originalString.trim();\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n }\n\n\n}",
"public class Constant {\n public static final String KEY = \"a06c2ff7467c7f15b8c594c1d44d8f78\";\n public static final String URL = \"http://app-service.wopu.me\";\n public static boolean isDebug = true; //是否开启日志输出\n\n public static final String GET_NEWSLIST = URL + \"/Common.wp/News/getNewsList\"; //获取资讯列表\n\n}",
"public class MD5 {\n public final static String getMessageDigest(byte[] buffer) {\n char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};\n try {\n MessageDigest mdTemp = MessageDigest.getInstance(\"MD5\");\n mdTemp.update(buffer);\n byte[] md = mdTemp.digest();\n int j = md.length;\n char str[] = new char[j * 2];\n int k = 0;\n for (int i = 0; i < j; i++) {\n byte byte0 = md[i];\n str[k++] = hexDigits[byte0 >>> 4 & 0xf];\n str[k++] = hexDigits[byte0 & 0xf];\n }\n return new String(str);\n } catch (Exception e) {\n return null;\n }\n }\n\n /**\n * 获取图片的url\n *\n * @param md5\n * @return\n */\n public final static String geturl(String md5) {\n return \"http://show-static-image.wopu.me/\" + md5 + \"@.gif\";\n }\n}"
] | import android.util.Log;
import com.example.administrator.myapplication.model.Base;
import com.example.administrator.myapplication.model.NewsList;
import com.example.administrator.myapplication.utils.AesUtil;
import com.example.administrator.myapplication.utils.Constant;
import com.example.administrator.myapplication.utils.MD5;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.List;
import okhttp3.Call;
import okhttp3.Response;
import rx.Subscription;
import rx.subscriptions.CompositeSubscription; | package com.example.administrator.myapplication.p;
/**
* Created by yy on 2016/12/22.
*/
public class NewsPresenter extends BasePresenter<INewsView> {
private static final String TAG = "NewsPresenter";
private INewsView mINewsView;
private CompositeSubscription compositeSubscription;
public NewsPresenter(INewsView newsView) {
mINewsView = newsView;
}
public void load_data(int page) {
mINewsView.showLoading();
try {
HashMap<String, Object> params = new HashMap<>();
params.put("page", page);
params.put("nonce_str", MD5.getMessageDigest(String.valueOf(System.currentTimeMillis()).getBytes()));
JSONObject jsonObject = new JSONObject(params);
Log.i(TAG, "req:" + jsonObject.toString());
String param = AesUtil.encrypt(jsonObject.toString());
OkGo.post(Constant.GET_NEWSLIST)
.tag(this)
.params("data", param)
.execute(new StringCallback() {
@Override
public void onSuccess(String s, Call call, Response response) {
try {
s = AesUtil.desEncrypt(s);
} catch (Exception e) {
e.printStackTrace();
}
Log.i(TAG, "data:" + s);
Gson gson = new Gson(); | Base<List<NewsList>> data = gson.fromJson(s, | 1 |
legobmw99/Allomancy | src/main/java/com/legobmw99/allomancy/datagen/Languages.java | [
"public enum Metal {\n IRON(true),\n STEEL,\n TIN,\n PEWTER,\n ZINC,\n BRASS,\n COPPER(true),\n BRONZE,\n ALUMINUM,\n DURALUMIN,\n CHROMIUM,\n NICROSIL,\n GOLD(true),\n ELECTRUM,\n CADMIUM,\n BENDALLOY;\n\n\n private final boolean vanilla;\n\n Metal() {\n this(false);\n }\n\n Metal(boolean isVanilla) {\n this.vanilla = isVanilla;\n }\n\n public static Metal getMetal(int index) {\n for (Metal metal : values()) {\n if (metal.getIndex() == index) {\n return metal;\n }\n }\n throw new IllegalArgumentException(\"Allomancy: Bad Metal Index\");\n }\n\n public boolean isVanilla() {\n return this.vanilla;\n }\n\n public String getName() {\n return name().toLowerCase(Locale.ROOT);\n }\n\n public int getIndex() {\n return ordinal();\n }\n\n\n}",
"public class CombatSetup {\n public static final DeferredRegister<EntityType<?>> ENTITIES = DeferredRegister.create(ForgeRegistries.ENTITIES, Allomancy.MODID);\n public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, Allomancy.MODID);\n public static final RegistryObject<CoinBagItem> COIN_BAG = ITEMS.register(\"coin_bag\", CoinBagItem::new);\n public static final RegistryObject<ObsidianDaggerItem> OBSIDIAN_DAGGER = ITEMS.register(\"obsidian_dagger\", ObsidianDaggerItem::new);\n public static final RegistryObject<KolossBladeItem> KOLOSS_BLADE = ITEMS.register(\"koloss_blade\", KolossBladeItem::new);\n public static final ArmorMaterial WoolArmor = new ArmorMaterial() {\n @Override\n public int getDurabilityForSlot(EquipmentSlot slotIn) {\n return 50;\n }\n\n @Override\n public int getDefenseForSlot(EquipmentSlot slotIn) {\n return slotIn == EquipmentSlot.CHEST ? 4 : 0;\n }\n\n @Override\n public int getEnchantmentValue() {\n return 15;\n }\n\n @Override\n public SoundEvent getEquipSound() {\n return SoundEvents.ARMOR_EQUIP_LEATHER;\n }\n\n @Override\n public Ingredient getRepairIngredient() {\n return Ingredient.of(Items.GRAY_WOOL);\n }\n\n @Override\n public String getName() {\n return \"allomancy:wool\";\n }\n\n @Override\n public float getToughness() {\n return 0;\n }\n\n @Override\n public float getKnockbackResistance() {\n return 0;\n }\n\n };\n public static final RegistryObject<MistcloakItem> MISTCLOAK = ITEMS.register(\"mistcloak\", MistcloakItem::new);\n public static final RegistryObject<EntityType<ProjectileNuggetEntity>> NUGGET_PROJECTILE = ENTITIES.register(\"nugget_projectile\", () -> EntityType.Builder\n .<ProjectileNuggetEntity>of(ProjectileNuggetEntity::new, MobCategory.MISC)\n .setShouldReceiveVelocityUpdates(true)\n .setUpdateInterval(20)\n .setCustomClientFactory((spawnEntity, world) -> new ProjectileNuggetEntity(world, spawnEntity.getEntity()))\n .sized(0.25F, 0.25F)\n .build(\"nugget_projectile\"));\n\n public static void register() {\n ENTITIES.register(FMLJavaModLoadingContext.get().getModEventBus());\n ITEMS.register(FMLJavaModLoadingContext.get().getModEventBus());\n }\n\n\n}",
"public class ConsumeSetup {\n public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, Allomancy.MODID);\n public static final DeferredRegister<RecipeSerializer<?>> RECIPES = DeferredRegister.create(ForgeRegistries.RECIPE_SERIALIZERS, Allomancy.MODID);\n public static final RegistryObject<GrinderItem> ALLOMANTIC_GRINDER = ITEMS.register(\"allomantic_grinder\", GrinderItem::new);\n public static final RegistryObject<LerasiumItem> LERASIUM_NUGGET = ITEMS.register(\"lerasium_nugget\", LerasiumItem::new);\n public static final RegistryObject<VialItem> VIAL = ITEMS.register(\"vial\", VialItem::new);\n public static final RegistryObject<SimpleRecipeSerializer<VialItemRecipe>> VIAL_RECIPE_SERIALIZER = RECIPES.register(\"vial_filling\", VialItemRecipe.Serializer::new);\n\n public static void register() {\n ITEMS.register(FMLJavaModLoadingContext.get().getModEventBus());\n RECIPES.register(FMLJavaModLoadingContext.get().getModEventBus());\n }\n\n}",
"public class ExtrasSetup {\n public static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, Allomancy.MODID);\n public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, Allomancy.MODID);\n\n public static final RegistryObject<IronButtonBlock> IRON_BUTTON = BLOCKS.register(\"iron_button\", IronButtonBlock::new);\n public static final RegistryObject<Item> IRON_BUTTON_ITEM = ITEMS.register(\"iron_button\",\n () -> new BlockItem(IRON_BUTTON.get(), new Item.Properties().tab(CreativeModeTab.TAB_REDSTONE)));\n public static final RegistryObject<IronLeverBlock> IRON_LEVER = BLOCKS.register(\"iron_lever\", IronLeverBlock::new);\n public static final RegistryObject<Item> IRON_LEVER_ITEM = ITEMS.register(\"iron_lever\",\n () -> new BlockItem(IRON_LEVER.get(), new Item.Properties().tab(CreativeModeTab.TAB_REDSTONE)));\n\n public static final List<BannerPattern> PATTERNS = new ArrayList<>();\n public static final List<RegistryObject<BannerPatternItem>> PATTERN_ITEMS = new ArrayList<>();\n\n\n static {\n for (Metal mt : Metal.values()) {\n String name = mt.getName();\n var pattern = BannerPattern.create(\"ALLOMANCY\" + mt.name(), \"allomancy_\" + name, \"allomancy_\" + name, true);\n var pattern_item = ITEMS.register(name + \"_pattern\", () -> new BannerPatternItem(pattern, Allomancy.createStandardItemProperties().stacksTo(1)));\n PATTERNS.add(pattern);\n PATTERN_ITEMS.add(pattern_item);\n }\n }\n\n public static void register() {\n BLOCKS.register(FMLJavaModLoadingContext.get().getModEventBus());\n ITEMS.register(FMLJavaModLoadingContext.get().getModEventBus());\n }\n}",
"public class MaterialsSetup {\n\n public static final String[] ORE_METALS = {\"aluminum\", \"cadmium\", \"chromium\", \"lead\", \"silver\", \"tin\", \"zinc\"};\n\n public static final DeferredRegister<Block> BLOCKS = DeferredRegister.create(ForgeRegistries.BLOCKS, Allomancy.MODID);\n public static final DeferredRegister<Item> ITEMS = DeferredRegister.create(ForgeRegistries.ITEMS, Allomancy.MODID);\n\n public static final List<RegistryObject<Item>> FLAKES = new ArrayList<>();\n public static final List<RegistryObject<Item>> NUGGETS = new ArrayList<>();\n public static final List<RegistryObject<Item>> INGOTS = new ArrayList<>();\n public static final List<RegistryObject<Block>> STORAGE_BLOCKS = new ArrayList<>();\n public static final List<RegistryObject<Item>> STORAGE_BLOCK_ITEMS = new ArrayList<>();\n\n\n public static final List<RegistryObject<OreBlock>> ORE_BLOCKS = new ArrayList<>();\n public static final List<RegistryObject<Item>> ORE_BLOCKS_ITEMS = new ArrayList<>();\n public static final List<RegistryObject<OreBlock>> DEEPSLATE_ORE_BLOCKS = new ArrayList<>();\n public static final List<RegistryObject<Item>> DEEPSLATE_ORE_BLOCKS_ITEMS = new ArrayList<>();\n public static final List<RegistryObject<Block>> RAW_ORE_BLOCKS = new ArrayList<>();\n public static final List<RegistryObject<Item>> RAW_ORE_BLOCKS_ITEMS = new ArrayList<>();\n public static final List<RegistryObject<Item>> RAW_ORE_ITEMS = new ArrayList<>();\n\n public static int METAL_ITEM_LEN = Metal.values().length;\n public static final int LEAD = METAL_ITEM_LEN++;\n public static final int SILVER = METAL_ITEM_LEN++;\n\n static {\n for (Metal mt : Metal.values()) {\n String name = mt.getName();\n FLAKES.add(MaterialsSetup.ITEMS.register(name + \"_flakes\", Allomancy::createStandardItem));\n\n if (mt.isVanilla()) {\n NUGGETS.add(null);\n INGOTS.add(null);\n STORAGE_BLOCKS.add(null);\n STORAGE_BLOCK_ITEMS.add(null);\n } else {\n NUGGETS.add(ITEMS.register(name + \"_nugget\", Allomancy::createStandardItem));\n INGOTS.add(ITEMS.register(name + \"_ingot\", Allomancy::createStandardItem));\n STORAGE_BLOCKS.add(BLOCKS.register(name + \"_block\", MaterialsSetup::createStandardBlock));\n STORAGE_BLOCK_ITEMS.add(ITEMS.register(name + \"_block\", () -> new BlockItem(STORAGE_BLOCKS.get(mt.getIndex()).get(), Allomancy.createStandardItemProperties())));\n }\n }\n FLAKES.add(MaterialsSetup.ITEMS.register(\"lead_flakes\", Allomancy::createStandardItem));\n NUGGETS.add(ITEMS.register(\"lead_nugget\", Allomancy::createStandardItem));\n INGOTS.add(ITEMS.register(\"lead_ingot\", Allomancy::createStandardItem));\n STORAGE_BLOCKS.add(BLOCKS.register(\"lead_block\", MaterialsSetup::createStandardBlock));\n STORAGE_BLOCK_ITEMS.add(ITEMS.register(\"lead_block\", () -> new BlockItem(STORAGE_BLOCKS.get(LEAD).get(), Allomancy.createStandardItemProperties())));\n\n FLAKES.add(MaterialsSetup.ITEMS.register(\"silver_flakes\", Allomancy::createStandardItem));\n NUGGETS.add(ITEMS.register(\"silver_nugget\", Allomancy::createStandardItem));\n INGOTS.add(ITEMS.register(\"silver_ingot\", Allomancy::createStandardItem));\n STORAGE_BLOCKS.add(BLOCKS.register(\"silver_block\", MaterialsSetup::createStandardBlock));\n STORAGE_BLOCK_ITEMS.add(ITEMS.register(\"silver_block\", () -> new BlockItem(STORAGE_BLOCKS.get(SILVER).get(), Allomancy.createStandardItemProperties())));\n\n for (String ore : ORE_METALS) {\n var ore_block = BLOCKS.register(ore + \"_ore\", MaterialsSetup::createStandardOre);\n ORE_BLOCKS.add(ore_block);\n ORE_BLOCKS_ITEMS.add(ITEMS.register(ore + \"_ore\", () -> new BlockItem(ore_block.get(), Allomancy.createStandardItemProperties())));\n\n var ds_ore_block = BLOCKS.register(\"deepslate_\" + ore + \"_ore\", MaterialsSetup::createDeepslateBlock);\n DEEPSLATE_ORE_BLOCKS.add(ds_ore_block);\n DEEPSLATE_ORE_BLOCKS_ITEMS.add(ITEMS.register(\"deepslate_\" + ore + \"_ore\", () -> new BlockItem(ds_ore_block.get(), Allomancy.createStandardItemProperties())));\n\n var raw_ore_block = BLOCKS.register(\"raw_\" + ore + \"_block\", MaterialsSetup::createStandardBlock);\n RAW_ORE_BLOCKS.add(raw_ore_block);\n RAW_ORE_BLOCKS_ITEMS.add(ITEMS.register(\"raw_\" + ore + \"_block\", () -> new BlockItem(raw_ore_block.get(), Allomancy.createStandardItemProperties())));\n\n RAW_ORE_ITEMS.add(ITEMS.register(\"raw_\" + ore, Allomancy::createStandardItem));\n }\n }\n\n\n public static void register() {\n BLOCKS.register(FMLJavaModLoadingContext.get().getModEventBus());\n ITEMS.register(FMLJavaModLoadingContext.get().getModEventBus());\n }\n\n public static void init(final FMLCommonSetupEvent e) {\n MinecraftForge.EVENT_BUS.register(LootTableInjector.class);\n OreGenerator.registerFeatures();\n }\n\n public static Block createStandardBlock() {\n return new Block(Block.Properties.of(Material.STONE).strength(2.1F).requiresCorrectToolForDrops());\n }\n\n public static OreBlock createStandardOre() {\n return new OreBlock(Block.Properties.of(Material.STONE).requiresCorrectToolForDrops().strength(3.0F, 3.0F));\n }\n\n public static OreBlock createDeepslateBlock() {\n return new OreBlock(Block.Properties.of(Material.STONE).requiresCorrectToolForDrops().color(MaterialColor.DEEPSLATE).strength(4.5F, 3.0F).sound(SoundType.DEEPSLATE));\n }\n}"
] | import com.legobmw99.allomancy.api.enums.Metal;
import com.legobmw99.allomancy.modules.combat.CombatSetup;
import com.legobmw99.allomancy.modules.consumables.ConsumeSetup;
import com.legobmw99.allomancy.modules.extras.ExtrasSetup;
import com.legobmw99.allomancy.modules.materials.MaterialsSetup;
import net.minecraft.data.DataGenerator;
import net.minecraft.world.item.DyeColor;
import net.minecraftforge.common.data.LanguageProvider;
import java.util.Arrays;
import java.util.Locale;
import java.util.stream.Collectors; | package com.legobmw99.allomancy.datagen;
public class Languages extends LanguageProvider {
public Languages(DataGenerator gen, String modid, String locale) {
super(gen, modid, locale);
}
private static String getDisplayName(Metal mt) {
return toTitleCase(mt.getName());
}
private static String toTitleCase(String in) {
return in.substring(0, 1).toUpperCase(Locale.US) + in.substring(1);
}
private static String getDisplayName(DyeColor color) {
String[] trans = color.getName().split("_");
return Arrays.stream(trans).map(Languages::toTitleCase).collect(Collectors.joining(" "));
}
@Override
protected void addTranslations() {
add("itemGroup.allomancy", "Allomancy");
for (int i = 0; i < MaterialsSetup.ORE_METALS.length; i++) {
String metal = MaterialsSetup.ORE_METALS[i];
var ore = MaterialsSetup.ORE_BLOCKS.get(i).get();
var ds = MaterialsSetup.DEEPSLATE_ORE_BLOCKS.get(i).get();
var rawb = MaterialsSetup.RAW_ORE_BLOCKS.get(i).get();
var raw = MaterialsSetup.RAW_ORE_ITEMS.get(i).get();
add(ore, toTitleCase(metal) + " Ore");
add(ds, "Deepslate " + toTitleCase(metal) + " Ore");
add(rawb, "Block of Raw " + toTitleCase(metal));
add(raw, "Raw " + toTitleCase(metal));
}
| add(ExtrasSetup.IRON_BUTTON.get(), "Iron Button"); | 3 |
xvik/generics-resolver | src/main/java/ru/vyarus/java/generics/resolver/util/walk/TypesWalker.java | [
"public final class ArrayTypeUtils {\n\n private static final String ARRAY_TYPE_SIMPLE_PREFIX = \"[\";\n private static final String ARRAY_TYPE_OBJECT_PREFIX = \"[L\";\n\n @SuppressWarnings({\"checkstyle:Indentation\", \"PMD.NonStaticInitializer\", \"PMD.AvoidUsingShortType\"})\n private static final Map<Class, String> PRIMITIVE_ARRAY_LETTER = new HashMap<Class, String>() {{\n put(byte.class, \"B\");\n put(char.class, \"C\");\n put(double.class, \"D\");\n put(float.class, \"F\");\n put(int.class, \"I\");\n put(long.class, \"J\");\n put(short.class, \"S\");\n put(boolean.class, \"Z\");\n }};\n\n private ArrayTypeUtils() {\n }\n\n /**\n * @param type type to check\n * @return true if type is array or generic array ({@link GenericArrayType}), false otherwise.\n */\n public static boolean isArray(final Type type) {\n return (type instanceof Class && ((Class) type).isArray()) || type instanceof GenericArrayType;\n }\n\n /**\n * For example, {@code getArrayComponentType(int[]) == int} and\n * {@code getArrayComponentType(List<String>[]) == List<String>}.\n *\n * @param type array type (class or {@link GenericArrayType}\n * @return array component type\n * @throws IllegalArgumentException if provided type is not array\n * @see #isArray(Type)\n */\n public static Type getArrayComponentType(final Type type) {\n if (!isArray(type)) {\n throw new IllegalArgumentException(\"Provided type is not an array: \"\n + TypeToStringUtils.toStringType(type));\n }\n if (type instanceof GenericArrayType) {\n return ((GenericArrayType) type).getGenericComponentType();\n } else {\n return ((Class) type).getComponentType();\n }\n }\n\n /**\n * Returns array class for provided class. For example, {@code toArrayClass(int) == int[]} and\n * {@code toArrayClass(List) == List[]}.\n * <p>\n * Pay attention that primitive arrays are returned for primitive types (no boxing applied automatically).\n * Also, primitives are not playing well with generalization, so you can't write\n * {@code Class<int[]> res = ArrayTypeUtils.toArrayClass(int.class)} (because IDE assumes {@code Integer[]} as\n * the return type, whereas actually {@code int[].class} will be returned). Use instead:\n * {@code Class<?> res = ArrayTypeUtils.toArrayClass(int.class)} or {@link #toArrayType(Type)} method.\n *\n * @param type class to get array of\n * @param <T> parameter type\n * @return class representing array of provided type\n * @see <a href=\"https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.3\">jvm arrays spec</a>\n * @see #toArrayType(Type) for general array case\n */\n @SuppressWarnings(\"unchecked\")\n public static <T> Class<T[]> toArrayClass(final Class<T> type) {\n try {\n final String name = type.getName();\n final String typeName;\n if (type.isArray()) {\n typeName = ARRAY_TYPE_SIMPLE_PREFIX + name;\n } else if (type.isPrimitive()) {\n typeName = ARRAY_TYPE_SIMPLE_PREFIX + PRIMITIVE_ARRAY_LETTER.get(type);\n } else {\n typeName = ARRAY_TYPE_OBJECT_PREFIX + name + \";\";\n }\n return (Class<T[]>) Class.forName(typeName);\n } catch (ClassNotFoundException e) {\n throw new IllegalStateException(\"Failed to create array class for \"\n + TypeToStringUtils.toStringType(type), e);\n }\n }\n\n /**\n * There are two possible cases:\n * <ul>\n * <li>Type is pure class - then arrays is simple class (e.g. {@code int[].class} or {@code List[].class}) </li>\n * <li>Type is generified - then {@link GenericArrayType} must be used (e.g. for parameterized type\n * {@code List<String>})</li>\n * </ul>\n *\n * @param type type to get array of\n * @return array type\n * @see #toArrayClass(Class) for pure class case\n */\n public static Type toArrayType(final Type type) {\n return type instanceof Class ? toArrayClass((Class<?>) type)\n : new GenericArrayTypeImpl(type);\n }\n}",
"@SuppressWarnings({\"PMD.LooseCoupling\", \"PMD.GodClass\", \"PMD.AvoidLiteralsInIfCondition\"})\npublic final class GenericsResolutionUtils {\n\n private static final String GROOVY_OBJECT = \"GroovyObject\";\n\n private GenericsResolutionUtils() {\n }\n\n /**\n * Analyze class hierarchy and resolve actual generic values for all composing types. Root type generics\n * (if present) will be resolved as upper bound from declaration.\n *\n * @param type type to resolve generics for\n * @param ignoreClasses classes to ignore (if required)\n * @return resolved generics for all types in class hierarchy\n * @see #resolve(Class, LinkedHashMap, Class[]) if you have known root generics\n * @see #resolve(Class, LinkedHashMap, Map, List) if you have known generics for middle types\n */\n public static Map<Class<?>, LinkedHashMap<String, Type>> resolve(final Class<?> type,\n final Class<?>... ignoreClasses) {\n return resolve(type, resolveRawGenerics(type), ignoreClasses);\n }\n\n /**\n * Resolve hierarchy of provided type. It makes sense only for {@link ParameterizedType} as only this type\n * could hold class generics. Parameter preserved to be {@link Type} for more universal usage\n * (to avoid instanceof checks), execution for simple {@link Class} is completely equal to\n * {@link #resolve(Class, Class[])} method call (original method preserved for api compatibility).\n * <p>\n * When provided type is not {@link ParameterizedType}, root class generics will be resolved\n * as upper bounds (the same as in {@link #resolve(Class, Class[])}).\n * <p>\n * IMPORTANT: If provided type contain variables ({@link TypeVariable}), they will be replaced by\n * {@link Object} (not upper bound!). Perform variables processing manually before calling this method\n * in order to get more precise results (e.g. with {@link TypeVariableUtils#resolveAllTypeVariables(Type)}).\n * <p>\n * You can also use {@link TypeLiteral} for dynamic type declarations (tracking cases):\n * {@code GenericsResolutionUtils.resolve(new TypeLiteral<MyClass<String, Boolean>(){}.getType())}.\n *\n * @param type type to resolve generics for\n * @param ignoreClasses classes to ignore (if required)\n * @return resolved generics for all types in class hierarchy\n * @see #resolve(Class, LinkedHashMap, Class[]) if you have known root generics\n * @see #resolve(Class, LinkedHashMap, Map, List) if you have known generics for middle types\n */\n public static Map<Class<?>, LinkedHashMap<String, Type>> resolve(final Type type,\n final Class<?>... ignoreClasses) {\n return resolve(GenericsUtils.resolveClassIgnoringVariables(type),\n resolveGenerics(type, IgnoreGenericsMap.getInstance()), ignoreClasses);\n }\n\n /**\n * Analyze class hierarchy and resolve actual generic values for all composing types. Root type generics\n * are known.\n *\n * @param type type to resolve generics for\n * @param rootGenerics resolved root type generics (including owner type generics); must not be null!\n * @param ignoreClasses classes to ignore (if required\n * @return resolved generics for all types in class hierarchy\n */\n public static Map<Class<?>, LinkedHashMap<String, Type>> resolve(\n final Class<?> type,\n final LinkedHashMap<String, Type> rootGenerics,\n final Class<?>... ignoreClasses) {\n return resolve(type,\n rootGenerics,\n Collections.<Class<?>, LinkedHashMap<String, Type>>emptyMap(),\n Arrays.asList(ignoreClasses));\n }\n\n /**\n * Analyze class hierarchy and resolve actual generic values for all composing types. Root type\n * generics must be specified directly.\n * <p>\n * If generics are known for some middle type, then they would be used \"as is\" instead of generics tracked\n * from root. Also, known generics will be used for lower hierarchy resolution.\n *\n * @param type class to analyze\n * @param rootGenerics resolved root type generics (including owner type generics); must not be null!\n * @param knownGenerics type generics known before analysis (some middle class generics are known) and\n * could contain possible outer generics (types for sure not included in resolving type\n * hierarchy); must not be null, but could be empty map\n * @param ignoreClasses classes to ignore during analysis\n * @return resolved generics for all types in class hierarchy\n */\n public static Map<Class<?>, LinkedHashMap<String, Type>> resolve(\n final Class<?> type,\n final LinkedHashMap<String, Type> rootGenerics,\n final Map<Class<?>, LinkedHashMap<String, Type>> knownGenerics,\n final List<Class<?>> ignoreClasses) {\n final Map<Class<?>, LinkedHashMap<String, Type>> generics =\n new HashMap<Class<?>, LinkedHashMap<String, Type>>();\n generics.put(type, rootGenerics);\n try {\n analyzeType(generics, type, knownGenerics, ignoreClasses);\n } catch (Exception ex) {\n throw new GenericsResolutionException(type, rootGenerics, knownGenerics, ex);\n }\n return generics;\n }\n\n /**\n * Resolve declared generics for type (actually declared generics in context of some type).\n * If provided class is inner class - resolves outer class generics as upper bound\n * <p>\n * If type is not {@link ParameterizedType} and so does not contains actual generics info, resolve\n * generics from type declaration ({@link #resolveRawGenerics(Class)}),\n * <p>\n * NOTE: for {@link WildcardType} returned map will contain only first upper bound type generics, resolved\n * by upper bound (because in many cases it would be impossible to build not contradicting generics map for\n * wildcard due to same generic names in different types).\n *\n * @param type type to resolve generics for\n * @param generics generics of context class\n * @return resolved generics of parameterized type or empty map\n */\n public static LinkedHashMap<String, Type> resolveGenerics(final Type type,\n final Map<String, Type> generics) {\n Type actual = type;\n if (type instanceof ParameterizedType) {\n // if parameterized type is not correct (contain only raw type without type arguments\n // (possible for instance types) then this call could unwrap it to pure class\n actual = GenericsUtils.resolveTypeVariables(type, generics);\n }\n final LinkedHashMap<String, Type> res;\n if (actual instanceof ParameterizedType) {\n final ParameterizedType actualType = (ParameterizedType) actual;\n final Type[] genericTypes = actualType.getActualTypeArguments();\n final Class target = (Class) actualType.getRawType();\n final TypeVariable[] genericNames = target.getTypeParameters();\n\n // inner class can use outer class generics\n res = fillOuterGenerics(actual, new LinkedHashMap<String, Type>(), null);\n\n final int cnt = genericNames.length;\n for (int i = 0; i < cnt; i++) {\n res.put(genericNames[i].getName(), genericTypes[i]);\n }\n } else {\n res = resolveRawGenerics(GenericsUtils.resolveClass(actual, generics));\n }\n return res;\n }\n\n /**\n * Resolve type generics by declaration (as upper bound). Used for cases when actual generic definition is not\n * available (so actual generics are unknown). In most cases such generics resolved as Object\n * (for example, {@code Some<T>}).\n * <p>\n * If class is inner class, resolve outer class generics (which may be used in class)\n *\n * @param type class to analyze generics for\n * @return resolved generics (including outer class generics) or empty map if not generics used\n * @see #resolveDirectRawGenerics(Class) to resolve without outer type\n */\n public static LinkedHashMap<String, Type> resolveRawGenerics(final Class<?> type) {\n // inner class can use outer class generics\n return fillOuterGenerics(type, resolveDirectRawGenerics(type), null);\n }\n\n /**\n * Resolve type generics by declaration (as upper bound). Used for cases when actual generic definition is not\n * available (so actual generics are unknown). In most cases such generics resolved as Object\n * (for example, {@code Some<T>}).\n * <p>\n * IMPORTANT: this method does not count possible outer class generics! Use\n * {@link #resolveRawGeneric(TypeVariable, LinkedHashMap)} as universal resolution method\n *\n * @param type class to analyze generics for\n * @return resolved generics or empty map if not generics used\n * @see #resolveRawGenerics(Class) to include outer type generics\n */\n public static LinkedHashMap<String, Type> resolveDirectRawGenerics(final Class<?> type) {\n return resolveRawGenericsChain(type.getTypeParameters(), null);\n }\n\n /**\n * Resolve method generics by declaration (as upper bound). Generics are resolved as upper bound (because it is\n * all available type information). For example, {@code public <T extends Serializable> do(T param)}\n * contains generic T which must be resolved as Serializable.\n *\n * @param method method to analyze generics for\n * @param generics context class generics (which could be used in method generics declarations)\n * @return resolved generics or empty map if method does not contain generics\n */\n public static LinkedHashMap<String, Type> resolveDirectRawGenerics(final Method method,\n final Map<String, Type> generics) {\n return resolveRawGenericsChain(method.getTypeParameters(), generics);\n }\n\n /**\n * Resolve constructor generics by declaration (as upper bound). Generics are resolved as upper bound (because it is\n * all available type information). For example, {@code public <T extends Serializable> MyType(T param)}\n * contains generic T which must be resolved as Serializable.\n *\n * @param constructor constructor to analyze generics for\n * @param generics context class generics (which could be used in constructor generics declarations)\n * @return resolved generics or empty map if constructor does not contain generics\n */\n public static LinkedHashMap<String, Type> resolveDirectRawGenerics(final Constructor constructor,\n final Map<String, Type> generics) {\n return resolveRawGenericsChain(constructor.getTypeParameters(), generics);\n }\n\n /**\n * Extracts declared upper bound from generic declaration. For example, {@code Base<T>} will be resolved\n * as Object (default bound). {@code Base<T extends A & B>} resolved as \"impossible\" wildcard\n * {@code ? extends A & B} in order to preserve all known information.\n * <p>\n * Map of already resolved generics is required because declaration may rely on them. For example,\n * {@code Base<T extends Serializable, K extends T>} could be solved as {@code T = Serializable, K = Serializable}.\n *\n * @param variable generic declaration to analyze\n * @param generics already resolved generics (on the left of current)\n * @return either upper bound class or wildcard with multiple bounds\n */\n public static Type resolveRawGeneric(final TypeVariable variable,\n final LinkedHashMap<String, Type> generics) {\n final Type res;\n if (variable.getBounds().length > 1) {\n // case: T extends A & B --> ? extends A & B\n final List<Type> types = new ArrayList<Type>();\n for (Type bound : variable.getBounds()) {\n // replace possible named generics with actual type (for cases like K extends T)\n final Type actual = GenericsUtils.resolveTypeVariables(bound, generics);\n if (actual instanceof WildcardType && ((WildcardType) actual).getUpperBounds().length > 0) {\n // case: T extends A & B, K extends T & C --> K must be aggregated as ? extends A & B & C\n // this case is impossible in java, but allowed in groovy\n types.addAll(Arrays.asList(GenericsUtils\n .resolveTypeVariables(((WildcardType) actual).getUpperBounds(), generics)));\n } else {\n types.add(actual);\n }\n }\n // case: T extends Object & Something (may appear because of transitive generics resolution)\n // only one object could appear (because wildcard could only be\n // ? extends type (or generic) & exact interface (& exact interface))\n // (repackaged from type declaration)\n types.remove(Object.class);\n if (types.size() > 1) {\n // repackaging as impossible wildcard <? extends A & B> to store all known information\n res = WildcardTypeImpl.upper(types.toArray(new Type[0]));\n } else {\n // if one type remain - use it directly; if no types remain - use Object\n res = types.isEmpty() ? Object.class : types.get(0);\n }\n } else {\n // case: simple generic declaration <T> (implicitly extends Object)\n res = GenericsUtils.resolveTypeVariables(variable.getBounds()[0], generics);\n }\n return res;\n }\n\n /**\n * Inner class could reference outer class generics and so this generics must be included into class context.\n * <p>\n * Outer generics could be included into declaration like {@code Outer<String>.Inner field}. In this case\n * incoming type should be {@link ParameterizedType} with generified owner.\n * <p>\n * When provided type is simply a class (or anything resolvable to class), then outer class generics are resolved\n * as upper bound (by declaration). Class may declare the same generic name and, in this case, outer generic\n * will be ignored (as not visible).\n * <p>\n * During inlying context resolution, if outer generic is not declared in type we can try to guess it:\n * we know outer context, and, if outer class is in outer context hierarchy, we could assume that it's actual\n * parent class and so we could use more specific generics. This will be true for most sane cases (often inner\n * class is used inside owner), but other cases are still possible (anyway, the chance that inner class will\n * appear in two different hierarchies of outer class is quite small).\n * <p>\n * It is very important to use returned map instead of passed in map because, incoming empty map is always replaced\n * to avoid modifications of shared empty maps.\n *\n * @param type context type\n * @param generics resolved type generics\n * @param knownGenerics map of known middle generics and possibly known outer context (outer context may contain\n * outer class generics declarations). May be null.\n * @return actual generics map (incoming map may be default empty map and in this case it must be replaced)\n */\n public static LinkedHashMap<String, Type> fillOuterGenerics(\n final Type type,\n final LinkedHashMap<String, Type> generics,\n final Map<Class<?>, LinkedHashMap<String, Type>> knownGenerics) {\n final LinkedHashMap<String, Type> res;\n final Type outer = TypeUtils.getOuter(type);\n if (outer == null) {\n // not inner class\n res = generics;\n } else {\n final LinkedHashMap<String, Type> outerGenerics;\n if (outer instanceof ParameterizedType) {\n // outer generics declared in field definition (ignorance required because provided type\n // may contain unknown outer generics (Outer<B>.Inner field))\n outerGenerics = resolveGenerics(outer, new IgnoreGenericsMap(generics));\n } else {\n final Class<?> outerType = GenericsUtils.resolveClass(outer, generics);\n // either use known generics for outer class or resolve by upper bound\n outerGenerics = knownGenerics != null && knownGenerics.containsKey(outerType)\n ? new LinkedHashMap<String, Type>(knownGenerics.get(outerType))\n : resolveRawGenerics(outerType);\n }\n // class may declare generics with the same name and they must not be overridden\n for (TypeVariable var : GenericsUtils.resolveClass(type, generics).getTypeParameters()) {\n outerGenerics.remove(var.getName());\n }\n\n if (generics instanceof EmptyGenericsMap) {\n // if outer map is empty then it was assumed that empty map could be returned\n // (outerGenerics could be empty map too)\n res = outerGenerics;\n } else {\n generics.putAll(outerGenerics);\n res = generics;\n }\n }\n return res;\n }\n\n /**\n * Generic method for direct generics declaration analysis for class, method or constructor.\n * Generic declarations may depend on each other ({@code <T, K extends Collection<T>>}, cycle\n * ({@code <T extends Comparable<T>}) and depend on some other generics (hosting class generics).\n *\n * @param declaredGenerics declaration chain (chain is important because declarations may be dependent)\n * @param generics known context generics or null\n * @return resolved generics or empty map if empty generic declarations provided\n */\n private static LinkedHashMap<String, Type> resolveRawGenericsChain(final TypeVariable[] declaredGenerics,\n final Map<String, Type> generics) {\n if (declaredGenerics.length == 0) {\n return EmptyGenericsMap.getInstance();\n }\n final LinkedHashMap<String, Type> contextGenerics = generics == null ? new LinkedHashMap<String, Type>()\n : new LinkedHashMap<String, Type>(generics);\n final LinkedHashMap<String, Type> res = new LinkedHashMap<String, Type>();\n final List<TypeVariable> failed = new ArrayList<TypeVariable>();\n // variables in declaration could be dependant and in any direction (e.g. <A extends List<B>, B>)\n // so assuming correct order at first, but if we face any error - order vars and resolve correctly\n // (it's better to avoid ordering by default as its required quite rarely)\n for (TypeVariable variable : declaredGenerics) {\n Type resolved = null;\n try {\n resolved = resolveRawGeneric(variable, contextGenerics);\n } catch (UnknownGenericException ex) {\n // direct cycle case Something<T extends Something<T>>\n // (failed generic is exactly resolving generic)\n if (ex.getGenericName().equals(variable.getName())\n && ex.getGenericSource().equals(variable.getGenericDeclaration())) {\n resolved = GenericsUtils.resolveClass(variable.getBounds()[0], contextGenerics);\n } else {\n // variable will be stored with null to preserve order (without resolution) and resolved later\n // (inversed declaration order case)\n failed.add(variable);\n }\n }\n // storing null is OK! - just holding correct generic place\n res.put(variable.getName(), resolved);\n contextGenerics.put(variable.getName(), resolved);\n }\n if (!failed.isEmpty()) {\n for (TypeVariable variable : GenericsUtils.orderVariablesForResolution(failed)) {\n // replacing nulls in map\n final Type result = resolveRawGeneric(variable, contextGenerics);\n res.put(variable.getName(), result);\n contextGenerics.put(variable.getName(), result);\n }\n }\n return res;\n }\n\n /**\n * Analyze type hierarchy (all subclasses and interfaces).\n *\n * @param generics resolved generics of already analyzed types\n * @param knownGenerics type generics known before analysis (some middle class generics are known) and\n * possible owner types (types not present in analyzed type hierarchy)\n * @param type class to analyze\n * @param ignoreClasses classes to ignore during analysis\n */\n private static void analyzeType(final Map<Class<?>, LinkedHashMap<String, Type>> generics,\n final Class<?> type,\n final Map<Class<?>, LinkedHashMap<String, Type>> knownGenerics,\n final List<Class<?>> ignoreClasses) {\n Class<?> supertype = type;\n while (true) {\n for (Type iface : supertype.getGenericInterfaces()) {\n analyzeInterface(generics, knownGenerics, iface, supertype, ignoreClasses);\n }\n final Class next = supertype.getSuperclass();\n if (next == null || Object.class == next || ignoreClasses.contains(next)) {\n break;\n }\n // possibly provided generics (externally)\n final LinkedHashMap<String, Type> nextGenerics = knownGenerics.containsKey(next)\n ? knownGenerics.get(next)\n : analyzeParent(supertype, generics.get(supertype));\n generics.put(next,\n fillOuterGenerics(next, nextGenerics, knownGenerics));\n supertype = next;\n }\n }\n\n /**\n * Analyze interface generics. If type is contained in known types - no generics resolution performed\n * (trust provided info).\n *\n * @param types resolved generics of already analyzed types\n * @param knownTypes type generics known before analysis (some middle class generics are known)\n * @param iface interface to analyze\n * @param hostType class implementing interface (where generics actually defined)\n * @param ignoreClasses classes to ignore during analysis\n */\n private static void analyzeInterface(final Map<Class<?>, LinkedHashMap<String, Type>> types,\n final Map<Class<?>, LinkedHashMap<String, Type>> knownTypes,\n final Type iface,\n final Class<?> hostType,\n final List<Class<?>> ignoreClasses) {\n final Class interfaceType = iface instanceof ParameterizedType\n ? (Class) ((ParameterizedType) iface).getRawType()\n : (Class) iface;\n if (!ignoreClasses.contains(interfaceType)) {\n if (knownTypes.containsKey(interfaceType)) {\n // check possibly already resolved generics (if provided externally)\n types.put(interfaceType, knownTypes.get(interfaceType));\n } else if (iface instanceof ParameterizedType) {\n final ParameterizedType parametrization = (ParameterizedType) iface;\n final LinkedHashMap<String, Type> generics =\n resolveGenerics(parametrization, types.get(hostType));\n\n if (types.containsKey(interfaceType)) {\n // class hierarchy may contain multiple implementations for the same interface\n // in this case we can merge known generics, using most specific types\n // (root type unifies interfaces, so we just collecting actual maximum known info\n // from multiple sources)\n merge(interfaceType, generics, types.get(interfaceType));\n }\n types.put(interfaceType, generics);\n } else if (interfaceType.getTypeParameters().length > 0) {\n // root class didn't declare generics\n types.put(interfaceType, resolveRawGenerics(interfaceType));\n } else if (!GROOVY_OBJECT.equals(interfaceType.getSimpleName())) {\n // avoid groovy specific interface (all groovy objects implements it)\n types.put(interfaceType, EmptyGenericsMap.getInstance());\n }\n analyzeType(types, interfaceType, knownTypes, ignoreClasses);\n }\n }\n\n private static void merge(final Class<?> type,\n final LinkedHashMap<String, Type> main,\n final LinkedHashMap<String, Type> additional) {\n for (Map.Entry<String, Type> entry : additional.entrySet()) {\n final String generic = entry.getKey();\n final Type value = entry.getValue();\n final Type currentValue = main.get(generic);\n\n if (TypeUtils.isCompatible(value, currentValue)) {\n main.put(generic, TypeUtils.getMoreSpecificType(value, currentValue));\n } else {\n // all variables already replaces, so no actual generics required\n throw new IncompatibleTypesException(String.format(\n \"Interface %s appears multiple times in root class hierarchy with incompatible \"\n + \"parametrization for generic %s: %%s and %%s\",\n TypeToStringUtils.toStringWithNamedGenerics(type), generic), currentValue, value);\n }\n }\n }\n\n /**\n * Analyze super class generics (relative to provided type). Class may not declare generics for super class\n * ({@code Some extends Base} where {@code class Base<T> }) and, in this case, parent class generics could\n * be resolved only by upper bound. Note that parent type analysis must be performed only when generics\n * for perent type are not known ahead of time (inlying resolution cases).\n *\n * @param type type to analyze parent class for\n * @param generics known type generics\n * @return resolved parent class generics\n */\n private static LinkedHashMap<String, Type> analyzeParent(final Class type,\n final Map<String, Type> generics) {\n LinkedHashMap<String, Type> res = null;\n final Class parent = type.getSuperclass();\n if (!type.isInterface() && parent != null && parent != Object.class\n && type.getGenericSuperclass() instanceof ParameterizedType) {\n res = resolveGenerics(type.getGenericSuperclass(), generics);\n } else if (parent != null && parent.getTypeParameters().length > 0) {\n // root class didn't declare generics\n res = resolveRawGenerics(parent);\n }\n return res == null ? EmptyGenericsMap.getInstance() : res;\n }\n}",
"@SuppressWarnings({\"PMD.GodClass\", \"PMD.TooManyMethods\", \"PMD.CyclomaticComplexity\"})\npublic final class GenericsUtils {\n\n private static final Type[] NO_TYPES = new Type[0];\n\n private GenericsUtils() {\n }\n\n /**\n * Shortcut for {@link GenericsTrackingUtils} to simplify tracking generics from known middle class.\n * For example, knowing {@code List<String>} we can track generic for {@code ArrayList<T>}.\n * <p>\n * In order to start generics resolution known type must be:\n * <ul>\n * <li>{@link ParameterizedType} - then parametrization used for tracking</li>\n * <li>{@link WildcardType} containing {@link ParameterizedType} - then all such types will be tracked\n * and the most specific generics selected</li>\n * <li>{@link GenericArrayType} - then component types are compared according to first two rules.</li>\n * </ul>\n * In all other cases, type is simply returned as is (no source to track from).\n * <p>\n * Target type may be any type (for usage simplicity), but only class declaration will be taken from it\n * (in order to build {@link ParameterizedType} with tracked generics). If target type\n * is already {@link ParameterizedType} and contain some generics - they will be used too in order to not\n * lower declaration specificity. If target class does not have declared generics at all - type is returned back\n * as is.\n *\n * @param type class to resolve generics for\n * @param source sub type with known generics\n * @return {@link ParameterizedType} with tracked generics or original type if no declared generics or known\n * type is not {@link ParameterizedType}\n * @throws IllegalArgumentException if type is not assignable to known type.\n * @see GenericsTrackingUtils#track(Class, Class, LinkedHashMap) for more specific cases\n */\n public static Type trackGenerics(final Type type, final Type source) {\n return TrackedTypeFactory.build(type, source);\n }\n\n /**\n * Called to properly resolve return type of root finder or inherited finder method.\n * Supposed to return enough type info to detect return type (collection, array or plain object).\n * <p>\n * Note: may return primitive because it might be important to differentiate actual value.\n * Use {@link TypeUtils#wrapPrimitive(Class)} to box possible primitive, if required.\n *\n * @param method method to analyze\n * @param generics generics resolution map for method class (will be null for root)\n * @return return type class\n */\n public static Class<?> getReturnClass(final Method method, final Map<String, Type> generics) {\n final Type returnType = method.getGenericReturnType();\n return resolveClass(returnType, generics);\n }\n\n /**\n * If type is a variable, looks actual variable type, if it contains generics.\n * For {@link ParameterizedType} return actual type parameters, for simple class returns raw class generics.\n * <p>\n * Note: returned generics may contain variables inside!\n *\n * @param type type to get generics of\n * @param generics context generics map\n * @return type generics array or empty array\n */\n public static Type[] getGenerics(final Type type, final Map<String, Type> generics) {\n Type[] res = NO_TYPES;\n Type analyzingType = type;\n if (type instanceof TypeVariable) {\n // if type is pure generic recovering parametrization\n analyzingType = declaredGeneric((TypeVariable) type, generics);\n }\n if ((analyzingType instanceof ParameterizedType)\n && ((ParameterizedType) analyzingType).getActualTypeArguments().length > 0) {\n res = ((ParameterizedType) analyzingType).getActualTypeArguments();\n } else if (type instanceof Class) {\n // if type is class return raw declaration\n final Class<?> actual = (Class<?>) analyzingType;\n if (actual.getTypeParameters().length > 0) {\n res = GenericsResolutionUtils.resolveDirectRawGenerics(actual)\n .values().toArray(new Type[0]);\n }\n }\n return res;\n }\n\n /**\n * Called to properly resolve generified type (e.g. generified method return).\n * For example, when calling for {@code List<T>} it will return type of {@code T}.\n * <p>\n * If called on class (e.g. List) then return raw generic definition (upper bounds).\n *\n * @param type type to analyze\n * @param generics root class generics mapping\n * @return resolved generic classes or empty list if type does not support generics\n * @throws UnknownGenericException when found generic not declared on type (e.g. method generic)\n */\n public static List<Class<?>> resolveGenericsOf(final Type type, final Map<String, Type> generics) {\n final Type[] typeGenerics = getGenerics(type, generics);\n if (typeGenerics.length == 0) {\n return Collections.emptyList();\n }\n final List<Class<?>> res = new ArrayList<Class<?>>();\n for (Type gen : typeGenerics) {\n res.add(resolveClass(gen, generics));\n }\n return res;\n }\n\n /**\n * Shortcut for {@link #resolveClass(Type, Map)} (called with {@link IgnoreGenericsMap}). Could be used\n * when class must be resolved ignoring possible variables.\n * <p>\n * Note: {@code Object} will be used instead of variable even if it has upper bound declared (e.g.\n * {@code T extends Serializable}).\n *\n * @param type type to resolve\n * @return resolved class\n */\n public static Class<?> resolveClassIgnoringVariables(final Type type) {\n return resolveClass(type, IgnoreGenericsMap.getInstance());\n }\n\n /**\n * Shortcut for {@link #resolveClass(Type, Map)} (called with {@link EmptyGenericsMap}). Could be used\n * when provided type does not contain variables. If provided type contain variables, error will be thrown.\n *\n * @param type type to resolve\n * @return resolved class\n * @throws UnknownGenericException when found generic not declared on type (e.g. method generic)\n * @see #resolveClassIgnoringVariables(Type) to resolve type ignoring variables\n */\n public static Class<?> resolveClass(final Type type) {\n return resolveClass(type, EmptyGenericsMap.getInstance());\n }\n\n /**\n * Resolves top class for provided type (for example, for generified classes like {@code List<T>} it\n * returns base type List).\n * <p>\n * Note: may return primitive because it might be important to differentiate actual value.\n * Use {@link TypeUtils#wrapPrimitive(Class)} to box possible primitive, if required.\n *\n * @param type type to resolve\n * @param generics root class generics mapping\n * @return resolved class\n * @throws UnknownGenericException when found generic not declared on type (e.g. method generic)\n * @see #resolveClass(Type) shortcut for types without variables\n * @see #resolveClassIgnoringVariables(Type) shortcut to resolve class ignoring passible variables\n */\n public static Class<?> resolveClass(final Type type, final Map<String, Type> generics) {\n final Class<?> res;\n if (type instanceof Class) {\n res = (Class) type;\n } else if (type instanceof ExplicitTypeVariable) {\n res = resolveClass(((ExplicitTypeVariable) type).getBounds()[0], generics);\n } else if (type instanceof ParameterizedType) {\n res = resolveClass(((ParameterizedType) type).getRawType(), generics);\n } else if (type instanceof TypeVariable) {\n res = resolveClass(declaredGeneric((TypeVariable) type, generics), generics);\n } else if (type instanceof WildcardType) {\n final Type[] upperBounds = ((WildcardType) type).getUpperBounds();\n res = resolveClass(upperBounds[0], generics);\n } else {\n res = ArrayTypeUtils.toArrayClass(\n resolveClass(((GenericArrayType) type).getGenericComponentType(), generics));\n }\n return res;\n }\n\n /**\n * Resolve classes of provided types.\n * <p>\n * Note: may return primitives because it might be important to differentiate actual value.\n * Use {@link TypeUtils#wrapPrimitive(Class)} to box possible primitive, if required.\n *\n * @param types types to resolve\n * @param generics type generics\n * @return list of resolved types classes\n */\n public static List<Class<?>> resolveClasses(final Type[] types, final Map<String, Type> generics) {\n final List<Class<?>> params = new ArrayList<Class<?>>();\n for (Type type : types) {\n params.add(resolveClass(type, generics));\n }\n return params;\n }\n\n /**\n * In most cases {@link #resolveClass(Type, Map)} could be used instead (for simplicity). This method will\n * only return different result for wildcards inside resolved types (where generics are replaced\n * {@link #resolveTypeVariables(Type, Map)}). Also, in contrast to {@link #resolveClass(Type, Map)},\n * method will replace primitive types with wrappers (int -> Integer etc.) because this method is used mostly for\n * comparison logic and avoiding primitives simplifies it.\n * <p>\n * Wildcards are used to store raw resolution of generic declaration {@code T extends Number & Comparable}\n * (but {@code ? extends Number & Comparable} is not allowed in java). Only for this case multiple bounds\n * will be returned.\n * <p>\n * That precision may be important only for exact types compatibility logic.\n *\n * @param type type to resolve upper bounds\n * @param generics known generics\n * @return resolved upper bounds (at least one class)\n * @throws UnknownGenericException when found generic not declared on type (e.g. method generic)\n * @see TypeUtils#isAssignableBounds(Class[], Class[]) supplement check method\n */\n public static Class[] resolveUpperBounds(final Type type, final Map<String, Type> generics) {\n final Class[] res;\n if (type instanceof WildcardType) {\n final List<Class> list = new ArrayList<Class>();\n for (Type t : ((WildcardType) type).getUpperBounds()) {\n final Class<?> bound = resolveClass(t, generics);\n // possible case: T extends K & Serializable - if T unknown then it become\n // T extends Object & Serializable\n if (bound != Object.class) {\n list.add(bound);\n }\n }\n if (list.isEmpty()) {\n list.add(Object.class);\n }\n res = list.toArray(new Class[0]);\n } else {\n // get rid of primitive to simplify comparison logic\n res = new Class[]{TypeUtils.wrapPrimitive(resolveClass(type, generics))};\n }\n return res;\n }\n\n /**\n * Resolve type generics. Returned type will contain actual types instead of generic names. Most likely, returned\n * type will be different than provided: for example, original type may be {@link TypeVariable} and returned\n * will be simple {@link Class} (resolved generic value).\n * <p>\n * Special handling for {@link ExplicitTypeVariable} - this kind of type variable is not resolved and not\n * throw exception as unknown generic (thought as resolved type). This may be used for cases when type\n * variable must be preserved (like generics tracking or custom to string). In order to replace such\n * variables use {@link TypeVariableUtils#resolveAllTypeVariables(Type, Map)}.\n * <p>\n * Important: method performs re-packaging of all inner types. In some cases types could be flattened:\n * <ul>\n * <li>{@link WildcardType}: upper bounded wildcards are flattened to simple type\n * ({@code ? extends Somthing -> Something} as upper bounded wildcards are not useful at runtime. The only\n * exception is wildcard with multiple bounds (repackaged declaration {@code T extends A&B}). Wildcards with\n * Object as bound are also flattened ({@code List<? extends Object> --> List<Object>},\n * {@code List<?> --> List<Object>}, {@code List<? super Object> --> List<Object>}.\n * </li>\n * <li>{@link ParameterizedType}: type without arguments ({@code type.getActualTypeArguments().length == 0}) and\n * outer class {@code type.getOwnerType() == null} is replaced by raw class (such type most commonly appear in\n * case of {@link ru.vyarus.java.generics.resolver.util.type.instance.InstanceType} usage).\n * </li>\n * <li>{@link GenericArrayType}: if component type flatten to simple class then generic array is replaced by\n * simple class array.\n * </li>\n * </ul>\n * Re-packaging could be used to convert custom type implementation (e.g.\n * {@link ru.vyarus.java.generics.resolver.util.type.instance.InstanceType} into normal types).\n *\n * @param type type to resolve\n * @param generics root class generics mapping\n * @return resolved type\n * @throws UnknownGenericException when found generic not declared on type (e.g. method generic)\n * @see TypeVariableUtils#resolveAllTypeVariables(Type, Map)\n * @see #findVariables(Type)\n */\n public static Type resolveTypeVariables(final Type type, final Map<String, Type> generics) {\n return resolveTypeVariables(type, generics, false);\n }\n\n /**\n * Shortcut for {@link #resolveTypeVariables(Type, Map)} to process multiple types at once.\n *\n * @param types types to replace named generics in\n * @param generics known generics\n * @return types without named generics\n * @see TypeVariableUtils#resolveAllTypeVariables(Type[], Map)\n */\n public static Type[] resolveTypeVariables(final Type[] types, final Map<String, Type> generics) {\n return resolveTypeVariables(types, generics, false);\n }\n\n // for TypeVariableUtils access\n @SuppressWarnings({\"PMD.AvoidProtectedMethodInFinalClassNotExtending\",\n \"PMD.CyclomaticComplexity\",\n \"checkstyle:CyclomaticComplexity\"})\n protected static Type resolveTypeVariables(final Type type,\n final Map<String, Type> generics,\n final boolean countPreservedVariables) {\n Type resolvedGenericType = null;\n if (type instanceof TypeVariable) {\n // simple named generics resolved to target types\n resolvedGenericType = declaredGeneric((TypeVariable) type, generics);\n } else if (type instanceof ExplicitTypeVariable) {\n // special type used to preserve named generic (and differentiate from type variable)\n resolvedGenericType = declaredGeneric((ExplicitTypeVariable) type, generics, countPreservedVariables);\n } else if (type instanceof Class) {\n resolvedGenericType = type;\n } else if (type instanceof ParameterizedType) {\n // here parameterized type could shrink to class (if it has no arguments and owner class)\n resolvedGenericType = resolveParameterizedTypeVariables(\n (ParameterizedType) type, generics, countPreservedVariables);\n } else if (type instanceof GenericArrayType) {\n // here generic array could shrink to array class (if component type shrink to simple class)\n resolvedGenericType = resolveGenericArrayTypeVariables(\n (GenericArrayType) type, generics, countPreservedVariables);\n } else if (type instanceof WildcardType) {\n // here wildcard could shrink to upper type (if it has only one upper type)\n resolvedGenericType = resolveWildcardTypeVariables(\n (WildcardType) type, generics, countPreservedVariables);\n }\n return resolvedGenericType;\n }\n\n // for TypeVariableUtils access\n @SuppressWarnings(\"PMD.AvoidProtectedMethodInFinalClassNotExtending\")\n protected static Type[] resolveTypeVariables(final Type[] types,\n final Map<String, Type> generics,\n final boolean countPreservedVariables) {\n if (types.length == 0) {\n return NO_TYPES;\n }\n final Type[] resolved = new Type[types.length];\n for (int i = 0; i < types.length; i++) {\n resolved[i] = resolveTypeVariables(types[i], generics, countPreservedVariables);\n }\n return resolved;\n }\n\n /**\n * It is important to keep possible outer class generics, because they may be used in type declarations.\n * NOTE: It may be not all generics of owner type, but only visible owner generics.\n * <pre>{@code class Outer<T, K> {\n * // outer generic T hidden\n * class Inner<T> {}\n * }}</pre>\n * In order to recover possibly missed outer generics use {@code extractTypeGenerics(type, resultedMap)}\n * (may be required for proper owner type to string printing with all generics).\n *\n * @param type type\n * @param generics all type's context generics (self + outer class)\n * @return owner class generics if type is inner class or empty map if not\n */\n public static Map<String, Type> extractOwnerGenerics(final Class<?> type,\n final Map<String, Type> generics) {\n final boolean hasOwnerGenerics =\n type.isMemberClass() && type.getTypeParameters().length != generics.size();\n if (!hasOwnerGenerics) {\n return Collections.emptyMap();\n }\n final LinkedHashMap<String, Type> res = new LinkedHashMap<String, Type>(generics);\n // owner generics are all generics not mentioned in signature\n for (TypeVariable var : type.getTypeParameters()) {\n res.remove(var.getName());\n }\n return res;\n }\n\n\n /**\n * Generics declaration may contain type's generics together with outer class generics (if type is inner class).\n * Return map itself for not inner class (or if no extra generics present in map).\n * <p>\n * In case when type's generic is not mentioned in map - it will be resolved from variable declaration.\n *\n * @param type type\n * @param generics all type's context generics (self + outer class)\n * @return generics, declared on type ({@code A<T, K> -> T, K}) or empty map if no generics declared on type\n */\n public static Map<String, Type> extractTypeGenerics(final Class<?> type,\n final Map<String, Type> generics) {\n // assuming generics map always contains correct generics and may include only outer\n // so if we call it with outer type and outer only generics it will correctly detect it\n final boolean enoughGenerics = type.getTypeParameters().length == generics.size();\n if (enoughGenerics) {\n return generics;\n }\n final LinkedHashMap<String, Type> res = new LinkedHashMap<String, Type>();\n // owner generics are all generics not mentioned in signature\n for (TypeVariable var : type.getTypeParameters()) {\n final String name = var.getName();\n if (generics.containsKey(name)) {\n res.put(name, generics.get(name));\n } else {\n // case: generic not provided in map may appear with outer class generics, which\n // may incompletely present in type's generic map (class may use generics with the same name)\n res.put(name, resolveClass(var.getBounds()[0], res));\n }\n }\n return res;\n }\n\n /**\n * @param variable generic variable\n * @return declaration class or null if not supported declaration source (should be impossible)\n */\n public static Class<?> getDeclarationClass(final TypeVariable variable) {\n return getDeclarationClass(variable.getGenericDeclaration());\n }\n\n /**\n * @param source generic declaration source (could be null)\n * @return declaration class or null if not supported declaration source (should be impossible)\n */\n public static Class<?> getDeclarationClass(final GenericDeclaration source) {\n Class<?> res = null;\n if (source != null) {\n if (source instanceof Class) {\n res = (Class<?>) source;\n } else if (source instanceof Method) {\n res = ((Method) source).getDeclaringClass();\n } else if (source instanceof Constructor) {\n res = ((Constructor) source).getDeclaringClass();\n }\n }\n return res;\n }\n\n /**\n * Converts type's known generics collection into generics map, suitable for usage with the api.\n * <p>\n * Note that if provided class is inner class then outer class generics will be added to the map to avoid\n * unknown generics while using api with this map\n * (see {@link GenericsResolutionUtils#fillOuterGenerics(Type, LinkedHashMap, Map)}).\n *\n * @param type type to build generics map for\n * @param generics known generics (assumed in correct order)\n * @return map of type generics\n * @throws IllegalArgumentException if type's generics count don't match provided list\n */\n // LinkedHashMap indicates stored order, important for context\n @SuppressWarnings(\"PMD.LooseCoupling\")\n public static LinkedHashMap<String, Type> createGenericsMap(final Class<?> type,\n final List<? extends Type> generics) {\n final TypeVariable<? extends Class<?>>[] params = type.getTypeParameters();\n if (params.length != generics.size()) {\n throw new IllegalArgumentException(String.format(\n \"Can't build generics map for %s with %s because of incorrect generics count\",\n TypeToStringUtils.toStringType(type), Arrays.toString(generics.toArray())));\n }\n final LinkedHashMap<String, Type> res = new LinkedHashMap<String, Type>();\n int i = 0;\n for (TypeVariable var : params) {\n res.put(var.getName(), generics.get(i++));\n }\n // add possible outer class generics to avoid unknown generics\n return GenericsResolutionUtils.fillOuterGenerics(type, res, null);\n }\n\n /**\n * Generics visibility (from inside context class):\n * <ul>\n * <li>Generics declared on class</li>\n * <li>Generics declared on outer class (if current is inner)</li>\n * <li>Constructor generics (if inside constructor)</li>\n * <li>Method generics (if inside method)</li>\n * </ul>.\n *\n * @param type type to check\n * @param context current context class\n * @param contextScope current context scope (class, method, constructor)\n * @param contextSource context source object (required for method and constructor scopes)\n * @return first variable, containing generic not visible from current class or null if no violations\n */\n public static TypeVariable findIncompatibleVariable(final Type type,\n final Class<?> context,\n final GenericDeclarationScope contextScope,\n final GenericDeclaration contextSource) {\n TypeVariable res = null;\n for (TypeVariable var : findVariables(type)) {\n final Class<?> target = getDeclarationClass(var);\n // declaration class must be context or it's outer class (even if outer = null equals will be correct)\n if (!target.equals(context) && !target.equals(TypeUtils.getOuter(context))) {\n res = var;\n break;\n }\n // e.g. correct class, but method generic when current context represents class\n if (!contextScope.isCompatible(GenericDeclarationScope.from(var.getGenericDeclaration()))\n // e.g. method scope could match but actual methods differ\n || contextSource != var.getGenericDeclaration()) {\n res = var;\n break;\n }\n }\n return res;\n }\n\n /**\n * Order variables for consequent variables resolution (to support reverse order declaration cases).\n * E.g. {@code T extends List<K>, K, P extends Collection<T>} must be resolved as 2, 1, 3 or\n * {@code T extends List<D>, D extends Collection<P>, P} must be resolved as 3, 2, 1 or\n * {@code T extends List<D>, P, D extends Collection<P>} must be resolved as 2, 3, 1\n * (otherwise resolution will fail due to unknown generic).\n * <p>\n * Note: incomplete set of variables could be provided: method order only provided vars, ignoring all\n * other variables (assuming they are known). This allows using this method inside error handler\n * (in order to process only not recognized vars).\n *\n * @param variables variables to order\n * @return variables ordered for correct types resolution\n */\n public static List<TypeVariable> orderVariablesForResolution(final List<TypeVariable> variables) {\n final List<TypeVariable> vars = new ArrayList<TypeVariable>(variables);\n final List<String> countableNames = new ArrayList<String>();\n for (TypeVariable var : variables) {\n countableNames.add(var.getName());\n }\n final List<String> known = new ArrayList<String>();\n final List<TypeVariable> res = new ArrayList<TypeVariable>();\n // cycle will definitely end because java compiler does not allow to specify generic cycles\n while (!vars.isEmpty()) {\n final Iterator<TypeVariable> it = vars.iterator();\n while (it.hasNext()) {\n final TypeVariable var = it.next();\n boolean reject = false;\n for (Type bound : var.getBounds()) {\n // can't be empty as otherwise variables would not be here\n final List<TypeVariable> unknowns = GenericsUtils.findVariables(bound);\n for (TypeVariable unknown : unknowns) {\n if (countableNames.contains(unknown.getName()) && !known.contains(unknown.getName())) {\n reject = true;\n break;\n }\n }\n }\n if (!reject) {\n res.add(var);\n known.add(var.getName());\n it.remove();\n }\n }\n }\n\n return res;\n }\n\n /**\n * Shortcut for {@link #orderVariablesForResolution(List)} method to use for\n * {@link Class#getTypeParameters()} generics.\n *\n * @param variables variables to order\n * @return variables ordered for correct types resolution\n */\n public static List<TypeVariable> orderVariablesForResolution(final TypeVariable... variables) {\n return orderVariablesForResolution(Arrays.asList(variables));\n }\n\n /**\n * Searches for generic variable declarations in type. May be used for scope checks.\n * For example, in {@code List<T>} it will find \"T\", in {@code Some<Long, T, List<K>} \"T\" and \"K\".\n * <p>\n * Also detects preserved variables {@link ExplicitTypeVariable} (used for tracking).\n *\n * @param type type to analyze.\n * @return list of generic variables inside type or empty list\n */\n public static List<TypeVariable> findVariables(final Type type) {\n if (type instanceof Class) {\n return Collections.emptyList();\n }\n final List<TypeVariable> res = new ArrayList<TypeVariable>();\n findVariables(type, res);\n return res;\n }\n\n private static void findVariables(final Type type, final List<TypeVariable> found) {\n // note ExplicitTypeVariable is not checked as it's considered as known type\n if (type instanceof TypeVariable) {\n recordVariable((TypeVariable) type, found);\n } else if (type instanceof ExplicitTypeVariable) {\n recordVariable(((ExplicitTypeVariable) type).getDeclarationSource(), found);\n } else if (type instanceof ParameterizedType) {\n final ParameterizedType parametrizedType = (ParameterizedType) type;\n if (parametrizedType.getOwnerType() != null) {\n findVariables(parametrizedType.getOwnerType(), found);\n }\n for (Type par : parametrizedType.getActualTypeArguments()) {\n findVariables(par, found);\n }\n } else if (type instanceof GenericArrayType) {\n findVariables(((GenericArrayType) type).getGenericComponentType(), found);\n } else if (type instanceof WildcardType) {\n final WildcardType wildcard = (WildcardType) type;\n if (wildcard.getLowerBounds().length > 0) {\n // ? super\n findVariables(wildcard.getLowerBounds()[0], found);\n } else {\n // ? extends\n // in java only one bound could be defined, but here could actually be repackaged TypeVariable\n for (Type par : wildcard.getUpperBounds()) {\n findVariables(par, found);\n }\n }\n }\n }\n\n // variables could also contain variables, e.g. <T, K extends List<T>>\n private static void recordVariable(final TypeVariable var, final List<TypeVariable> found) {\n // prevent cycles\n if (!found.contains(var)) {\n found.add(var);\n for (Type type : var.getBounds()) {\n findVariables(type, found);\n }\n }\n }\n\n private static Type declaredGeneric(final TypeVariable generic, final Map<String, Type> declarations) {\n final String name = generic.getName();\n final Type result = declarations.get(name);\n if (result == null) {\n throw new UnknownGenericException(name, generic.getGenericDeclaration());\n }\n return result;\n }\n\n private static Type declaredGeneric(final ExplicitTypeVariable generic,\n final Map<String, Type> declarations,\n final boolean resolve) {\n return resolve ? declaredGeneric(generic.getDeclarationSource(), declarations) : generic;\n }\n\n /**\n * Situation when parameterized type contains 0 arguments is not normal (impossible normally, except inner\n * classes), but may appear after {@link ru.vyarus.java.generics.resolver.util.type.instance.InstanceType}\n * resolution (where parameterized type have to be used even for classes in order to store actual instance),\n * but, as we repackage type here, we don't need wrapper anymore.\n *\n * @param type type to repackage\n * @param generics known generics\n * @param countPreservedVariables true to replace {@link ExplicitTypeVariable} too\n * @return type without {@link TypeVariable}'s\n */\n private static Type resolveParameterizedTypeVariables(final ParameterizedType type,\n final Map<String, Type> generics,\n final boolean countPreservedVariables) {\n\n final boolean emptyContainerForClass = type.getActualTypeArguments().length == 0\n && type.getOwnerType() == null;\n final Type owner = type.getOwnerType() != null\n ? resolveTypeVariables(type.getOwnerType(),\n // some outer class generics could be hidden by inner class generics (same name)\n // so need IgnoreGenericsMap to use Object instead (besides these hidden generics\n // does not influence for sure inner type)\n new IgnoreGenericsMap(extractOwnerGenerics((Class) type.getRawType(), generics)))\n : null;\n return emptyContainerForClass ? type.getRawType()\n : new ParameterizedTypeImpl(type.getRawType(),\n resolveTypeVariables(type.getActualTypeArguments(), generics, countPreservedVariables), owner);\n }\n\n /**\n * Some apis (like common types {@link ru.vyarus.java.generics.resolver.util.type.CommonTypeFactory}) use\n * wildcards as a \"composite type\" (in essence, the same way as wildcards in pure variable declaration\n * like {@code T extends A & B}). But it may appear, that wildcard contains only one upper bound, which\n * is useless and could be unwrapped to this bound directly.\n * <p>\n * Note that common types resolution rely on this in order to get rid of wildcard placeholder objects.\n *\n * @param type type to repackage\n * @param generics known generics\n * @param countPreservedVariables true to replace {@link ExplicitTypeVariable} too\n * @return type without {@link TypeVariable}'s\n */\n private static Type resolveWildcardTypeVariables(final WildcardType type,\n final Map<String, Type> generics,\n final boolean countPreservedVariables) {\n final Type res;\n if (type.getLowerBounds().length > 0) {\n // only one lower bound could be (? super A)\n final Type lowerBound = resolveTypeVariables(\n type.getLowerBounds(), generics, countPreservedVariables)[0];\n // flatten <? super Object> to Object\n res = lowerBound == Object.class\n ? Object.class : WildcardTypeImpl.lower(lowerBound);\n } else {\n // could be multiple upper bounds because of named generic bounds repackage (T extends A & B)\n final Type[] upperBounds = resolveTypeVariables(type.getUpperBounds(), generics, countPreservedVariables);\n // flatten <? extends Object> (<?>) to Object and <? extends Something> to Something\n res = upperBounds.length == 1 ? upperBounds[0] : WildcardTypeImpl.upper(upperBounds);\n }\n return res;\n }\n\n /**\n * May produce array class instead of generic array type. This is possible due to wildcard or parameterized type\n * shrinking.\n *\n * @param type type to repackage\n * @param generics known generics\n * @param countPreservedVariables true to replace {@link ExplicitTypeVariable} too\n * @return type without {@link TypeVariable}'s\n */\n private static Type resolveGenericArrayTypeVariables(final GenericArrayType type,\n final Map<String, Type> generics,\n final boolean countPreservedVariables) {\n final Type componentType = resolveTypeVariables(\n type.getGenericComponentType(), generics, countPreservedVariables);\n return ArrayTypeUtils.toArrayType(componentType);\n }\n}",
"public final class TypeUtils {\n\n @SuppressWarnings({\"checkstyle:Indentation\", \"PMD.NonStaticInitializer\", \"PMD.AvoidUsingShortType\"})\n private static final Map<Class, Class> PRIMITIVES = new HashMap<Class, Class>() {{\n put(boolean.class, Boolean.class);\n put(byte.class, Byte.class);\n put(char.class, Character.class);\n put(double.class, Double.class);\n put(float.class, Float.class);\n put(int.class, Integer.class);\n put(long.class, Long.class);\n put(short.class, Short.class);\n put(void.class, Void.class);\n }};\n\n private TypeUtils() {\n }\n\n /**\n * @param type class to wrap\n * @return primitive wrapper class if provided class is primitive or class itself\n */\n public static Class<?> wrapPrimitive(final Class<?> type) {\n return type.isPrimitive() ? PRIMITIVES.get(type) : type;\n }\n\n /**\n * Checks if type is more specific than provided one. E.g. {@code ArrayList} is more specific then\n * {@code List} or {@code List<Integer>} is more specific then {@code List<Object>}.\n * <p>\n * Note that comparison logic did not follow all java rules (especially wildcards) as some rules\n * are not important at runtime.\n * <p>\n * Not resolved type variables are resolved to Object. Object is considered as unknown type: everything\n * is assignable to Object and Object is assignable to everything.\n * {@code List == List<Object> == List<?> == List<? super Object> == List<? extends Object>}.\n * <p>\n * For lower bounded wildcards more specific wildcard contains lower bound: {@code ? extends Number} is\n * more specific then {@code ? extends Integer}. Also, lower bounded wildcard is always more specific then\n * Object.\n * <p>\n * Not the same as {@link #isAssignable(Type, Type)}. For example:\n * {@code isAssignable(List, List<String>) == true}, but {@code isMoreSpecific(List, List<String>) == false}.\n * <p>\n * Primitive types are checked as wrappers (for example, int is more specific then Number).\n *\n * @param what type to check\n * @param comparingTo type to compare to\n * @return true when provided type is more specific than other type,\n * false otherwise (including when types are equal)\n * @throws IncompatibleTypesException when types are not compatible\n * @see ComparatorTypesVisitor for implementation details\n * @see #isCompatible(Type, Type) use for compatibility check (before) to avoid incompatible types exception\n * @see #isMoreSpecificOrEqual(Type, Type) for broader check\n */\n public static boolean isMoreSpecific(final Type what, final Type comparingTo) {\n if (what.equals(comparingTo)) {\n // assume correct type implementation (for faster check)\n return false;\n }\n return doMoreSpecificWalk(what, comparingTo).isMoreSpecific();\n }\n\n /**\n * Shortcut for {@link #isMoreSpecific(Type, Type)} for cases when equality is also acceptable (quite often\n * required case).\n *\n * @param what type to check\n * @param comparingTo type to compare to\n * @return true when provided type is more specific than other type or equal, false otherwise\n * @throws IncompatibleTypesException when types are not compatible\n */\n public static boolean isMoreSpecificOrEqual(final Type what, final Type comparingTo) {\n if (what.equals(comparingTo)) {\n // assume correct type implementation (for faster check)\n return true;\n }\n final ComparatorTypesVisitor visitor = doMoreSpecificWalk(what, comparingTo);\n return visitor.isMoreSpecific() || visitor.isEqual();\n }\n\n /**\n * Checks if type could be casted to type. Generally, method is supposed to answer: if this type could be tried\n * to set on that place (defined by second type). Not resolved type variables are resolved to Object. Object is\n * considered as unknown type: everything is assignable to Object and Object is assignable to everything.\n * Note that {@code T<String, Object>} is assignable to {@code T<String, String>} as Object considered as unknown\n * type and so could be compatible (in opposite way is also assignable as anything is assignable to Object).\n * <p>\n * Of course, actual value used instead of Object may be incompatible, but method intended only to\n * check all available types information (if nothing stops me yet). Use exact types to get more correct\n * result. Example usage scenario: check field type before trying to assign something with reflection.\n * <p>\n * Java wildcard rules are generally not honored because at runtime they are meaningless.\n * {@code List == List<Object> == List<? super Object> == List<? extends Object>}. All upper bounds are used for\n * comparison (multiple upper bounds in wildcard could be from repackaging of generic declaration\n * {@code T<extends A&B>}. Lower bounds are taken into account as: if both have lower bound then\n * right's type bound must be higher ({@code ? extends Number and ? extends Integer}). If only left\n * type is lower bounded wildcard then it is not assignable (except Object).\n * <p>\n * Primitive types are checked as wrappers (for example, int is more specific then Number).\n *\n * @param what type to check\n * @param toType type to check assignability for\n * @return true if types are equal or type is more specific, false if can't be casted or types incompatible\n * @see AssignabilityTypesVisitor for implementation details\n */\n public static boolean isAssignable(final Type what, final Type toType) {\n if (what.equals(toType)) {\n // assume correct type implementation (for faster check)\n return true;\n }\n final AssignabilityTypesVisitor visitor = new AssignabilityTypesVisitor();\n TypesWalker.walk(what, toType, visitor);\n\n return visitor.isAssignable();\n }\n\n /**\n * Method is useful for wildcards processing. Note that it is impossible in java to have multiple types in wildcard,\n * but generics resolver use wildcards to store multiple generic bounds from raw resolution\n * ({@code T extends Something & Comparable} stored as wildcard {@code ? extends Something & Comparable}).\n * Use only when exact precision is required, otherwise you can use just first classes from both\n * (first upper bound) as multiple bounds case is quite rare.\n * <p>\n * Bounds are assignable if all classes in right bound are assignable from any class in left bound.\n * For example,\n * <ul>\n * <li>{@code Number & SomeInterface and Number} assignable</li>\n * <li>{@code Integer & SomeInterface and Number & Comparable} assignable</li>\n * <li>{@code Integer and Number & SomeInterface} not assignable</li>\n * </ul>\n * <p>\n * Object is assumed as unknown type. Object could be assigned to any type and any type could be assigned to\n * Object. Closest analogy from java rules is no generics: for example, {@code List} without generics could be\n * assigned anywhere ({@code List<Integer> = List} - valid java code).\n * <p>\n * No primitives expected: no special wrapping performed (as supplement method\n * {@link GenericsUtils#resolveUpperBounds(Type, Map)} already handle primitives).\n *\n * @param one first bound\n * @param two second bound\n * @return true if left bound could be assigned to right bound, false otherwise\n * @see GenericsUtils#resolveUpperBounds(Type, Map) supplement bound resolution method\n */\n @SuppressWarnings({\"PMD.UseVarargs\", \"PMD.CyclomaticComplexity\", \"checkstyle:CyclomaticComplexity\"})\n public static boolean isAssignableBounds(final Class[] one, final Class[] two) {\n if (one.length == 0 || two.length == 0) {\n throw new IllegalArgumentException(String.format(\"Incomplete bounds information: %s %s\",\n Arrays.toString(one), Arrays.toString(two)));\n }\n // nothing to do for Object - it's assignable to anything\n if (!(one.length == 1 && (one[0] == Object.class\n || (ArrayTypeUtils.isArray(one[0]) && ArrayTypeUtils.getArrayComponentType(one[0]) == Object.class)))) {\n for (Class<?> twoType : two) {\n // everything is assignable to object\n if (twoType != Object.class) {\n boolean assignable = false;\n for (Class<?> oneType : one) {\n if (twoType.isAssignableFrom(oneType)) {\n assignable = true;\n break;\n }\n }\n // none on left types is assignable to this right type\n if (!assignable) {\n return false;\n }\n }\n }\n }\n\n return true;\n }\n\n /**\n * Not resolved type variables are resolved to Object.\n *\n * @param one first type\n * @param two second type\n * @return more specific type or first type if they are equal\n * @throws IncompatibleTypesException when types are not compatible\n * @see #isMoreSpecific(Type, Type)\n */\n public static Type getMoreSpecificType(final Type one, final Type two) {\n return isMoreSpecificOrEqual(one, two) ? one : two;\n }\n\n\n /**\n * Check if types are compatible: types must be equal or one extend another. Object is compatible with any type.\n * <p>\n * Not resolved type variables are resolved to Object.\n * <p>\n * Primitive types are checked as wrappers (for example, int is more specific then Number).\n *\n * @param one first type\n * @param two second type\n * @return true if types are alignable, false otherwise\n * @see TypesWalker for implementation details\n */\n public static boolean isCompatible(final Type one, final Type two) {\n final CompatibilityTypesVisitor visitor = new CompatibilityTypesVisitor();\n TypesWalker.walk(one, two, visitor);\n return visitor.isCompatible();\n }\n\n\n /**\n * <pre>{@code class Owner<T> {\n * class Inner {\n * T field; // parent generic reference\n * }\n * }}</pre>.\n *\n * @param type class to check\n * @return true when type is inner (requires outer class instance for creation), false otherwise\n */\n public static boolean isInner(final Type type) {\n if (type instanceof ParameterizedType) {\n return ((ParameterizedType) type).getOwnerType() != null;\n }\n final Class<?> actual = GenericsUtils.resolveClassIgnoringVariables(type);\n // interface is always static and can't use outer generics\n return !actual.isInterface() && actual.isMemberClass() && !Modifier.isStatic(actual.getModifiers());\n }\n\n /**\n * May return {@link ParameterizedType} if incoming type contains owner declaration like\n * {@code Outer<String>.Inner field} ({@code field.getGenericType()} will contain outer generic).\n *\n * @param type inner class (probably)\n * @return outer type or null if type is not inner class\n */\n public static Type getOuter(final Type type) {\n if (type instanceof ParameterizedType) {\n // could contain outer generics\n return ((ParameterizedType) type).getOwnerType();\n }\n return isInner(type)\n ? GenericsUtils.resolveClassIgnoringVariables(type).getEnclosingClass()\n : null;\n }\n\n /**\n * Searching for maximum type to which both types could be downcasted. For example, for {@code Integer}\n * and {@code Double} common class would be {@code ? extends Number & Comparable<Number>} (because both\n * {@code Integer} and {@code Double} extend {@code Number} and implement {@code Comparable} and so both types\n * could be downcasted to this common type).\n * <p>\n * Generics are also counted, e.g. common type for {@code List<Double>} and {@code List<Integer>} is\n * {@code List<Number & Comparable<Number>>}. Generics are tracked on all depths (in order to compute maximally\n * accurate type).\n * <p>\n * Types may be common only in implemented interfaces: e.g. for {@code class One implements Comparable}\n * and {@code class Two implements Comparable} common type would be {@code Comparable}.\n * All shared interfaces are returned as wildcard ({@link WildcardType} meaning\n * {@code ? extends BaseType & IFace1 & Iface2 }).\n * <p>\n * For returned wildcard, contained types will be sorted as: class, interface from not java package, interface\n * with generic(s), by name. So order of types will always be predictable and first upper bound will be the most\n * specific type.\n * <p>\n * Returned type is maximally accurate common type, but if you need only base class without interfaces\n * (and use interfaces only if direct base class can't be found) then you can call\n * {@code CommonTypeFactory.build(one, two, false)} directly.\n * <p>\n * Primitives are boxed for comparison (e.g. {@code int -> Integer}) so even for two {@code int} common type\n * would be {@code Integer}. The exception is primitive arrays: they can't be unboxed (because {@code int[]}\n * and {@code Integer[]} are not the same) and so the result will be {@code Object} for primitive arrays in\n * all cases except when types are equal.\n * <p>\n * NOTE: returned type will not contain variables ({@link TypeVariable}), even if provided types contain them\n * (all variables are solved to upper bound). For example, {@code List<T extends Number>} will be counted as\n * {@code List<Number>} and {@code Set<N>} as {@code Set<Object>}.\n *\n * @param one first type\n * @param two second type\n * @return maximum class assignable to both types or {@code Object} if classes are incompatible\n */\n public static Type getCommonType(final Type one, final Type two) {\n return CommonTypeFactory.build(one, two, true);\n }\n\n /**\n * Analyze provided instance and return instance type. In the simplest case it would be just\n * {@code instance.getClass()}, but with class generics resolved by upper bounds. In case of multiple instances\n * provided, it would be median type (type assignable from all instances).\n * <p>\n * The essential part is that returned type would contain original instance(s)\n * ({@link ru.vyarus.java.generics.resolver.util.type.instance.InstanceType}). So even if all type information\n * can't be resolved right now from provided instance(s), it could be done later (when some logic, aware\n * of instance types could detect it and analyze instance further). For example, container types like\n * {@link java.util.List}: initially only list class could be extracted form list instance, but logic\n * knowing what list is and so be able to extract instances can further analyze list content and so resolve\n * list generic type:\n * <pre>{@code\n * List listInstance = [12, 13.4] // integer and double\n * Type type = TypeUtils.getInstanceType(listInstance); // List<Object>\n *\n * // somewhere later where we know how to work with a list\n * if (List.class.isAssignableFrom(GenericUtils.resolveClass(type))\n * && type instanceof InstanceType) {\n * ParameterizedInstanceType ptype = type.getImprovableType(); // will be the same instance\n *\n * assert ptype.isCompleteType() == false // type not yet completely resolved\n *\n * List containedList = (List) ptype.getInstance()\n * Type innerType = TypeUtils.getInstanceType(containedList.toArray()) // ? extends Number & Comparable<Number>\n *\n * // improving list type: type changes form List<Object> to List<Number & Comparable<Number>>\n * ptype.improveAccuracy(innerType)\n * // note that we changing the original instance type so application will use more complete type in all\n * // places where this type were referenced\n *\n * assert ptype.isCompleteType() == true // type considered complete now (completely resolved)\n * }\n * }</pre>\n * <p>\n * Instance types behave as usual types and so could be used in any api required types. The only difference\n * is contained instance so logic parts aware for instance types could detect them and use instance for\n * type improvement.\n * <p>\n * Note that returned instance type will contain only not null instances. If all instances are null then\n * returned type will be simply {@code Object}, because object is assignable to anything (at least\n * {@link TypeUtils} methods assume that).\n * <p>\n * Also, if instance is an array, which does not contain non null instances, then simple array class\n * is returned (e.g. {@code TypeUtils.getInstanceType(new Integer[0]) == Integer[].class}\n *\n * @param instances instances to resolve type from\n * @return instance type for one instance and median type for multiple instances\n * @see ru.vyarus.java.generics.resolver.util.type.instance.InstanceType for more info\n */\n public static Type getInstanceType(final Object... instances) {\n return InstanceTypeFactory.build(instances);\n }\n\n private static ComparatorTypesVisitor doMoreSpecificWalk(final Type what, final Type comparingTo) {\n final ComparatorTypesVisitor visitor = new ComparatorTypesVisitor();\n TypesWalker.walk(what, comparingTo, visitor);\n\n if (!visitor.isCompatible()) {\n throw new IncompatibleTypesException(\"Type %s can't be compared to %s because they are not compatible\",\n what, comparingTo);\n }\n return visitor;\n }\n}",
"public final class IgnoreGenericsMap extends LinkedHashMap<String, Type> {\n\n private static final IgnoreGenericsMap INSTANCE = new IgnoreGenericsMap();\n\n public IgnoreGenericsMap() {\n // default\n }\n\n public IgnoreGenericsMap(final Map<? extends String, ? extends Type> m) {\n super(m);\n }\n\n @Override\n public Type get(final Object key) {\n // always Object for unknown generic name\n final Type res = super.get(key);\n return res == null ? Object.class : res;\n }\n\n @Override\n public Type put(final String key, final Type value) {\n throw new UnsupportedOperationException();\n }\n\n @Override\n public void putAll(final Map<? extends String, ? extends Type> m) {\n throw new UnsupportedOperationException();\n }\n\n /**\n * @return shared map instance\n */\n public static IgnoreGenericsMap getInstance() {\n return INSTANCE;\n }\n}"
] | import ru.vyarus.java.generics.resolver.util.ArrayTypeUtils;
import ru.vyarus.java.generics.resolver.util.GenericsResolutionUtils;
import ru.vyarus.java.generics.resolver.util.GenericsUtils;
import ru.vyarus.java.generics.resolver.util.TypeUtils;
import ru.vyarus.java.generics.resolver.util.map.IgnoreGenericsMap;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.util.Arrays;
import java.util.List;
import java.util.Map; | package ru.vyarus.java.generics.resolver.util.walk;
/**
* Deep types analysis utility.
* <p>
* Algorithm:
* <ul>
* <li>If types are not compatible - notify fail</li>
* <li>Ask visitor to continue</li>
* <li>If one if types is Object - stop</li>
* <li>Look if types are arrays and cycle with actual array type</li>
* <li>If types contains generics ({@code T<A,B>}) then align types (resolve hierarchy for upper type and
* compare generics of lower types) and cycle for each generic pair</li>
* </ul>
* <p>
* Generics rules are not honored. For example, {@code List<?>} is considered as {@code List<Object>} and
* assumed compatible with any list. {@code <? extends Something>} is considered as {@code Something} and
* compatible with any subtype.
* <p>
* The only exception is wildcard's lower bound: {@code <? super Something>} is compatible with any super type
* of {@code Something} but not compatible with any subtype.
* <p>
* If generic declares multiple bounds {@code T extends A & B} and it was not resolved with actual type
* (sub type did not declare exact generic for it), then both bounds will be used for comparison.
* <p>
* When one of types is primitive then wrapper class used instead (e.g. Integer instead of int) to simplify
* visitor logic.
* <p>
* NOTE: all variables in type ({@link java.lang.reflect.TypeVariable}) will be replaced in types into
* lower bound. If you need to preserve variables (e.g. to match variable), make them explicit with
* {@link ru.vyarus.java.generics.resolver.util.TypeVariableUtils#preserveVariables(Type)}.
*
* @author Vyacheslav Rusakov
* @since 11.05.2018
*/
public final class TypesWalker {
private static final IgnoreGenericsMap IGNORE_VARS = IgnoreGenericsMap.getInstance();
@SuppressWarnings("unchecked")
private static final List<Class<?>> STOP_TYPES = Arrays.asList(Object.class, Enum.class);
private TypesWalker() {
}
/**
* Walk will stop if visitor tells it's enough or when hierarchy incompatibility will be found.
*
* @param one first type
* @param two second type
* @param visitor visitor
*/
public static void walk(final Type one, final Type two, final TypesVisitor visitor) {
// Use possibly more specific generics (otherwise root class generics would be used as Object and this
// way it could be used as upper bound)
// Also, types could contain outer class generics declarations, which must be preserved
// e.g. (Outer<String>.Inner field).getGenericType() == ParameterizedType with parametrized owner
// Wrapped into ignore map for very specific case, when type is TypeVariable
final Map<String, Type> oneKnownGenerics = | new IgnoreGenericsMap(GenericsResolutionUtils.resolveGenerics(one, IGNORE_VARS)); | 1 |
memfis19/Annca | annca/src/main/java/io/github/memfis19/annca/internal/ui/preview/PreviewActivity.java | [
"public final class AnncaConfiguration {\n\n public static final int MEDIA_QUALITY_AUTO = 10;\n public static final int MEDIA_QUALITY_LOWEST = 15;\n public static final int MEDIA_QUALITY_LOW = 11;\n public static final int MEDIA_QUALITY_MEDIUM = 12;\n public static final int MEDIA_QUALITY_HIGH = 13;\n public static final int MEDIA_QUALITY_HIGHEST = 14;\n\n public static final int MEDIA_ACTION_VIDEO = 100;\n public static final int MEDIA_ACTION_PHOTO = 101;\n public static final int MEDIA_ACTION_UNSPECIFIED = 102;\n\n public static final int CAMERA_FACE_FRONT = 0x6;\n public static final int CAMERA_FACE_REAR = 0x7;\n\n public static final int SENSOR_POSITION_UP = 90;\n public static final int SENSOR_POSITION_UP_SIDE_DOWN = 270;\n public static final int SENSOR_POSITION_LEFT = 0;\n public static final int SENSOR_POSITION_RIGHT = 180;\n public static final int SENSOR_POSITION_UNSPECIFIED = -1;\n\n public static final int DISPLAY_ROTATION_0 = 0;\n public static final int DISPLAY_ROTATION_90 = 90;\n public static final int DISPLAY_ROTATION_180 = 180;\n public static final int DISPLAY_ROTATION_270 = 270;\n\n public static final int ORIENTATION_PORTRAIT = 0x111;\n public static final int ORIENTATION_LANDSCAPE = 0x222;\n\n public static final int FLASH_MODE_ON = 1;\n public static final int FLASH_MODE_OFF = 2;\n public static final int FLASH_MODE_AUTO = 3;\n\n public static final int PREVIEW = 1;\n public static final int CLOSE = 2;\n public static final int CONTINUE = 3;\n\n public interface Arguments {\n String REQUEST_CODE = \"io.memfis19.annca.request_code\";\n String MEDIA_ACTION = \"io.memfis19.annca.media_action\";\n String MEDIA_QUALITY = \"io.memfis19.annca.camera_media_quality\";\n String VIDEO_DURATION = \"io.memfis19.annca.video_duration\";\n String MINIMUM_VIDEO_DURATION = \"io.memfis19.annca.minimum.video_duration\";\n String VIDEO_FILE_SIZE = \"io.memfis19.annca.camera_video_file_size\";\n String FLASH_MODE = \"io.memfis19.annca.camera_flash_mode\";\n String FILE_PATH = \"io.memfis19.annca.camera_video_file_path\";\n String CAMERA_FACE = \"io.memfis19.annca.camera_face\";\n String MEDIA_RESULT_BEHAVIOUR = \"io.memfis19.annca.media_result_behaviour\";\n }\n\n @IntDef({MEDIA_QUALITY_AUTO, MEDIA_QUALITY_LOWEST, MEDIA_QUALITY_LOW, MEDIA_QUALITY_MEDIUM, MEDIA_QUALITY_HIGH, MEDIA_QUALITY_HIGHEST})\n @Retention(RetentionPolicy.SOURCE)\n public @interface MediaQuality {\n }\n\n @IntDef({PREVIEW, CLOSE, CONTINUE})\n @Retention(RetentionPolicy.SOURCE)\n public @interface MediaResultBehaviour {\n }\n\n @IntDef({MEDIA_ACTION_VIDEO, MEDIA_ACTION_PHOTO, MEDIA_ACTION_UNSPECIFIED})\n @Retention(RetentionPolicy.SOURCE)\n public @interface MediaAction {\n }\n\n @IntDef({FLASH_MODE_ON, FLASH_MODE_OFF, FLASH_MODE_AUTO})\n @Retention(RetentionPolicy.SOURCE)\n public @interface FlashMode {\n }\n\n @IntDef({CAMERA_FACE_FRONT, CAMERA_FACE_REAR})\n @Retention(RetentionPolicy.SOURCE)\n public @interface CameraFace {\n }\n\n @IntDef({SENSOR_POSITION_UP, SENSOR_POSITION_UP_SIDE_DOWN, SENSOR_POSITION_LEFT, SENSOR_POSITION_RIGHT, SENSOR_POSITION_UNSPECIFIED})\n @Retention(RetentionPolicy.SOURCE)\n public @interface SensorPosition {\n }\n\n @IntDef({DISPLAY_ROTATION_0, DISPLAY_ROTATION_90, DISPLAY_ROTATION_180, DISPLAY_ROTATION_270})\n @Retention(RetentionPolicy.SOURCE)\n public @interface DisplayRotation {\n }\n\n @IntDef({ORIENTATION_PORTRAIT, ORIENTATION_LANDSCAPE})\n @Retention(RetentionPolicy.SOURCE)\n public @interface DeviceDefaultOrientation {\n }\n\n private Activity activity = null;\n private Fragment fragment = null;\n\n private int requestCode = -1;\n\n @MediaAction\n private int mediaAction = -1;\n\n @MediaResultBehaviour\n private int mediaResultBehaviour = PREVIEW;\n\n @MediaQuality\n private int mediaQuality = -1;\n\n @CameraFace\n private int cameraFace = CAMERA_FACE_REAR;\n\n private int videoDuration = -1;\n\n private long videoFileSize = -1;\n\n private int minimumVideoDuration = -1;\n\n private String outPutFilePath = \"\";\n\n @FlashMode\n private int flashMode = FLASH_MODE_AUTO;\n\n private AnncaConfiguration(Activity activity, int requestCode) {\n this.activity = activity;\n this.requestCode = requestCode;\n }\n\n private AnncaConfiguration(@NonNull Fragment fragment, int requestCode) {\n this.fragment = fragment;\n this.requestCode = requestCode;\n }\n\n public static class Builder {\n\n private AnncaConfiguration anncaConfiguration;\n\n\n public Builder(@NonNull Activity activity, @IntRange(from = 0) int requestCode) {\n anncaConfiguration = new AnncaConfiguration(activity, requestCode);\n }\n\n public Builder(@NonNull Fragment fragment, @IntRange(from = 0) int requestCode) {\n anncaConfiguration = new AnncaConfiguration(fragment, requestCode);\n }\n\n public Builder setMediaAction(@MediaAction int mediaAction) {\n anncaConfiguration.mediaAction = mediaAction;\n return this;\n }\n\n public Builder setCameraFace(@CameraFace int cameraFace) {\n anncaConfiguration.cameraFace = cameraFace;\n return this;\n }\n\n public Builder setMediaResultBehaviour(@MediaResultBehaviour int mediaResultBehaviour) {\n anncaConfiguration.mediaResultBehaviour = mediaResultBehaviour;\n return this;\n }\n\n // TODO: 4/21/17 need to add separate destination folder and file name pattern.\n// public Builder setOutPutFilePath(String outPutFilePath) {\n// anncaConfiguration.outPutFilePath = outPutFilePath;\n// return this;\n// }\n\n public Builder setMediaQuality(@MediaQuality int mediaQuality) {\n anncaConfiguration.mediaQuality = mediaQuality;\n return this;\n }\n\n /***\n * @param videoDurationInMilliseconds - video duration in milliseconds\n * @return\n */\n public Builder setVideoDuration(@IntRange(from = 1000, to = Integer.MAX_VALUE) int videoDurationInMilliseconds) {\n anncaConfiguration.videoDuration = videoDurationInMilliseconds;\n return this;\n }\n\n /***\n * @param minimumVideoDurationInMilliseconds - minimum video duration in milliseconds, used only in video mode\n * for auto quality.\n * @return\n */\n public Builder setMinimumVideoDuration(@IntRange(from = 1000, to = Integer.MAX_VALUE) int minimumVideoDurationInMilliseconds) {\n anncaConfiguration.minimumVideoDuration = minimumVideoDurationInMilliseconds;\n return this;\n }\n\n /***\n * @param videoSizeInBytes - file size in bytes\n * @return\n */\n public Builder setVideoFileSize(@IntRange(from = 1048576, to = Long.MAX_VALUE) long videoSizeInBytes) {\n anncaConfiguration.videoFileSize = videoSizeInBytes;\n return this;\n }\n\n public Builder setFlashMode(@FlashMode int flashMode) {\n anncaConfiguration.flashMode = flashMode;\n return this;\n }\n\n public AnncaConfiguration build() throws IllegalArgumentException {\n if (anncaConfiguration.requestCode < 0)\n throw new IllegalArgumentException(\"Wrong request code value. Please set the value > 0.\");\n if (anncaConfiguration.mediaQuality == MEDIA_QUALITY_AUTO && anncaConfiguration.minimumVideoDuration < 0) {\n throw new IllegalStateException(\"Please provide minimum video duration in milliseconds to use auto quality.\");\n }\n\n return anncaConfiguration;\n }\n\n }\n\n public Activity getActivity() {\n return activity;\n }\n\n public Fragment getFragment() {\n return fragment;\n }\n\n public int getRequestCode() {\n return requestCode;\n }\n\n public int getMediaAction() {\n return mediaAction;\n }\n\n public int getMediaQuality() {\n return mediaQuality;\n }\n\n public int getCameraFace() {\n return cameraFace;\n }\n\n public int getMediaResultBehaviour() {\n return mediaResultBehaviour;\n }\n\n public String getOutPutFilePath() {\n return outPutFilePath;\n }\n\n public int getVideoDuration() {\n return videoDuration;\n }\n\n public long getVideoFileSize() {\n return videoFileSize;\n }\n\n public int getMinimumVideoDuration() {\n return minimumVideoDuration;\n }\n\n public int getFlashMode() {\n return flashMode;\n }\n}",
"public abstract class BaseAnncaActivity<CameraId> extends AnncaCameraActivity<CameraId>\n implements\n RecordButton.RecordButtonListener,\n FlashSwitchView.FlashModeSwitchListener,\n MediaActionSwitchView.OnMediaActionStateChangeListener,\n CameraSwitchView.OnCameraTypeChangeListener, CameraControlPanel.SettingsClickListener {\n\n private CameraControlPanel cameraControlPanel;\n private AlertDialog settingsDialog;\n\n protected static final int REQUEST_PREVIEW_CODE = 1001;\n\n public static final int ACTION_CONFIRM = 900;\n public static final int ACTION_RETAKE = 901;\n public static final int ACTION_CANCEL = 902;\n\n protected int requestCode = -1;\n\n @AnncaConfiguration.MediaAction\n protected int mediaAction = AnncaConfiguration.MEDIA_ACTION_UNSPECIFIED;\n @AnncaConfiguration.MediaQuality\n protected int mediaQuality = AnncaConfiguration.MEDIA_QUALITY_MEDIUM;\n @AnncaConfiguration.MediaQuality\n protected int passedMediaQuality = AnncaConfiguration.MEDIA_QUALITY_MEDIUM;\n\n @AnncaConfiguration.FlashMode\n protected int flashMode = AnncaConfiguration.FLASH_MODE_AUTO;\n\n protected CharSequence[] videoQualities;\n protected CharSequence[] photoQualities;\n\n protected int videoDuration = -1;\n protected long videoFileSize = -1;\n protected int minimumVideoDuration = -1;\n protected String filePath = \"\";\n\n @MediaActionSwitchView.MediaActionState\n protected int currentMediaActionState;\n\n @CameraSwitchView.CameraType\n protected int currentCameraType = CameraSwitchView.CAMERA_TYPE_REAR;\n\n @AnncaConfiguration.MediaResultBehaviour\n private int mediaResultBehaviour = AnncaConfiguration.PREVIEW;\n\n @AnncaConfiguration.MediaQuality\n protected int newQuality = -1;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n }\n\n @Override\n protected void onProcessBundle(Bundle savedInstanceState) {\n super.onProcessBundle(savedInstanceState);\n\n extractConfiguration(getIntent().getExtras());\n currentMediaActionState = mediaAction == AnncaConfiguration.MEDIA_ACTION_VIDEO ?\n MediaActionSwitchView.ACTION_VIDEO : MediaActionSwitchView.ACTION_PHOTO;\n }\n\n @Override\n protected void onCameraControllerReady() {\n super.onCameraControllerReady();\n\n videoQualities = getVideoQualityOptions();\n photoQualities = getPhotoQualityOptions();\n }\n\n @Override\n protected void onResume() {\n super.onResume();\n\n cameraControlPanel.lockControls();\n cameraControlPanel.allowRecord(false);\n }\n\n @Override\n protected void onPause() {\n super.onPause();\n\n cameraControlPanel.lockControls();\n cameraControlPanel.allowRecord(false);\n }\n\n private void extractConfiguration(Bundle bundle) {\n if (bundle != null) {\n if (bundle.containsKey(AnncaConfiguration.Arguments.REQUEST_CODE))\n requestCode = bundle.getInt(AnncaConfiguration.Arguments.REQUEST_CODE);\n\n if (bundle.containsKey(AnncaConfiguration.Arguments.MEDIA_ACTION)) {\n switch (bundle.getInt(AnncaConfiguration.Arguments.MEDIA_ACTION)) {\n case AnncaConfiguration.MEDIA_ACTION_PHOTO:\n mediaAction = AnncaConfiguration.MEDIA_ACTION_PHOTO;\n break;\n case AnncaConfiguration.MEDIA_ACTION_VIDEO:\n mediaAction = AnncaConfiguration.MEDIA_ACTION_VIDEO;\n break;\n default:\n mediaAction = AnncaConfiguration.MEDIA_ACTION_UNSPECIFIED;\n break;\n }\n }\n\n if (bundle.containsKey(AnncaConfiguration.Arguments.MEDIA_RESULT_BEHAVIOUR)) {\n switch (bundle.getInt(AnncaConfiguration.Arguments.MEDIA_RESULT_BEHAVIOUR)) {\n case AnncaConfiguration.CLOSE:\n mediaResultBehaviour = AnncaConfiguration.CLOSE;\n break;\n case AnncaConfiguration.PREVIEW:\n mediaResultBehaviour = AnncaConfiguration.PREVIEW;\n break;\n case AnncaConfiguration.CONTINUE:\n mediaResultBehaviour = AnncaConfiguration.CONTINUE;\n break;\n default:\n mediaResultBehaviour = AnncaConfiguration.PREVIEW;\n break;\n }\n }\n\n if (bundle.containsKey(AnncaConfiguration.Arguments.CAMERA_FACE)) {\n switch (bundle.getInt(AnncaConfiguration.Arguments.CAMERA_FACE)) {\n case AnncaConfiguration.CAMERA_FACE_FRONT:\n currentCameraType = CameraSwitchView.CAMERA_TYPE_FRONT;\n break;\n case AnncaConfiguration.CAMERA_FACE_REAR:\n currentCameraType = CameraSwitchView.CAMERA_TYPE_REAR;\n break;\n default:\n currentCameraType = CameraSwitchView.CAMERA_TYPE_REAR;\n break;\n }\n }\n\n if (bundle.containsKey(AnncaConfiguration.Arguments.FILE_PATH)) {\n filePath = bundle.getString(AnncaConfiguration.Arguments.FILE_PATH);\n }\n\n if (bundle.containsKey(AnncaConfiguration.Arguments.MEDIA_QUALITY)) {\n switch (bundle.getInt(AnncaConfiguration.Arguments.MEDIA_QUALITY)) {\n case AnncaConfiguration.MEDIA_QUALITY_AUTO:\n mediaQuality = AnncaConfiguration.MEDIA_QUALITY_AUTO;\n break;\n case AnncaConfiguration.MEDIA_QUALITY_HIGHEST:\n mediaQuality = AnncaConfiguration.MEDIA_QUALITY_HIGHEST;\n break;\n case AnncaConfiguration.MEDIA_QUALITY_HIGH:\n mediaQuality = AnncaConfiguration.MEDIA_QUALITY_HIGH;\n break;\n case AnncaConfiguration.MEDIA_QUALITY_MEDIUM:\n mediaQuality = AnncaConfiguration.MEDIA_QUALITY_MEDIUM;\n break;\n case AnncaConfiguration.MEDIA_QUALITY_LOW:\n mediaQuality = AnncaConfiguration.MEDIA_QUALITY_LOW;\n break;\n case AnncaConfiguration.MEDIA_QUALITY_LOWEST:\n mediaQuality = AnncaConfiguration.MEDIA_QUALITY_LOWEST;\n break;\n default:\n mediaQuality = AnncaConfiguration.MEDIA_QUALITY_MEDIUM;\n break;\n }\n passedMediaQuality = mediaQuality;\n }\n\n if (bundle.containsKey(AnncaConfiguration.Arguments.VIDEO_DURATION))\n videoDuration = bundle.getInt(AnncaConfiguration.Arguments.VIDEO_DURATION);\n\n if (bundle.containsKey(AnncaConfiguration.Arguments.VIDEO_FILE_SIZE))\n videoFileSize = bundle.getLong(AnncaConfiguration.Arguments.VIDEO_FILE_SIZE);\n\n if (bundle.containsKey(AnncaConfiguration.Arguments.MINIMUM_VIDEO_DURATION))\n minimumVideoDuration = bundle.getInt(AnncaConfiguration.Arguments.MINIMUM_VIDEO_DURATION);\n\n if (bundle.containsKey(AnncaConfiguration.Arguments.FLASH_MODE))\n switch (bundle.getInt(AnncaConfiguration.Arguments.FLASH_MODE)) {\n case AnncaConfiguration.FLASH_MODE_AUTO:\n flashMode = AnncaConfiguration.FLASH_MODE_AUTO;\n break;\n case AnncaConfiguration.FLASH_MODE_ON:\n flashMode = AnncaConfiguration.FLASH_MODE_ON;\n break;\n case AnncaConfiguration.FLASH_MODE_OFF:\n flashMode = AnncaConfiguration.FLASH_MODE_OFF;\n break;\n default:\n flashMode = AnncaConfiguration.FLASH_MODE_AUTO;\n break;\n }\n }\n }\n\n @Override\n protected View getUserContentView(LayoutInflater layoutInflater, ViewGroup parent) {\n cameraControlPanel = (CameraControlPanel) layoutInflater.inflate(R.layout.user_control_layout, parent, false);\n\n if (cameraControlPanel != null) {\n cameraControlPanel.setup(getMediaAction());\n\n switch (flashMode) {\n case AnncaConfiguration.FLASH_MODE_AUTO:\n cameraControlPanel.setFlasMode(FlashSwitchView.FLASH_AUTO);\n break;\n case AnncaConfiguration.FLASH_MODE_ON:\n cameraControlPanel.setFlasMode(FlashSwitchView.FLASH_ON);\n break;\n case AnncaConfiguration.FLASH_MODE_OFF:\n cameraControlPanel.setFlasMode(FlashSwitchView.FLASH_OFF);\n break;\n }\n\n cameraControlPanel.setRecordButtonListener(this);\n cameraControlPanel.setFlashModeSwitchListener(this);\n cameraControlPanel.setOnMediaActionStateChangeListener(this);\n cameraControlPanel.setOnCameraTypeChangeListener(this);\n cameraControlPanel.setMaxVideoDuration(getVideoDuration());\n cameraControlPanel.setMaxVideoFileSize(getVideoFileSize());\n cameraControlPanel.setSettingsClickListener(this);\n }\n\n return cameraControlPanel;\n }\n\n @Override\n public void onSettingsClick() {\n AlertDialog.Builder builder = new AlertDialog.Builder(this);\n\n if (currentMediaActionState == MediaActionSwitchView.ACTION_VIDEO) {\n builder.setSingleChoiceItems(videoQualities, getVideoOptionCheckedIndex(), getVideoOptionSelectedListener());\n if (getVideoFileSize() > 0)\n builder.setTitle(String.format(getString(R.string.settings_video_quality_title),\n \"(Max \" + String.valueOf(getVideoFileSize() / (1024 * 1024) + \" MB)\")));\n else\n builder.setTitle(String.format(getString(R.string.settings_video_quality_title), \"\"));\n } else {\n builder.setSingleChoiceItems(photoQualities, getPhotoOptionCheckedIndex(), getPhotoOptionSelectedListener());\n builder.setTitle(R.string.settings_photo_quality_title);\n }\n\n builder.setPositiveButton(R.string.ok_label, new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialogInterface, int i) {\n if (newQuality > 0 && newQuality != mediaQuality) {\n mediaQuality = newQuality;\n dialogInterface.dismiss();\n cameraControlPanel.lockControls();\n getCameraController().switchQuality();\n }\n }\n });\n builder.setNegativeButton(R.string.cancel_label, new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialogInterface, int i) {\n dialogInterface.dismiss();\n }\n });\n settingsDialog = builder.create();\n settingsDialog.show();\n WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();\n layoutParams.copyFrom(settingsDialog.getWindow().getAttributes());\n layoutParams.width = Utils.convertDipToPixels(this, 350);\n layoutParams.height = Utils.convertDipToPixels(this, 350);\n settingsDialog.getWindow().setAttributes(layoutParams);\n }\n\n @Override\n public void onCameraTypeChanged(@CameraSwitchView.CameraType int cameraType) {\n if (currentCameraType == cameraType) return;\n currentCameraType = cameraType;\n\n cameraControlPanel.lockControls();\n cameraControlPanel.allowRecord(false);\n\n int cameraFace = cameraType == CameraSwitchView.CAMERA_TYPE_FRONT\n ? AnncaConfiguration.CAMERA_FACE_FRONT : AnncaConfiguration.CAMERA_FACE_REAR;\n\n getCameraController().switchCamera(cameraFace);\n }\n\n @Override\n public void onFlashModeChanged(@FlashSwitchView.FlashMode int mode) {\n switch (mode) {\n case FlashSwitchView.FLASH_AUTO:\n flashMode = AnncaConfiguration.FLASH_MODE_AUTO;\n getCameraController().setFlashMode(AnncaConfiguration.FLASH_MODE_AUTO);\n break;\n case FlashSwitchView.FLASH_ON:\n flashMode = AnncaConfiguration.FLASH_MODE_ON;\n getCameraController().setFlashMode(AnncaConfiguration.FLASH_MODE_ON);\n break;\n case FlashSwitchView.FLASH_OFF:\n flashMode = AnncaConfiguration.FLASH_MODE_OFF;\n getCameraController().setFlashMode(AnncaConfiguration.FLASH_MODE_OFF);\n break;\n }\n }\n\n @Override\n public void onMediaActionChanged(int mediaActionState) {\n if (currentMediaActionState == mediaActionState) return;\n currentMediaActionState = mediaActionState;\n }\n\n @Override\n public void onTakePhotoButtonPressed() {\n getCameraController().takePhoto();\n }\n\n @Override\n public void onStartRecordingButtonPressed() {\n getCameraController().startVideoRecord();\n }\n\n @Override\n public void onStopRecordingButtonPressed() {\n getCameraController().stopVideoRecord();\n }\n\n @Override\n protected void onScreenRotation(int degrees) {\n cameraControlPanel.rotateControls(degrees);\n rotateSettingsDialog(degrees);\n }\n\n @Override\n public int getRequestCode() {\n return requestCode;\n }\n\n @Override\n public int getMediaAction() {\n return mediaAction;\n }\n\n @Override\n public int getMediaQuality() {\n return mediaQuality;\n }\n\n @Override\n public int getVideoDuration() {\n return videoDuration;\n }\n\n @Override\n public long getVideoFileSize() {\n return videoFileSize;\n }\n\n\n @Override\n public int getMinimumVideoDuration() {\n return minimumVideoDuration / 1000;\n }\n\n @Override\n public int getFlashMode() {\n return flashMode;\n }\n\n @Override\n public Activity getActivity() {\n return this;\n }\n\n @Override\n public int getCameraFace() {\n return currentCameraType;\n }\n\n @Override\n public int getMediaResultBehaviour() {\n return mediaResultBehaviour;\n }\n\n @Override\n public String getFilePath() {\n return filePath;\n }\n\n @Override\n public void updateCameraPreview(Size size, View cameraPreview) {\n cameraControlPanel.unLockControls();\n cameraControlPanel.allowRecord(true);\n\n setCameraPreview(cameraPreview, size);\n }\n\n @Override\n public void updateUiForMediaAction(@AnncaConfiguration.MediaAction int mediaAction) {\n\n }\n\n @Override\n public void updateCameraSwitcher(int numberOfCameras) {\n cameraControlPanel.allowCameraSwitching(numberOfCameras > 1);\n }\n\n @Override\n public void onPhotoTaken() {\n startPreviewActivity();\n }\n\n @Override\n public void onVideoRecordStart(int width, int height) {\n cameraControlPanel.onStartVideoRecord(getCameraController().getOutputFile());\n }\n\n @Override\n public void onVideoRecordStop() {\n cameraControlPanel.allowRecord(false);\n cameraControlPanel.onStopVideoRecord();\n startPreviewActivity();\n }\n\n @Override\n public void releaseCameraPreview() {\n clearCameraPreview();\n }\n\n private void startPreviewActivity() {\n if (mediaResultBehaviour == AnncaConfiguration.PREVIEW) {\n Intent intent = PreviewActivity.newIntent(this,\n getMediaAction(), getCameraController().getOutputFile().toString());\n startActivityForResult(intent, REQUEST_PREVIEW_CODE);\n } else if (mediaResultBehaviour == AnncaConfiguration.CONTINUE) {\n getCameraController().openCamera();\n } else if (mediaResultBehaviour == AnncaConfiguration.CLOSE) {\n finish();\n } else {\n Intent intent = PreviewActivity.newIntent(this,\n getMediaAction(), getCameraController().getOutputFile().toString());\n startActivityForResult(intent, REQUEST_PREVIEW_CODE);\n }\n }\n\n @Override\n protected void onActivityResult(int requestCode, int resultCode, Intent data) {\n if (resultCode == RESULT_OK) {\n if (requestCode == REQUEST_PREVIEW_CODE) {\n if (PreviewActivity.isResultConfirm(data)) {\n Intent resultIntent = new Intent();\n resultIntent.putExtra(AnncaConfiguration.Arguments.FILE_PATH,\n PreviewActivity.getMediaFilePatch(data));\n setResult(RESULT_OK, resultIntent);\n finish();\n } else if (PreviewActivity.isResultCancel(data)) {\n setResult(RESULT_CANCELED);\n finish();\n } else if (PreviewActivity.isResultRetake(data)) {\n //ignore, just proceed the camera\n }\n }\n }\n }\n\n private void rotateSettingsDialog(int degrees) {\n if (settingsDialog != null && settingsDialog.isShowing() && Build.VERSION.SDK_INT > 10) {\n ViewGroup dialogView = (ViewGroup) settingsDialog.getWindow().getDecorView();\n for (int i = 0; i < dialogView.getChildCount(); i++) {\n dialogView.getChildAt(i).setRotation(degrees);\n }\n }\n }\n\n protected abstract CharSequence[] getVideoQualityOptions();\n\n protected abstract CharSequence[] getPhotoQualityOptions();\n\n protected int getVideoOptionCheckedIndex() {\n int checkedIndex = -1;\n if (mediaQuality == AnncaConfiguration.MEDIA_QUALITY_AUTO) checkedIndex = 0;\n else if (mediaQuality == AnncaConfiguration.MEDIA_QUALITY_HIGH) checkedIndex = 1;\n else if (mediaQuality == AnncaConfiguration.MEDIA_QUALITY_MEDIUM) checkedIndex = 2;\n else if (mediaQuality == AnncaConfiguration.MEDIA_QUALITY_LOW) checkedIndex = 3;\n\n if (passedMediaQuality != AnncaConfiguration.MEDIA_QUALITY_AUTO) checkedIndex--;\n\n return checkedIndex;\n }\n\n protected int getPhotoOptionCheckedIndex() {\n int checkedIndex = -1;\n if (mediaQuality == AnncaConfiguration.MEDIA_QUALITY_HIGHEST) checkedIndex = 0;\n else if (mediaQuality == AnncaConfiguration.MEDIA_QUALITY_HIGH) checkedIndex = 1;\n else if (mediaQuality == AnncaConfiguration.MEDIA_QUALITY_MEDIUM) checkedIndex = 2;\n else if (mediaQuality == AnncaConfiguration.MEDIA_QUALITY_LOWEST) checkedIndex = 3;\n return checkedIndex;\n }\n\n protected DialogInterface.OnClickListener getVideoOptionSelectedListener() {\n return new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialogInterface, int index) {\n newQuality = ((VideoQualityOption) videoQualities[index]).getMediaQuality();\n }\n };\n }\n\n protected DialogInterface.OnClickListener getPhotoOptionSelectedListener() {\n return new DialogInterface.OnClickListener() {\n @Override\n public void onClick(DialogInterface dialogInterface, int index) {\n newQuality = ((PhotoQualityOption) photoQualities[index]).getMediaQuality();\n }\n };\n }\n}",
"public class AspectFrameLayout extends FrameLayout {\n\n private static final String TAG = \"AspectFrameLayout\";\n\n private double targetAspectRatio = -1.0; // initially use default window size\n\n private Size size = null;\n private int actualPreviewWidth;\n private int actualPreviewHeight;\n\n public AspectFrameLayout(Context context) {\n super(context);\n }\n\n public AspectFrameLayout(Context context, AttributeSet attrs) {\n super(context, attrs);\n }\n\n public void setAspectRatio(double aspectRatio) {\n if (aspectRatio < 0) {\n throw new IllegalArgumentException();\n }\n\n if (targetAspectRatio != aspectRatio) {\n targetAspectRatio = aspectRatio;\n requestLayout();\n }\n }\n\n @Override\n protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {\n if (size != null) {\n setMeasuredDimension(size.getWidth(), size.getHeight());\n return;\n }\n\n if (targetAspectRatio > 0) {\n int initialWidth = MeasureSpec.getSize(widthMeasureSpec);\n int initialHeight = MeasureSpec.getSize(heightMeasureSpec);\n\n // padding\n int horizontalPadding = getPaddingLeft() + getPaddingRight();\n int verticalPadding = getPaddingTop() + getPaddingBottom();\n initialWidth -= horizontalPadding;\n initialHeight -= verticalPadding;\n\n double viewAspectRatio = (double) initialWidth / initialHeight;\n double aspectDifference = targetAspectRatio / viewAspectRatio - 1;\n\n if (Math.abs(aspectDifference) < 0.01) {\n //no changes\n } else {\n if (aspectDifference > 0) {\n initialHeight = (int) (initialWidth / targetAspectRatio);\n } else {\n initialWidth = (int) (initialHeight * targetAspectRatio);\n }\n initialWidth += horizontalPadding;\n initialHeight += verticalPadding;\n widthMeasureSpec = MeasureSpec.makeMeasureSpec(initialWidth, MeasureSpec.EXACTLY);\n heightMeasureSpec = MeasureSpec.makeMeasureSpec(initialHeight, MeasureSpec.EXACTLY);\n }\n }\n super.onMeasure(widthMeasureSpec, heightMeasureSpec);\n }\n\n @Override\n protected void onLayout(boolean changed, int l, int t, int r, int b) {\n if (size != null && getChildAt(0) != null) {\n getChildAt(0).layout(0, 0, actualPreviewWidth, actualPreviewHeight);\n } else super.onLayout(changed, l, t, r, b);\n }\n\n public void setCustomSize(final Size size, Size previewSize) {\n if (targetAspectRatio <= 0) {\n getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {\n @Override\n public void onGlobalLayout() {\n getViewTreeObserver().removeGlobalOnLayoutListener(this);\n// AspectFrameLayout.this.size = size;\n\n actualPreviewWidth = getMeasuredWidth();\n actualPreviewHeight = getMeasuredHeight();\n\n if (actualPreviewHeight < actualPreviewWidth)\n AspectFrameLayout.this.size = new Size(actualPreviewHeight, actualPreviewHeight);\n else\n AspectFrameLayout.this.size = new Size(actualPreviewWidth, actualPreviewWidth);\n\n ViewGroup.LayoutParams layoutParams = getLayoutParams();\n layoutParams.width = size.getWidth();\n layoutParams.height = size.getHeight();\n\n setLayoutParams(layoutParams);\n requestLayout();\n }\n });\n setAspectRatio(previewSize.getHeight() / (double) previewSize.getWidth());\n }\n }\n\n public int getCroppSize() {\n return size.getHeight();\n }\n\n public void getCameraViewLocation(int[] location) {\n if (getChildAt(0) != null) {\n getChildAt(0).getLocationInWindow(location);\n } else getLocationInWindow(location);\n }\n}",
"public final class AnncaImageLoader {\n\n private static final String TAG = \"AnncaImageLoader\";\n\n private Context context;\n private String url;\n\n private AnncaImageLoader(Context context) {\n this.context = context;\n }\n\n public static class Builder {\n\n private AnncaImageLoader anncaImageLoader;\n\n public Builder(@NonNull Context context) {\n anncaImageLoader = new AnncaImageLoader(context);\n }\n\n public Builder load(String url) {\n anncaImageLoader.url = url;\n return this;\n }\n\n public AnncaImageLoader build() {\n return anncaImageLoader;\n }\n }\n\n public void into(final ImageView target) {\n ViewTreeObserver viewTreeObserver = target.getViewTreeObserver();\n viewTreeObserver.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {\n public boolean onPreDraw() {\n target.getViewTreeObserver().removeOnPreDrawListener(this);\n\n new ImageLoaderThread(target, url).start();\n\n return true;\n }\n });\n }\n\n private class ImageLoaderThread extends Thread {\n\n private ImageView target;\n private String url;\n private Handler mainHandler = new Handler(Looper.getMainLooper());\n\n private ImageLoaderThread(ImageView target, String url) {\n this.target = target;\n this.url = url;\n }\n\n @Override\n public void run() {\n Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);\n\n WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);\n Display display = windowManager.getDefaultDisplay();\n\n int imageViewHeight;\n int imageViewWidth;\n\n if (Build.VERSION.SDK_INT < 13) {\n imageViewHeight = display.getHeight();\n imageViewWidth = display.getWidth();\n } else {\n Point size = new Point();\n display.getSize(size);\n imageViewHeight = size.y;\n imageViewWidth = size.x;\n }\n\n// int imageViewHeight = target.getMeasuredHeight();\n// int imageViewWidth = target.getMeasuredWidth();\n\n Bitmap decodedBitmap = decodeSampledBitmapFromResource(url, imageViewWidth, imageViewHeight);\n final Bitmap resultBitmap = rotateBitmap(decodedBitmap, getExifOrientation());\n\n mainHandler.post(new Runnable() {\n @Override\n public void run() {\n target.setImageBitmap(resultBitmap);\n }\n });\n }\n\n private Bitmap rotateBitmap(Bitmap bitmap, int orientation) {\n Matrix matrix = new Matrix();\n switch (orientation) {\n case ExifInterface.ORIENTATION_NORMAL:\n return bitmap;\n case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:\n matrix.setScale(-1, 1);\n break;\n case ExifInterface.ORIENTATION_ROTATE_180:\n matrix.setRotate(180);\n break;\n case ExifInterface.ORIENTATION_FLIP_VERTICAL:\n matrix.setRotate(180);\n matrix.postScale(-1, 1);\n break;\n case ExifInterface.ORIENTATION_TRANSPOSE:\n matrix.setRotate(90);\n matrix.postScale(-1, 1);\n break;\n case ExifInterface.ORIENTATION_ROTATE_90:\n matrix.setRotate(90);\n break;\n case ExifInterface.ORIENTATION_TRANSVERSE:\n matrix.setRotate(-90);\n matrix.postScale(-1, 1);\n break;\n case ExifInterface.ORIENTATION_ROTATE_270:\n matrix.setRotate(-90);\n break;\n default:\n return bitmap;\n }\n\n try {\n Bitmap bmRotated = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);\n bitmap.recycle();\n return bmRotated;\n } catch (OutOfMemoryError ignore) {\n return null;\n }\n }\n\n private int getExifOrientation() {\n ExifInterface exif = null;\n try {\n exif = new ExifInterface(url);\n } catch (IOException ignore) {\n }\n return exif == null ? ExifInterface.ORIENTATION_UNDEFINED :\n exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);\n }\n\n private Bitmap decodeSampledBitmapFromResource(String url,\n int requestedWidth, int requestedHeight) {\n\n final BitmapFactory.Options options = new BitmapFactory.Options();\n options.inJustDecodeBounds = true;\n BitmapFactory.decodeFile(url, options);\n\n options.inSampleSize = calculateInSampleSize(options, requestedWidth, requestedHeight);\n options.inJustDecodeBounds = false;\n options.inPreferredConfig = Bitmap.Config.RGB_565;\n return BitmapFactory.decodeFile(url, options);\n }\n\n private int calculateInSampleSize(BitmapFactory.Options options,\n int requestedWidth, int requestedHeight) {\n\n final int height = options.outHeight;\n final int width = options.outWidth;\n int inSampleSize = 1;\n\n if (height > requestedHeight || width > requestedWidth) {\n\n final int halfHeight = height / inSampleSize;\n final int halfWidth = width / inSampleSize;\n\n while ((halfHeight / inSampleSize) > requestedHeight\n && (halfWidth / inSampleSize) > requestedWidth) {\n inSampleSize *= 2;\n }\n }\n return inSampleSize;\n }\n }\n\n}",
"public class Utils {\n\n public static int getDeviceDefaultOrientation(Context context) {\n WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);\n Configuration config = context.getResources().getConfiguration();\n\n int rotation = windowManager.getDefaultDisplay().getRotation();\n\n if (((rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180) &&\n config.orientation == Configuration.ORIENTATION_LANDSCAPE)\n || ((rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270) &&\n config.orientation == Configuration.ORIENTATION_PORTRAIT)) {\n return Configuration.ORIENTATION_LANDSCAPE;\n } else {\n return Configuration.ORIENTATION_PORTRAIT;\n }\n }\n\n public static String getMimeType(String url) {\n String type = \"\";\n String extension = MimeTypeMap.getFileExtensionFromUrl(url);\n if (!TextUtils.isEmpty(extension)) {\n type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);\n } else {\n String reCheckExtension = MimeTypeMap.getFileExtensionFromUrl(url.replaceAll(\"\\\\s+\", \"\"));\n if (!TextUtils.isEmpty(reCheckExtension)) {\n type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(reCheckExtension);\n }\n }\n return type;\n }\n\n public static int convertDipToPixels(Context context, int dip) {\n Resources resources = context.getResources();\n float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, resources.getDisplayMetrics());\n return (int) px;\n }\n\n}"
] | import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.TextView;
import java.io.File;
import io.github.memfis19.annca.R;
import io.github.memfis19.annca.internal.configuration.AnncaConfiguration;
import io.github.memfis19.annca.internal.ui.BaseAnncaActivity;
import io.github.memfis19.annca.internal.ui.view.AspectFrameLayout;
import io.github.memfis19.annca.internal.utils.AnncaImageLoader;
import io.github.memfis19.annca.internal.utils.Utils; | package io.github.memfis19.annca.internal.ui.preview;
/**
* Created by memfis on 7/6/16.
*/
public class PreviewActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "PreviewActivity";
private final static String MEDIA_ACTION_ARG = "media_action_arg";
private final static String FILE_PATH_ARG = "file_path_arg";
private final static String RESPONSE_CODE_ARG = "response_code_arg";
private final static String VIDEO_POSITION_ARG = "current_video_position";
private final static String VIDEO_IS_PLAYED_ARG = "is_played";
private final static String MIME_TYPE_VIDEO = "video";
private final static String MIME_TYPE_IMAGE = "image";
private int mediaAction;
private String previewFilePath;
private SurfaceView surfaceView;
private FrameLayout photoPreviewContainer;
private ImageView imagePreview;
private ViewGroup buttonPanel;
private AspectFrameLayout videoPreviewContainer;
private View cropMediaAction;
private TextView ratioChanger;
private MediaController mediaController;
private MediaPlayer mediaPlayer;
private int currentPlaybackPosition = 0;
private boolean isVideoPlaying = true;
private int currentRatioIndex = 0;
private float[] ratios;
private String[] ratioLabels;
private SurfaceHolder.Callback surfaceCallbacks = new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder holder) {
showVideoPreview(holder);
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
};
private MediaController.MediaPlayerControl MediaPlayerControlImpl = new MediaController.MediaPlayerControl() {
@Override
public void start() {
mediaPlayer.start();
}
@Override
public void pause() {
mediaPlayer.pause();
}
@Override
public int getDuration() {
return mediaPlayer.getDuration();
}
@Override
public int getCurrentPosition() {
return mediaPlayer.getCurrentPosition();
}
@Override
public void seekTo(int pos) {
mediaPlayer.seekTo(pos);
}
@Override
public boolean isPlaying() {
return mediaPlayer.isPlaying();
}
@Override
public int getBufferPercentage() {
return 0;
}
@Override
public boolean canPause() {
return true;
}
@Override
public boolean canSeekBackward() {
return true;
}
@Override
public boolean canSeekForward() {
return true;
}
@Override
public int getAudioSessionId() {
return mediaPlayer.getAudioSessionId();
}
};
public static Intent newIntent(Context context, | @AnncaConfiguration.MediaAction int mediaAction, | 0 |
monapu/monacoinj-multibit | core/src/main/java/org/multibit/store/MultiBitWalletProtobufSerializer.java | [
"public enum ConfidenceType {\n /** If BUILDING, then the transaction is included in the best chain and your confidence in it is increasing. */\n BUILDING(1),\n\n /**\n * If PENDING, then the transaction is unconfirmed and should be included shortly, as long as it is being\n * announced and is considered valid by the network. A pending transaction will be announced if the containing\n * wallet has been attached to a live {@link PeerGroup} using {@link PeerGroup#addWallet(Wallet)}.\n * You can estimate how likely the transaction is to be included by connecting to a bunch of nodes then measuring\n * how many announce it, using {@link com.google.bitcoin.core.TransactionConfidence#numBroadcastPeers()}.\n * Or if you saw it from a trusted peer, you can assume it's valid and will get mined sooner or later as well.\n */\n PENDING(2),\n\n /**\n * If DEAD, then it means the transaction won't confirm unless there is another re-org,\n * because some other transaction is spending one of its inputs. Such transactions should be alerted to the user\n * so they can take action, eg, suspending shipment of goods if they are a merchant.\n * It can also mean that a coinbase transaction has been made dead from it being moved onto a side chain.\n */\n DEAD(4),\n\n /**\n * If a transaction hasn't been broadcast yet, or there's no record of it, its confidence is UNKNOWN.\n */\n UNKNOWN(0);\n \n private int value;\n ConfidenceType(int value) {\n this.value = value;\n }\n \n public int getValue() {\n return value;\n }\n}",
"public class KeyCrypterScrypt implements KeyCrypter, Serializable {\n private static final Logger log = LoggerFactory.getLogger(KeyCrypterScrypt.class);\n private static final long serialVersionUID = 949662512049152670L;\n\n /**\n * Key length in bytes.\n */\n public static final int KEY_LENGTH = 32; // = 256 bits.\n\n /**\n * The size of an AES block in bytes.\n * This is also the length of the initialisation vector.\n */\n public static final int BLOCK_LENGTH = 16; // = 128 bits.\n\n /**\n * The length of the salt used.\n */\n public static final int SALT_LENGTH = 8;\n\n private static final transient SecureRandom secureRandom = new SecureRandom();\n\n // Scrypt parameters.\n private final transient ScryptParameters scryptParameters;\n\n /**\n * Encryption/ Decryption using default parameters and a random salt\n */\n public KeyCrypterScrypt() {\n byte[] salt = new byte[SALT_LENGTH];\n secureRandom.nextBytes(salt);\n Protos.ScryptParameters.Builder scryptParametersBuilder = Protos.ScryptParameters.newBuilder().setSalt(ByteString.copyFrom(salt));\n this.scryptParameters = scryptParametersBuilder.build();\n }\n\n /**\n * Encryption/ Decryption using specified Scrypt parameters.\n *\n * @param scryptParameters ScryptParameters to use\n * @throws NullPointerException if the scryptParameters or any of its N, R or P is null.\n */\n public KeyCrypterScrypt(ScryptParameters scryptParameters) {\n this.scryptParameters = checkNotNull(scryptParameters);\n // Check there is a non-empty salt.\n // (Some early MultiBit wallets has a missing salt so it is not a hard fail).\n if (scryptParameters.getSalt() == null\n || scryptParameters.getSalt().toByteArray() == null\n || scryptParameters.getSalt().toByteArray().length == 0) {\n log.warn(\"You are using a ScryptParameters with no salt. Your encryption may be vulnerable to a dictionary attack.\");\n }\n }\n\n /**\n * Generate AES key.\n *\n * This is a very slow operation compared to encrypt/ decrypt so it is normally worth caching the result.\n *\n * @param password The password to use in key generation\n * @return The KeyParameter containing the created AES key\n * @throws KeyCrypterException\n */\n @Override\n public KeyParameter deriveKey(CharSequence password) throws KeyCrypterException {\n byte[] passwordBytes = null;\n try {\n passwordBytes = convertToByteArray(password);\n byte[] salt = new byte[0];\n if ( scryptParameters.getSalt() != null) {\n salt = scryptParameters.getSalt().toByteArray();\n } else {\n // Warn the user that they are not using a salt.\n // (Some early MultiBit wallets had a blank salt).\n log.warn(\"You are using a ScryptParameters with no salt. Your encryption may be vulnerable to a dictionary attack.\");\n }\n\n byte[] keyBytes = SCrypt.scrypt(passwordBytes, salt, (int) scryptParameters.getN(), scryptParameters.getR(), scryptParameters.getP(), KEY_LENGTH);\n return new KeyParameter(keyBytes);\n } catch (Exception e) {\n throw new KeyCrypterException(\"Could not generate key from password and salt.\", e);\n } finally {\n // Zero the password bytes.\n if (passwordBytes != null) {\n java.util.Arrays.fill(passwordBytes, (byte) 0);\n }\n }\n }\n\n /**\n * Password based encryption using AES - CBC 256 bits.\n */\n @Override\n public EncryptedPrivateKey encrypt(byte[] plainBytes, KeyParameter aesKey) throws KeyCrypterException {\n checkNotNull(plainBytes);\n checkNotNull(aesKey);\n\n try {\n // Generate iv - each encryption call has a different iv.\n byte[] iv = new byte[BLOCK_LENGTH];\n secureRandom.nextBytes(iv);\n\n ParametersWithIV keyWithIv = new ParametersWithIV(aesKey, iv);\n\n // Encrypt using AES.\n BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));\n cipher.init(true, keyWithIv);\n byte[] encryptedBytes = new byte[cipher.getOutputSize(plainBytes.length)];\n final int length1 = cipher.processBytes(plainBytes, 0, plainBytes.length, encryptedBytes, 0);\n final int length2 = cipher.doFinal(encryptedBytes, length1);\n\n return new EncryptedPrivateKey(iv, Arrays.copyOf(encryptedBytes, length1 + length2));\n } catch (Exception e) {\n throw new KeyCrypterException(\"Could not encrypt bytes.\", e);\n }\n }\n\n /**\n * Decrypt bytes previously encrypted with this class.\n *\n * @param privateKeyToDecode The private key to decrypt\n * @param aesKey The AES key to use for decryption\n * @return The decrypted bytes\n * @throws KeyCrypterException if bytes could not be decoded to a valid key\n */\n @Override\n public byte[] decrypt(EncryptedPrivateKey privateKeyToDecode, KeyParameter aesKey) throws KeyCrypterException {\n checkNotNull(privateKeyToDecode);\n checkNotNull(aesKey);\n\n try {\n ParametersWithIV keyWithIv = new ParametersWithIV(new KeyParameter(aesKey.getKey()), privateKeyToDecode.getInitialisationVector());\n\n // Decrypt the message.\n BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CBCBlockCipher(new AESFastEngine()));\n cipher.init(false, keyWithIv);\n\n byte[] cipherBytes = privateKeyToDecode.getEncryptedBytes();\n byte[] decryptedBytes = new byte[cipher.getOutputSize(cipherBytes.length)];\n final int length1 = cipher.processBytes(cipherBytes, 0, cipherBytes.length, decryptedBytes, 0);\n final int length2 = cipher.doFinal(decryptedBytes, length1);\n\n return Arrays.copyOf(decryptedBytes, length1 + length2);\n } catch (Exception e) {\n throw new KeyCrypterException(\"Could not decrypt bytes\", e);\n }\n }\n\n /**\n * Convert a CharSequence (which are UTF16) into a byte array.\n *\n * Note: a String.getBytes() is not used to avoid creating a String of the password in the JVM.\n */\n private static byte[] convertToByteArray(CharSequence charSequence) {\n checkNotNull(charSequence);\n\n byte[] byteArray = new byte[charSequence.length() << 1];\n for(int i = 0; i < charSequence.length(); i++) {\n int bytePosition = i << 1;\n byteArray[bytePosition] = (byte) ((charSequence.charAt(i)&0xFF00)>>8);\n byteArray[bytePosition + 1] = (byte) (charSequence.charAt(i)&0x00FF);\n }\n return byteArray;\n }\n\n public ScryptParameters getScryptParameters() {\n return scryptParameters;\n }\n\n /**\n * Return the EncryptionType enum value which denotes the type of encryption/ decryption that this KeyCrypter\n * can understand.\n */\n @Override\n public EncryptionType getUnderstoodEncryptionType() {\n return EncryptionType.ENCRYPTED_SCRYPT_AES;\n }\n\n @Override\n public String toString() {\n return \"Scrypt/AES\";\n }\n\n @Override\n public int hashCode() {\n return com.google.common.base.Objects.hashCode(scryptParameters);\n }\n\n @Override\n public boolean equals(Object obj) {\n if (obj == null) {\n return false;\n }\n if (getClass() != obj.getClass()) {\n return false;\n }\n final KeyCrypterScrypt other = (KeyCrypterScrypt) obj;\n\n return com.google.common.base.Objects.equal(this.scryptParameters, other.scryptParameters);\n }\n}",
"public class Script {\n private static final Logger log = LoggerFactory.getLogger(Script.class);\n public static final long MAX_SCRIPT_ELEMENT_SIZE = 520; // bytes\n\n // The program is a set of chunks where each element is either [opcode] or [data, data, data ...]\n protected List<ScriptChunk> chunks;\n // Unfortunately, scripts are not ever re-serialized or canonicalized when used in signature hashing. Thus we\n // must preserve the exact bytes that we read off the wire, along with the parsed form.\n protected byte[] program;\n\n // Creation time of the associated keys in seconds since the epoch.\n private long creationTimeSeconds;\n\n /** Creates an empty script that serializes to nothing. */\n private Script() {\n chunks = Lists.newArrayList();\n }\n\n // Used from ScriptBuilder.\n Script(List<ScriptChunk> chunks) {\n this.chunks = Collections.unmodifiableList(new ArrayList<ScriptChunk>(chunks));\n creationTimeSeconds = Utils.currentTimeMillis() / 1000;\n }\n\n /**\n * Construct a Script that copies and wraps the programBytes array. The array is parsed and checked for syntactic\n * validity.\n * @param programBytes Array of program bytes from a transaction.\n */\n public Script(byte[] programBytes) throws ScriptException {\n program = programBytes;\n parse(programBytes);\n creationTimeSeconds = Utils.currentTimeMillis() / 1000;\n }\n\n public Script(byte[] programBytes, long creationTimeSeconds) throws ScriptException {\n program = programBytes;\n parse(programBytes);\n this.creationTimeSeconds = creationTimeSeconds;\n }\n\n public long getCreationTimeSeconds() {\n return creationTimeSeconds;\n }\n\n public void setCreationTimeSeconds(long creationTimeSeconds) {\n this.creationTimeSeconds = creationTimeSeconds;\n }\n\n /**\n * Returns the program opcodes as a string, for example \"[1234] DUP HASH160\"\n */\n public String toString() {\n StringBuilder buf = new StringBuilder();\n for (ScriptChunk chunk : chunks) {\n if (chunk.isOpCode()) {\n buf.append(getOpCodeName(chunk.data[0]));\n buf.append(\" \");\n } else {\n // Data chunk\n buf.append(\"[\");\n buf.append(bytesToHexString(chunk.data));\n buf.append(\"] \");\n }\n }\n return buf.toString().trim();\n }\n\n /** Returns the serialized program as a newly created byte array. */\n public byte[] getProgram() {\n try {\n // Don't round-trip as Satoshi's code doesn't and it would introduce a mismatch.\n if (program != null)\n return Arrays.copyOf(program, program.length);\n ByteArrayOutputStream bos = new ByteArrayOutputStream();\n for (ScriptChunk chunk : chunks) {\n chunk.write(bos);\n }\n program = bos.toByteArray();\n return program;\n } catch (IOException e) {\n throw new RuntimeException(e); // Cannot happen.\n }\n }\n\n /** Returns an immutable list of the scripts parsed form. */\n public List<ScriptChunk> getChunks() {\n return Collections.unmodifiableList(chunks);\n }\n\n private static final ScriptChunk INTERN_TABLE[];\n\n static {\n Script examplePayToAddress = ScriptBuilder.createOutputScript(new Address(MainNetParams.get(), new byte[20]));\n examplePayToAddress = new Script(examplePayToAddress.getProgram());\n INTERN_TABLE = new ScriptChunk[] {\n examplePayToAddress.chunks.get(0), // DUP\n examplePayToAddress.chunks.get(1), // HASH160\n examplePayToAddress.chunks.get(3), // EQUALVERIFY\n examplePayToAddress.chunks.get(4), // CHECKSIG\n };\n }\n\n /**\n * <p>To run a script, first we parse it which breaks it up into chunks representing pushes of data or logical\n * opcodes. Then we can run the parsed chunks.</p>\n *\n * <p>The reason for this split, instead of just interpreting directly, is to make it easier\n * to reach into a programs structure and pull out bits of data without having to run it.\n * This is necessary to render the to/from addresses of transactions in a user interface.\n * The official client does something similar.</p>\n */\n private void parse(byte[] program) throws ScriptException {\n chunks = new ArrayList<ScriptChunk>(5); // Common size.\n ByteArrayInputStream bis = new ByteArrayInputStream(program);\n int initialSize = bis.available();\n while (bis.available() > 0) {\n int startLocationInProgram = initialSize - bis.available();\n int opcode = bis.read();\n\n long dataToRead = -1;\n if (opcode >= 0 && opcode < OP_PUSHDATA1) {\n // Read some bytes of data, where how many is the opcode value itself.\n dataToRead = opcode;\n } else if (opcode == OP_PUSHDATA1) {\n if (bis.available() < 1) throw new ScriptException(\"Unexpected end of script\");\n dataToRead = bis.read();\n } else if (opcode == OP_PUSHDATA2) {\n // Read a short, then read that many bytes of data.\n if (bis.available() < 2) throw new ScriptException(\"Unexpected end of script\");\n dataToRead = bis.read() | (bis.read() << 8);\n } else if (opcode == OP_PUSHDATA4) {\n // Read a uint32, then read that many bytes of data.\n // Though this is allowed, because its value cannot be > 520, it should never actually be used\n if (bis.available() < 4) throw new ScriptException(\"Unexpected end of script\");\n dataToRead = ((long)bis.read()) | (((long)bis.read()) << 8) | (((long)bis.read()) << 16) | (((long)bis.read()) << 24);\n }\n\n ScriptChunk chunk;\n if (dataToRead == -1) {\n chunk = new ScriptChunk(true, new byte[]{(byte) opcode}, startLocationInProgram);\n } else {\n if (dataToRead > bis.available())\n throw new ScriptException(\"Push of data element that is larger than remaining data\");\n byte[] data = new byte[(int)dataToRead];\n checkState(dataToRead == 0 || bis.read(data, 0, (int)dataToRead) == dataToRead);\n chunk = new ScriptChunk(false, data, startLocationInProgram);\n }\n // Save some memory by eliminating redundant copies of the same chunk objects. INTERN_TABLE can be null\n // here because this method is called whilst setting it up.\n if (INTERN_TABLE != null) {\n for (ScriptChunk c : INTERN_TABLE) {\n if (c.equals(chunk)) chunk = c;\n }\n }\n chunks.add(chunk);\n }\n }\n\n /**\n * Returns true if this script is of the form <sig> OP_CHECKSIG. This form was originally intended for transactions\n * where the peers talked to each other directly via TCP/IP, but has fallen out of favor with time due to that mode\n * of operation being susceptible to man-in-the-middle attacks. It is still used in coinbase outputs and can be\n * useful more exotic types of transaction, but today most payments are to addresses.\n */\n public boolean isSentToRawPubKey() {\n return chunks.size() == 2 && chunks.get(1).equalsOpCode(OP_CHECKSIG) &&\n !chunks.get(0).isOpCode() && chunks.get(0).data.length > 1;\n }\n\n /**\n * Returns true if this script is of the form DUP HASH160 <pubkey hash> EQUALVERIFY CHECKSIG, ie, payment to an\n * address like 1VayNert3x1KzbpzMGt2qdqrAThiRovi8. This form was originally intended for the case where you wish\n * to send somebody money with a written code because their node is offline, but over time has become the standard\n * way to make payments due to the short and recognizable base58 form addresses come in.\n */\n public boolean isSentToAddress() {\n return chunks.size() == 5 &&\n chunks.get(0).equalsOpCode(OP_DUP) &&\n chunks.get(1).equalsOpCode(OP_HASH160) &&\n chunks.get(2).data.length == Address.LENGTH &&\n chunks.get(3).equalsOpCode(OP_EQUALVERIFY) &&\n chunks.get(4).equalsOpCode(OP_CHECKSIG);\n }\n\n /**\n * Returns true if this script is of the form OP_HASH160 <scriptHash> OP_EQUAL, ie, payment to an\n * address like 35b9vsyH1KoFT5a5KtrKusaCcPLkiSo1tU. This form was codified as part of BIP13 and BIP16,\n * for pay to script hash type addresses.\n */\n public boolean isSentToP2SH() {\n return chunks.size() == 3 &&\n chunks.get(0).equalsOpCode(OP_HASH160) &&\n chunks.get(1).data.length == Address.LENGTH &&\n chunks.get(2).equalsOpCode(OP_EQUAL);\n }\n\n /**\n * If a program matches the standard template DUP HASH160 <pubkey hash> EQUALVERIFY CHECKSIG\n * then this function retrieves the third element, otherwise it throws a ScriptException.<p>\n *\n * This is useful for fetching the destination address of a transaction.\n */\n public byte[] getPubKeyHash() throws ScriptException {\n if (isSentToAddress())\n return chunks.get(2).data;\n else if (isSentToP2SH())\n return chunks.get(1).data;\n else\n throw new ScriptException(\"Script not in the standard scriptPubKey form\");\n }\n\n /**\n * Returns the public key in this script. If a script contains two constants and nothing else, it is assumed to\n * be a scriptSig (input) for a pay-to-address output and the second constant is returned (the first is the\n * signature). If a script contains a constant and an OP_CHECKSIG opcode, the constant is returned as it is\n * assumed to be a direct pay-to-key scriptPubKey (output) and the first constant is the public key.\n *\n * @throws ScriptException if the script is none of the named forms.\n */\n public byte[] getPubKey() throws ScriptException {\n if (chunks.size() != 2) {\n throw new ScriptException(\"Script not of right size, expecting 2 but got \" + chunks.size());\n }\n if (chunks.get(0).data.length > 2 && chunks.get(1).data.length > 2) {\n // If we have two large constants assume the input to a pay-to-address output.\n return chunks.get(1).data;\n } else if (chunks.get(1).data.length == 1 && chunks.get(1).equalsOpCode(OP_CHECKSIG) && chunks.get(0).data.length > 2) {\n // A large constant followed by an OP_CHECKSIG is the key.\n return chunks.get(0).data;\n } else {\n throw new ScriptException(\"Script did not match expected form: \" + toString());\n }\n }\n\n /**\n * For 2-element [input] scripts assumes that the paid-to-address can be derived from the public key.\n * The concept of a \"from address\" isn't well defined in Bitcoin and you should not assume the sender of a\n * transaction can actually receive coins on it. This method may be removed in future.\n */\n @Deprecated\n public Address getFromAddress(NetworkParameters params) throws ScriptException {\n return new Address(params, Utils.sha256hash160(getPubKey()));\n }\n\n /**\n * Gets the destination address from this script, if it's in the required form (see getPubKey).\n */\n public Address getToAddress(NetworkParameters params) throws ScriptException {\n if (isSentToAddress())\n return new Address(params, getPubKeyHash());\n else if (isSentToP2SH())\n return Address.fromP2SHScript(params, this);\n else\n throw new ScriptException(\"Cannot cast this script to a pay-to-address type\");\n }\n\n ////////////////////// Interface for writing scripts from scratch ////////////////////////////////\n\n /**\n * Writes out the given byte buffer to the output stream with the correct opcode prefix\n * To write an integer call writeBytes(out, Utils.reverseBytes(Utils.encodeMPI(val, false)));\n */\n public static void writeBytes(OutputStream os, byte[] buf) throws IOException {\n if (buf.length < OP_PUSHDATA1) {\n os.write(buf.length);\n os.write(buf);\n } else if (buf.length < 256) {\n os.write(OP_PUSHDATA1);\n os.write(buf.length);\n os.write(buf);\n } else if (buf.length < 65536) {\n os.write(OP_PUSHDATA2);\n os.write(0xFF & (buf.length));\n os.write(0xFF & (buf.length >> 8));\n os.write(buf);\n } else {\n throw new RuntimeException(\"Unimplemented\");\n }\n }\n\n /** Creates a program that requires at least N of the given keys to sign, using OP_CHECKMULTISIG. */\n public static byte[] createMultiSigOutputScript(int threshold, List<ECKey> pubkeys) {\n checkArgument(threshold > 0);\n checkArgument(threshold <= pubkeys.size());\n checkArgument(pubkeys.size() <= 16); // That's the max we can represent with a single opcode.\n if (pubkeys.size() > 3) {\n log.warn(\"Creating a multi-signature output that is non-standard: {} pubkeys, should be <= 3\", pubkeys.size());\n }\n try {\n ByteArrayOutputStream bits = new ByteArrayOutputStream();\n bits.write(encodeToOpN(threshold));\n for (ECKey key : pubkeys) {\n writeBytes(bits, key.getPubKey());\n }\n bits.write(encodeToOpN(pubkeys.size()));\n bits.write(OP_CHECKMULTISIG);\n return bits.toByteArray();\n } catch (IOException e) {\n throw new RuntimeException(e); // Cannot happen.\n }\n }\n\n public static byte[] createInputScript(byte[] signature, byte[] pubkey) {\n try {\n // TODO: Do this by creating a Script *first* then having the script reassemble itself into bytes.\n ByteArrayOutputStream bits = new UnsafeByteArrayOutputStream(signature.length + pubkey.length + 2);\n writeBytes(bits, signature);\n writeBytes(bits, pubkey);\n return bits.toByteArray();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n public static byte[] createInputScript(byte[] signature) {\n try {\n // TODO: Do this by creating a Script *first* then having the script reassemble itself into bytes.\n ByteArrayOutputStream bits = new UnsafeByteArrayOutputStream(signature.length + 2);\n writeBytes(bits, signature);\n return bits.toByteArray();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n \n ////////////////////// Interface used during verification of transactions/blocks ////////////////////////////////\n \n private static int getSigOpCount(List<ScriptChunk> chunks, boolean accurate) throws ScriptException {\n int sigOps = 0;\n int lastOpCode = OP_INVALIDOPCODE;\n for (ScriptChunk chunk : chunks) {\n if (chunk.isOpCode()) {\n int opcode = 0xFF & chunk.data[0];\n switch (opcode) {\n case OP_CHECKSIG:\n case OP_CHECKSIGVERIFY:\n sigOps++;\n break;\n case OP_CHECKMULTISIG:\n case OP_CHECKMULTISIGVERIFY:\n if (accurate && lastOpCode >= OP_1 && lastOpCode <= OP_16)\n sigOps += decodeFromOpN(lastOpCode);\n else\n sigOps += 20;\n break;\n default:\n break;\n }\n lastOpCode = opcode;\n }\n }\n return sigOps;\n }\n\n /**\n * Converts an opcode to its int representation (including OP_1NEGATE and OP_0/OP_FALSE)\n * @throws IllegalArgumentException If the opcode is not an OP_N opcode\n */\n public static int decodeFromOpN(byte opcode) throws IllegalArgumentException {\n return decodeFromOpN((int)opcode);\n }\n static int decodeFromOpN(int opcode) {\n checkArgument((opcode == OP_0 || opcode == OP_1NEGATE) || (opcode >= OP_1 && opcode <= OP_16), \"decodeFromOpN called on non OP_N opcode\");\n if (opcode == OP_0)\n return 0;\n else if (opcode == OP_1NEGATE)\n return -1;\n else\n return opcode + 1 - OP_1;\n }\n\n static int encodeToOpN(int value) {\n checkArgument(value >= -1 && value <= 16, \"encodeToOpN called for \" + value + \" which we cannot encode in an opcode.\");\n if (value == 0)\n return OP_0;\n else if (value == -1)\n return OP_1NEGATE;\n else\n return value - 1 + OP_1;\n }\n\n /**\n * Gets the count of regular SigOps in the script program (counting multisig ops as 20)\n */\n public static int getSigOpCount(byte[] program) throws ScriptException {\n Script script = new Script();\n try {\n script.parse(program);\n } catch (ScriptException e) {\n // Ignore errors and count up to the parse-able length\n }\n return getSigOpCount(script.chunks, false);\n }\n \n /**\n * Gets the count of P2SH Sig Ops in the Script scriptSig\n */\n public static long getP2SHSigOpCount(byte[] scriptSig) throws ScriptException {\n Script script = new Script();\n try {\n script.parse(scriptSig);\n } catch (ScriptException e) {\n // Ignore errors and count up to the parse-able length\n }\n for (int i = script.chunks.size() - 1; i >= 0; i--)\n if (!script.chunks.get(i).isOpCode()) {\n Script subScript = new Script();\n subScript.parse(script.chunks.get(i).data);\n return getSigOpCount(subScript.chunks, true);\n }\n return 0;\n }\n\n /**\n * <p>Whether or not this is a scriptPubKey representing a pay-to-script-hash output. In such outputs, the logic that\n * controls reclamation is not actually in the output at all. Instead there's just a hash, and it's up to the\n * spending input to provide a program matching that hash. This rule is \"soft enforced\" by the network as it does\n * not exist in Satoshis original implementation. It means blocks containing P2SH transactions that don't match\n * correctly are considered valid, but won't be mined upon, so they'll be rapidly re-orgd out of the chain. This\n * logic is defined by <a href=\"https://github.com/bitcoin/bips/blob/master/bip-0016.mediawiki\">BIP 16</a>.</p>\n *\n * <p>bitcoinj does not support creation of P2SH transactions today. The goal of P2SH is to allow short addresses\n * even for complex scripts (eg, multi-sig outputs) so they are convenient to work with in things like QRcodes or\n * with copy/paste, and also to minimize the size of the unspent output set (which improves performance of the\n * Bitcoin system).</p>\n */\n public boolean isPayToScriptHash() {\n // We have to check against the serialized form because BIP16 defines a P2SH output using an exact byte\n // template, not the logical program structure. Thus you can have two programs that look identical when\n // printed out but one is a P2SH script and the other isn't! :(\n byte[] program = getProgram();\n return program.length == 23 &&\n (program[0] & 0xff) == OP_HASH160 &&\n (program[1] & 0xff) == 0x14 &&\n (program[22] & 0xff) == OP_EQUAL;\n }\n\n /**\n * Returns whether this script matches the format used for multisig outputs: [n] [keys...] [m] CHECKMULTISIG\n */\n public boolean isSentToMultiSig() {\n if (chunks.size() < 4) return false;\n ScriptChunk chunk = chunks.get(chunks.size() - 1);\n // Must end in OP_CHECKMULTISIG[VERIFY].\n if (!chunk.isOpCode()) return false;\n if (!(chunk.equalsOpCode(OP_CHECKMULTISIG) || chunk.equalsOpCode(OP_CHECKMULTISIGVERIFY))) return false;\n try {\n // Second to last chunk must be an OP_N opcode and there should be that many data chunks (keys).\n ScriptChunk m = chunks.get(chunks.size() - 2);\n if (!m.isOpCode()) return false;\n int numKeys = decodeFromOpN(m.data[0]);\n if (numKeys < 1 || chunks.size() != 3 + numKeys) return false;\n for (int i = 1; i < chunks.size() - 2; i++) {\n if (chunks.get(i).isOpCode()) return false;\n }\n // First chunk must be an OP_N opcode too.\n if (decodeFromOpN(chunks.get(0).data[0]) < 1) return false;\n } catch (IllegalStateException e) {\n return false; // Not an OP_N opcode.\n }\n return true;\n }\n\n private static boolean equalsRange(byte[] a, int start, byte[] b) {\n if (start + b.length > a.length)\n return false;\n for (int i = 0; i < b.length; i++)\n if (a[i + start] != b[i])\n return false;\n return true;\n }\n \n /**\n * Returns the script bytes of inputScript with all instances of the specified script object removed\n */\n public static byte[] removeAllInstancesOf(byte[] inputScript, byte[] chunkToRemove) {\n // We usually don't end up removing anything\n UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream(inputScript.length);\n\n int cursor = 0;\n while (cursor < inputScript.length) {\n boolean skip = equalsRange(inputScript, cursor, chunkToRemove);\n \n int opcode = inputScript[cursor++] & 0xFF;\n int additionalBytes = 0;\n if (opcode >= 0 && opcode < OP_PUSHDATA1) {\n additionalBytes = opcode;\n } else if (opcode == OP_PUSHDATA1) {\n additionalBytes = (0xFF & inputScript[cursor]) + 1;\n } else if (opcode == OP_PUSHDATA2) {\n additionalBytes = ((0xFF & inputScript[cursor]) |\n ((0xFF & inputScript[cursor+1]) << 8)) + 2;\n } else if (opcode == OP_PUSHDATA4) {\n additionalBytes = ((0xFF & inputScript[cursor]) |\n ((0xFF & inputScript[cursor+1]) << 8) |\n ((0xFF & inputScript[cursor+1]) << 16) |\n ((0xFF & inputScript[cursor+1]) << 24)) + 4;\n }\n if (!skip) {\n try {\n bos.write(opcode);\n bos.write(Arrays.copyOfRange(inputScript, cursor, cursor + additionalBytes));\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n cursor += additionalBytes;\n }\n return bos.toByteArray();\n }\n \n /**\n * Returns the script bytes of inputScript with all instances of the given op code removed\n */\n public static byte[] removeAllInstancesOfOp(byte[] inputScript, int opCode) {\n return removeAllInstancesOf(inputScript, new byte[] {(byte)opCode});\n }\n \n ////////////////////// Script verification and helpers ////////////////////////////////\n \n private static boolean castToBool(byte[] data) {\n for (int i = 0; i < data.length; i++)\n {\n // \"Can be negative zero\" -reference client (see OpenSSL's BN_bn2mpi)\n if (data[i] != 0)\n return !(i == data.length - 1 && (data[i] & 0xFF) == 0x80);\n }\n return false;\n }\n \n private static BigInteger castToBigInteger(byte[] chunk) throws ScriptException {\n if (chunk.length > 4)\n throw new ScriptException(\"Script attempted to use an integer larger than 4 bytes\");\n return Utils.decodeMPI(Utils.reverseBytes(chunk), false);\n }\n \n private static void executeScript(Transaction txContainingThis, long index,\n Script script, LinkedList<byte[]> stack) throws ScriptException {\n int opCount = 0;\n int lastCodeSepLocation = 0;\n \n LinkedList<byte[]> altstack = new LinkedList<byte[]>();\n LinkedList<Boolean> ifStack = new LinkedList<Boolean>();\n \n for (ScriptChunk chunk : script.chunks) {\n boolean shouldExecute = !ifStack.contains(false);\n \n if (!chunk.isOpCode()) {\n if (chunk.data.length > MAX_SCRIPT_ELEMENT_SIZE)\n throw new ScriptException(\"Attempted to push a data string larger than 520 bytes\");\n \n if (!shouldExecute)\n continue;\n \n stack.add(chunk.data);\n } else {\n int opcode = 0xFF & chunk.data[0];\n if (opcode > OP_16) {\n opCount++;\n if (opCount > 201)\n throw new ScriptException(\"More script operations than is allowed\");\n }\n \n if (opcode == OP_VERIF || opcode == OP_VERNOTIF)\n throw new ScriptException(\"Script included OP_VERIF or OP_VERNOTIF\");\n \n if (opcode == OP_CAT || opcode == OP_SUBSTR || opcode == OP_LEFT || opcode == OP_RIGHT ||\n opcode == OP_INVERT || opcode == OP_AND || opcode == OP_OR || opcode == OP_XOR ||\n opcode == OP_2MUL || opcode == OP_2DIV || opcode == OP_MUL || opcode == OP_DIV ||\n opcode == OP_MOD || opcode == OP_LSHIFT || opcode == OP_RSHIFT)\n throw new ScriptException(\"Script included a disabled Script Op.\");\n \n switch (opcode) {\n case OP_IF:\n if (!shouldExecute) {\n ifStack.add(false);\n continue;\n }\n if (stack.size() < 1)\n throw new ScriptException(\"Attempted OP_IF on an empty stack\");\n ifStack.add(castToBool(stack.pollLast()));\n continue;\n case OP_NOTIF:\n if (!shouldExecute) {\n ifStack.add(false);\n continue;\n }\n if (stack.size() < 1)\n throw new ScriptException(\"Attempted OP_NOTIF on an empty stack\");\n ifStack.add(!castToBool(stack.pollLast()));\n continue;\n case OP_ELSE:\n if (ifStack.isEmpty())\n throw new ScriptException(\"Attempted OP_ELSE without OP_IF/NOTIF\");\n ifStack.add(!ifStack.pollLast());\n continue;\n case OP_ENDIF:\n if (ifStack.isEmpty())\n throw new ScriptException(\"Attempted OP_ENDIF without OP_IF/NOTIF\");\n ifStack.pollLast();\n continue;\n }\n \n if (!shouldExecute)\n continue;\n \n switch(opcode) {\n // OP_0 is no opcode\n case OP_1NEGATE:\n stack.add(Utils.reverseBytes(Utils.encodeMPI(BigInteger.ONE.negate(), false)));\n break;\n case OP_1:\n case OP_2:\n case OP_3:\n case OP_4:\n case OP_5:\n case OP_6:\n case OP_7:\n case OP_8:\n case OP_9:\n case OP_10:\n case OP_11:\n case OP_12:\n case OP_13:\n case OP_14:\n case OP_15:\n case OP_16:\n stack.add(Utils.reverseBytes(Utils.encodeMPI(BigInteger.valueOf(decodeFromOpN(opcode)), false)));\n break;\n case OP_NOP:\n break;\n case OP_VERIFY:\n if (stack.size() < 1)\n throw new ScriptException(\"Attempted OP_VERIFY on an empty stack\");\n if (!castToBool(stack.pollLast()))\n throw new ScriptException(\"OP_VERIFY failed\");\n break;\n case OP_RETURN:\n throw new ScriptException(\"Script called OP_RETURN\");\n case OP_TOALTSTACK:\n if (stack.size() < 1)\n throw new ScriptException(\"Attempted OP_TOALTSTACK on an empty stack\");\n altstack.add(stack.pollLast());\n break;\n case OP_FROMALTSTACK:\n if (altstack.size() < 1)\n throw new ScriptException(\"Attempted OP_TOALTSTACK on an empty altstack\");\n stack.add(altstack.pollLast());\n break;\n case OP_2DROP:\n if (stack.size() < 2)\n throw new ScriptException(\"Attempted OP_2DROP on a stack with size < 2\");\n stack.pollLast();\n stack.pollLast();\n break;\n case OP_2DUP:\n if (stack.size() < 2)\n throw new ScriptException(\"Attempted OP_2DUP on a stack with size < 2\");\n Iterator<byte[]> it2DUP = stack.descendingIterator();\n byte[] OP2DUPtmpChunk2 = it2DUP.next();\n stack.add(it2DUP.next());\n stack.add(OP2DUPtmpChunk2);\n break;\n case OP_3DUP:\n if (stack.size() < 3)\n throw new ScriptException(\"Attempted OP_3DUP on a stack with size < 3\");\n Iterator<byte[]> it3DUP = stack.descendingIterator();\n byte[] OP3DUPtmpChunk3 = it3DUP.next();\n byte[] OP3DUPtmpChunk2 = it3DUP.next();\n stack.add(it3DUP.next());\n stack.add(OP3DUPtmpChunk2);\n stack.add(OP3DUPtmpChunk3);\n break;\n case OP_2OVER:\n if (stack.size() < 4)\n throw new ScriptException(\"Attempted OP_2OVER on a stack with size < 4\");\n Iterator<byte[]> it2OVER = stack.descendingIterator();\n it2OVER.next();\n it2OVER.next();\n byte[] OP2OVERtmpChunk2 = it2OVER.next();\n stack.add(it2OVER.next());\n stack.add(OP2OVERtmpChunk2);\n break;\n case OP_2ROT:\n if (stack.size() < 6)\n throw new ScriptException(\"Attempted OP_2ROT on a stack with size < 6\");\n byte[] OP2ROTtmpChunk6 = stack.pollLast();\n byte[] OP2ROTtmpChunk5 = stack.pollLast();\n byte[] OP2ROTtmpChunk4 = stack.pollLast();\n byte[] OP2ROTtmpChunk3 = stack.pollLast();\n byte[] OP2ROTtmpChunk2 = stack.pollLast();\n byte[] OP2ROTtmpChunk1 = stack.pollLast();\n stack.add(OP2ROTtmpChunk3);\n stack.add(OP2ROTtmpChunk4);\n stack.add(OP2ROTtmpChunk5);\n stack.add(OP2ROTtmpChunk6);\n stack.add(OP2ROTtmpChunk1);\n stack.add(OP2ROTtmpChunk2);\n break;\n case OP_2SWAP:\n if (stack.size() < 4)\n throw new ScriptException(\"Attempted OP_2SWAP on a stack with size < 4\");\n byte[] OP2SWAPtmpChunk4 = stack.pollLast();\n byte[] OP2SWAPtmpChunk3 = stack.pollLast();\n byte[] OP2SWAPtmpChunk2 = stack.pollLast();\n byte[] OP2SWAPtmpChunk1 = stack.pollLast();\n stack.add(OP2SWAPtmpChunk3);\n stack.add(OP2SWAPtmpChunk4);\n stack.add(OP2SWAPtmpChunk1);\n stack.add(OP2SWAPtmpChunk2);\n break;\n case OP_IFDUP:\n if (stack.size() < 1)\n throw new ScriptException(\"Attempted OP_IFDUP on an empty stack\");\n if (castToBool(stack.getLast()))\n stack.add(stack.getLast());\n break;\n case OP_DEPTH:\n stack.add(Utils.reverseBytes(Utils.encodeMPI(BigInteger.valueOf(stack.size()), false)));\n break;\n case OP_DROP:\n if (stack.size() < 1)\n throw new ScriptException(\"Attempted OP_DROP on an empty stack\");\n stack.pollLast();\n break;\n case OP_DUP:\n if (stack.size() < 1)\n throw new ScriptException(\"Attempted OP_DUP on an empty stack\");\n stack.add(stack.getLast());\n break;\n case OP_NIP:\n if (stack.size() < 2)\n throw new ScriptException(\"Attempted OP_NIP on a stack with size < 2\");\n byte[] OPNIPtmpChunk = stack.pollLast();\n stack.pollLast();\n stack.add(OPNIPtmpChunk);\n break;\n case OP_OVER:\n if (stack.size() < 2)\n throw new ScriptException(\"Attempted OP_OVER on a stack with size < 2\");\n Iterator<byte[]> itOVER = stack.descendingIterator();\n itOVER.next();\n stack.add(itOVER.next());\n break;\n case OP_PICK:\n case OP_ROLL:\n if (stack.size() < 1)\n throw new ScriptException(\"Attempted OP_PICK/OP_ROLL on an empty stack\");\n long val = castToBigInteger(stack.pollLast()).longValue();\n if (val < 0 || val >= stack.size())\n throw new ScriptException(\"OP_PICK/OP_ROLL attempted to get data deeper than stack size\");\n Iterator<byte[]> itPICK = stack.descendingIterator();\n for (long i = 0; i < val; i++)\n itPICK.next();\n byte[] OPROLLtmpChunk = itPICK.next();\n if (opcode == OP_ROLL)\n itPICK.remove();\n stack.add(OPROLLtmpChunk);\n break;\n case OP_ROT:\n if (stack.size() < 3)\n throw new ScriptException(\"Attempted OP_ROT on a stack with size < 3\");\n byte[] OPROTtmpChunk3 = stack.pollLast();\n byte[] OPROTtmpChunk2 = stack.pollLast();\n byte[] OPROTtmpChunk1 = stack.pollLast();\n stack.add(OPROTtmpChunk2);\n stack.add(OPROTtmpChunk3);\n stack.add(OPROTtmpChunk1);\n break;\n case OP_SWAP:\n case OP_TUCK:\n if (stack.size() < 2)\n throw new ScriptException(\"Attempted OP_SWAP on a stack with size < 2\");\n byte[] OPSWAPtmpChunk2 = stack.pollLast();\n byte[] OPSWAPtmpChunk1 = stack.pollLast();\n stack.add(OPSWAPtmpChunk2);\n stack.add(OPSWAPtmpChunk1);\n if (opcode == OP_TUCK)\n stack.add(OPSWAPtmpChunk2);\n break;\n case OP_CAT:\n case OP_SUBSTR:\n case OP_LEFT:\n case OP_RIGHT:\n throw new ScriptException(\"Attempted to use disabled Script Op.\");\n case OP_SIZE:\n if (stack.size() < 1)\n throw new ScriptException(\"Attempted OP_SIZE on an empty stack\");\n stack.add(Utils.reverseBytes(Utils.encodeMPI(BigInteger.valueOf(stack.getLast().length), false)));\n break;\n case OP_INVERT:\n case OP_AND:\n case OP_OR:\n case OP_XOR:\n throw new ScriptException(\"Attempted to use disabled Script Op.\");\n case OP_EQUAL:\n if (stack.size() < 2)\n throw new ScriptException(\"Attempted OP_EQUALVERIFY on a stack with size < 2\");\n stack.add(Arrays.equals(stack.pollLast(), stack.pollLast()) ? new byte[] {1} : new byte[] {0});\n break;\n case OP_EQUALVERIFY:\n if (stack.size() < 2)\n throw new ScriptException(\"Attempted OP_EQUALVERIFY on a stack with size < 2\");\n if (!Arrays.equals(stack.pollLast(), stack.pollLast()))\n throw new ScriptException(\"OP_EQUALVERIFY: non-equal data\");\n break;\n case OP_1ADD:\n case OP_1SUB:\n case OP_NEGATE:\n case OP_ABS:\n case OP_NOT:\n case OP_0NOTEQUAL:\n if (stack.size() < 1)\n throw new ScriptException(\"Attempted a numeric op on an empty stack\");\n BigInteger numericOPnum = castToBigInteger(stack.pollLast());\n \n switch (opcode) {\n case OP_1ADD:\n numericOPnum = numericOPnum.add(BigInteger.ONE);\n break;\n case OP_1SUB:\n numericOPnum = numericOPnum.subtract(BigInteger.ONE);\n break;\n case OP_NEGATE:\n numericOPnum = numericOPnum.negate();\n break;\n case OP_ABS:\n if (numericOPnum.compareTo(BigInteger.ZERO) < 0)\n numericOPnum = numericOPnum.negate();\n break;\n case OP_NOT:\n if (numericOPnum.equals(BigInteger.ZERO))\n numericOPnum = BigInteger.ONE;\n else\n numericOPnum = BigInteger.ZERO;\n break;\n case OP_0NOTEQUAL:\n if (numericOPnum.equals(BigInteger.ZERO))\n numericOPnum = BigInteger.ZERO;\n else\n numericOPnum = BigInteger.ONE;\n break;\n default:\n throw new AssertionError(\"Unreachable\");\n }\n \n stack.add(Utils.reverseBytes(Utils.encodeMPI(numericOPnum, false)));\n break;\n case OP_2MUL:\n case OP_2DIV:\n throw new ScriptException(\"Attempted to use disabled Script Op.\");\n case OP_ADD:\n case OP_SUB:\n case OP_BOOLAND:\n case OP_BOOLOR:\n case OP_NUMEQUAL:\n case OP_NUMNOTEQUAL:\n case OP_LESSTHAN:\n case OP_GREATERTHAN:\n case OP_LESSTHANOREQUAL:\n case OP_GREATERTHANOREQUAL:\n case OP_MIN:\n case OP_MAX:\n if (stack.size() < 2)\n throw new ScriptException(\"Attempted a numeric op on a stack with size < 2\");\n BigInteger numericOPnum2 = castToBigInteger(stack.pollLast());\n BigInteger numericOPnum1 = castToBigInteger(stack.pollLast());\n\n BigInteger numericOPresult;\n switch (opcode) {\n case OP_ADD:\n numericOPresult = numericOPnum1.add(numericOPnum2);\n break;\n case OP_SUB:\n numericOPresult = numericOPnum1.subtract(numericOPnum2);\n break;\n case OP_BOOLAND:\n if (!numericOPnum1.equals(BigInteger.ZERO) && !numericOPnum2.equals(BigInteger.ZERO))\n numericOPresult = BigInteger.ONE;\n else\n numericOPresult = BigInteger.ZERO;\n break;\n case OP_BOOLOR:\n if (!numericOPnum1.equals(BigInteger.ZERO) || !numericOPnum2.equals(BigInteger.ZERO))\n numericOPresult = BigInteger.ONE;\n else\n numericOPresult = BigInteger.ZERO;\n break;\n case OP_NUMEQUAL:\n if (numericOPnum1.equals(numericOPnum2))\n numericOPresult = BigInteger.ONE;\n else\n numericOPresult = BigInteger.ZERO;\n break;\n case OP_NUMNOTEQUAL:\n if (!numericOPnum1.equals(numericOPnum2))\n numericOPresult = BigInteger.ONE;\n else\n numericOPresult = BigInteger.ZERO;\n break;\n case OP_LESSTHAN:\n if (numericOPnum1.compareTo(numericOPnum2) < 0)\n numericOPresult = BigInteger.ONE;\n else\n numericOPresult = BigInteger.ZERO;\n break;\n case OP_GREATERTHAN:\n if (numericOPnum1.compareTo(numericOPnum2) > 0)\n numericOPresult = BigInteger.ONE;\n else\n numericOPresult = BigInteger.ZERO;\n break;\n case OP_LESSTHANOREQUAL:\n if (numericOPnum1.compareTo(numericOPnum2) <= 0)\n numericOPresult = BigInteger.ONE;\n else\n numericOPresult = BigInteger.ZERO;\n break;\n case OP_GREATERTHANOREQUAL:\n if (numericOPnum1.compareTo(numericOPnum2) >= 0)\n numericOPresult = BigInteger.ONE;\n else\n numericOPresult = BigInteger.ZERO;\n break;\n case OP_MIN:\n if (numericOPnum1.compareTo(numericOPnum2) < 0)\n numericOPresult = numericOPnum1;\n else\n numericOPresult = numericOPnum2;\n break;\n case OP_MAX:\n if (numericOPnum1.compareTo(numericOPnum2) > 0)\n numericOPresult = numericOPnum1;\n else\n numericOPresult = numericOPnum2;\n break;\n default:\n throw new RuntimeException(\"Opcode switched at runtime?\");\n }\n \n stack.add(Utils.reverseBytes(Utils.encodeMPI(numericOPresult, false)));\n break;\n case OP_MUL:\n case OP_DIV:\n case OP_MOD:\n case OP_LSHIFT:\n case OP_RSHIFT:\n throw new ScriptException(\"Attempted to use disabled Script Op.\");\n case OP_NUMEQUALVERIFY:\n if (stack.size() < 2)\n throw new ScriptException(\"Attempted OP_NUMEQUALVERIFY on a stack with size < 2\");\n BigInteger OPNUMEQUALVERIFYnum2 = castToBigInteger(stack.pollLast());\n BigInteger OPNUMEQUALVERIFYnum1 = castToBigInteger(stack.pollLast());\n \n if (!OPNUMEQUALVERIFYnum1.equals(OPNUMEQUALVERIFYnum2))\n throw new ScriptException(\"OP_NUMEQUALVERIFY failed\");\n break;\n case OP_WITHIN:\n if (stack.size() < 3)\n throw new ScriptException(\"Attempted OP_WITHIN on a stack with size < 3\");\n BigInteger OPWITHINnum3 = castToBigInteger(stack.pollLast());\n BigInteger OPWITHINnum2 = castToBigInteger(stack.pollLast());\n BigInteger OPWITHINnum1 = castToBigInteger(stack.pollLast());\n if (OPWITHINnum2.compareTo(OPWITHINnum1) <= 0 && OPWITHINnum1.compareTo(OPWITHINnum3) < 0)\n stack.add(Utils.reverseBytes(Utils.encodeMPI(BigInteger.ONE, false)));\n else\n stack.add(Utils.reverseBytes(Utils.encodeMPI(BigInteger.ZERO, false)));\n break;\n case OP_RIPEMD160:\n if (stack.size() < 1)\n throw new ScriptException(\"Attempted OP_RIPEMD160 on an empty stack\");\n RIPEMD160Digest digest = new RIPEMD160Digest();\n byte[] dataToHash = stack.pollLast();\n digest.update(dataToHash, 0, dataToHash.length);\n byte[] ripmemdHash = new byte[20];\n digest.doFinal(ripmemdHash, 0);\n stack.add(ripmemdHash);\n break;\n case OP_SHA1:\n if (stack.size() < 1)\n throw new ScriptException(\"Attempted OP_SHA1 on an empty stack\");\n try {\n stack.add(MessageDigest.getInstance(\"SHA-1\").digest(stack.pollLast()));\n } catch (NoSuchAlgorithmException e) {\n throw new RuntimeException(e); // Cannot happen.\n }\n break;\n case OP_SHA256:\n if (stack.size() < 1)\n throw new ScriptException(\"Attempted OP_SHA256 on an empty stack\");\n try {\n stack.add(MessageDigest.getInstance(\"SHA-256\").digest(stack.pollLast()));\n } catch (NoSuchAlgorithmException e) {\n throw new RuntimeException(e); // Cannot happen.\n }\n break;\n case OP_HASH160:\n if (stack.size() < 1)\n throw new ScriptException(\"Attempted OP_HASH160 on an empty stack\");\n stack.add(Utils.sha256hash160(stack.pollLast()));\n break;\n case OP_HASH256:\n if (stack.size() < 1)\n throw new ScriptException(\"Attempted OP_SHA256 on an empty stack\");\n stack.add(Utils.doubleDigest(stack.pollLast()));\n break;\n case OP_CODESEPARATOR:\n lastCodeSepLocation = chunk.getStartLocationInProgram() + 1;\n break;\n case OP_CHECKSIG:\n case OP_CHECKSIGVERIFY:\n executeCheckSig(txContainingThis, (int) index, script, stack, lastCodeSepLocation, opcode);\n break;\n case OP_CHECKMULTISIG:\n case OP_CHECKMULTISIGVERIFY:\n opCount = executeMultiSig(txContainingThis, (int) index, script, stack, opCount, lastCodeSepLocation, opcode);\n break;\n case OP_NOP1:\n case OP_NOP2:\n case OP_NOP3:\n case OP_NOP4:\n case OP_NOP5:\n case OP_NOP6:\n case OP_NOP7:\n case OP_NOP8:\n case OP_NOP9:\n case OP_NOP10:\n break;\n \n default:\n throw new ScriptException(\"Script used a reserved opcode \" + opcode);\n }\n }\n \n if (stack.size() + altstack.size() > 1000 || stack.size() + altstack.size() < 0)\n throw new ScriptException(\"Stack size exceeded range\");\n }\n \n if (!ifStack.isEmpty())\n throw new ScriptException(\"OP_IF/OP_NOTIF without OP_ENDIF\");\n }\n\n private static void executeCheckSig(Transaction txContainingThis, int index, Script script, LinkedList<byte[]> stack,\n int lastCodeSepLocation, int opcode) throws ScriptException {\n if (stack.size() < 2)\n throw new ScriptException(\"Attempted OP_CHECKSIG(VERIFY) on a stack with size < 2\");\n byte[] pubKey = stack.pollLast();\n byte[] sigBytes = stack.pollLast();\n\n byte[] prog = script.getProgram();\n byte[] connectedScript = Arrays.copyOfRange(prog, lastCodeSepLocation, prog.length);\n\n UnsafeByteArrayOutputStream outStream = new UnsafeByteArrayOutputStream(sigBytes.length + 1);\n try {\n writeBytes(outStream, sigBytes);\n } catch (IOException e) {\n throw new RuntimeException(e); // Cannot happen\n }\n connectedScript = removeAllInstancesOf(connectedScript, outStream.toByteArray());\n\n // TODO: Use int for indexes everywhere, we can't have that many inputs/outputs\n boolean sigValid = false;\n try {\n TransactionSignature sig = TransactionSignature.decodeFromBitcoin(sigBytes, false);\n Sha256Hash hash = txContainingThis.hashForSignature(index, connectedScript, (byte) sig.sighashFlags);\n sigValid = ECKey.verify(hash.getBytes(), sig, pubKey);\n } catch (Exception e1) {\n // There is (at least) one exception that could be hit here (EOFException, if the sig is too short)\n // Because I can't verify there aren't more, we use a very generic Exception catch\n log.warn(e1.toString());\n }\n\n if (opcode == OP_CHECKSIG)\n stack.add(sigValid ? new byte[] {1} : new byte[] {0});\n else if (opcode == OP_CHECKSIGVERIFY)\n if (!sigValid)\n throw new ScriptException(\"Script failed OP_CHECKSIGVERIFY\");\n }\n\n private static int executeMultiSig(Transaction txContainingThis, int index, Script script, LinkedList<byte[]> stack,\n int opCount, int lastCodeSepLocation, int opcode) throws ScriptException {\n if (stack.size() < 2)\n throw new ScriptException(\"Attempted OP_CHECKMULTISIG(VERIFY) on a stack with size < 2\");\n int pubKeyCount = castToBigInteger(stack.pollLast()).intValue();\n if (pubKeyCount < 0 || pubKeyCount > 20)\n throw new ScriptException(\"OP_CHECKMULTISIG(VERIFY) with pubkey count out of range\");\n opCount += pubKeyCount;\n if (opCount > 201)\n throw new ScriptException(\"Total op count > 201 during OP_CHECKMULTISIG(VERIFY)\");\n if (stack.size() < pubKeyCount + 1)\n throw new ScriptException(\"Attempted OP_CHECKMULTISIG(VERIFY) on a stack with size < num_of_pubkeys + 2\");\n\n LinkedList<byte[]> pubkeys = new LinkedList<byte[]>();\n for (int i = 0; i < pubKeyCount; i++) {\n byte[] pubKey = stack.pollLast();\n pubkeys.add(pubKey);\n }\n\n int sigCount = castToBigInteger(stack.pollLast()).intValue();\n if (sigCount < 0 || sigCount > pubKeyCount)\n throw new ScriptException(\"OP_CHECKMULTISIG(VERIFY) with sig count out of range\");\n if (stack.size() < sigCount + 1)\n throw new ScriptException(\"Attempted OP_CHECKMULTISIG(VERIFY) on a stack with size < num_of_pubkeys + num_of_signatures + 3\");\n\n LinkedList<byte[]> sigs = new LinkedList<byte[]>();\n for (int i = 0; i < sigCount; i++) {\n byte[] sig = stack.pollLast();\n sigs.add(sig);\n }\n\n byte[] prog = script.getProgram();\n byte[] connectedScript = Arrays.copyOfRange(prog, lastCodeSepLocation, prog.length);\n\n for (byte[] sig : sigs) {\n UnsafeByteArrayOutputStream outStream = new UnsafeByteArrayOutputStream(sig.length + 1);\n try {\n writeBytes(outStream, sig);\n } catch (IOException e) {\n throw new RuntimeException(e); // Cannot happen\n }\n connectedScript = removeAllInstancesOf(connectedScript, outStream.toByteArray());\n }\n\n boolean valid = true;\n while (sigs.size() > 0) {\n byte[] pubKey = pubkeys.pollFirst();\n // We could reasonably move this out of the loop, but because signature verification is significantly\n // more expensive than hashing, its not a big deal.\n try {\n TransactionSignature sig = TransactionSignature.decodeFromBitcoin(sigs.getFirst(), false);\n Sha256Hash hash = txContainingThis.hashForSignature(index, connectedScript, (byte) sig.sighashFlags);\n if (ECKey.verify(hash.getBytes(), sig, pubKey))\n sigs.pollFirst();\n } catch (Exception e) {\n // There is (at least) one exception that could be hit here (EOFException, if the sig is too short)\n // Because I can't verify there aren't more, we use a very generic Exception catch\n }\n\n if (sigs.size() > pubkeys.size()) {\n valid = false;\n break;\n }\n }\n\n // We uselessly remove a stack object to emulate a reference client bug.\n stack.pollLast();\n\n if (opcode == OP_CHECKMULTISIG) {\n stack.add(valid ? new byte[] {1} : new byte[] {0});\n } else if (opcode == OP_CHECKMULTISIGVERIFY) {\n if (!valid)\n throw new ScriptException(\"Script failed OP_CHECKMULTISIGVERIFY\");\n }\n return opCount;\n }\n\n /**\n * Verifies that this script (interpreted as a scriptSig) correctly spends the given scriptPubKey.\n * @param txContainingThis The transaction in which this input scriptSig resides.\n * Accessing txContainingThis from another thread while this method runs results in undefined behavior.\n * @param scriptSigIndex The index in txContainingThis of the scriptSig (note: NOT the index of the scriptPubKey).\n * @param scriptPubKey The connected scriptPubKey containing the conditions needed to claim the value.\n * @param enforceP2SH Whether \"pay to script hash\" rules should be enforced. If in doubt, set to true.\n */\n public void correctlySpends(Transaction txContainingThis, long scriptSigIndex, Script scriptPubKey,\n boolean enforceP2SH) throws ScriptException {\n // Clone the transaction because executing the script involves editing it, and if we die, we'll leave\n // the tx half broken (also it's not so thread safe to work on it directly.\n try {\n txContainingThis = new Transaction(txContainingThis.getParams(), txContainingThis.bitcoinSerialize());\n } catch (ProtocolException e) {\n throw new RuntimeException(e); // Should not happen unless we were given a totally broken transaction.\n }\n if (getProgram().length > 10000 || scriptPubKey.getProgram().length > 10000)\n throw new ScriptException(\"Script larger than 10,000 bytes\");\n \n LinkedList<byte[]> stack = new LinkedList<byte[]>();\n LinkedList<byte[]> p2shStack = null;\n \n executeScript(txContainingThis, scriptSigIndex, this, stack);\n if (enforceP2SH)\n p2shStack = new LinkedList<byte[]>(stack);\n executeScript(txContainingThis, scriptSigIndex, scriptPubKey, stack);\n \n if (stack.size() == 0)\n throw new ScriptException(\"Stack empty at end of script execution.\");\n \n if (!castToBool(stack.pollLast()))\n throw new ScriptException(\"Script resulted in a non-true stack: \" + stack);\n\n // P2SH is pay to script hash. It means that the scriptPubKey has a special form which is a valid\n // program but it has \"useless\" form that if evaluated as a normal program always returns true.\n // Instead, miners recognize it as special based on its template - it provides a hash of the real scriptPubKey\n // and that must be provided by the input. The goal of this bizarre arrangement is twofold:\n //\n // (1) You can sum up a large, complex script (like a CHECKMULTISIG script) with an address that's the same\n // size as a regular address. This means it doesn't overload scannable QR codes/NFC tags or become\n // un-wieldy to copy/paste.\n // (2) It allows the working set to be smaller: nodes perform best when they can store as many unspent outputs\n // in RAM as possible, so if the outputs are made smaller and the inputs get bigger, then it's better for\n // overall scalability and performance.\n\n // TODO: Check if we can take out enforceP2SH if there's a checkpoint at the enforcement block.\n if (enforceP2SH && scriptPubKey.isPayToScriptHash()) {\n for (ScriptChunk chunk : chunks)\n if (chunk.isOpCode() && (chunk.data[0] & 0xff) > OP_16)\n throw new ScriptException(\"Attempted to spend a P2SH scriptPubKey with a script that contained script ops\");\n \n byte[] scriptPubKeyBytes = p2shStack.pollLast();\n Script scriptPubKeyP2SH = new Script(scriptPubKeyBytes);\n \n executeScript(txContainingThis, scriptSigIndex, scriptPubKeyP2SH, p2shStack);\n \n if (p2shStack.size() == 0)\n throw new ScriptException(\"P2SH stack empty at end of script execution.\");\n \n if (!castToBool(p2shStack.pollLast()))\n throw new ScriptException(\"P2SH script execution resulted in a non-true stack\");\n }\n }\n\n // Utility that doesn't copy for internal use\n private byte[] getQuickProgram() {\n if (program != null)\n return program;\n return getProgram();\n }\n\n @Override\n public boolean equals(Object obj) {\n if (!(obj instanceof Script))\n return false;\n Script s = (Script)obj;\n return Arrays.equals(getQuickProgram(), s.getQuickProgram());\n }\n\n @Override\n public int hashCode() {\n byte[] bytes = getQuickProgram();\n return Arrays.hashCode(bytes);\n }\n}",
"public final class Protos {\n private Protos() {}\n public static void registerAllExtensions(\n com.google.protobuf.ExtensionRegistry registry) {\n }\n public interface PeerAddressOrBuilder\n extends com.google.protobuf.MessageOrBuilder {\n\n // required bytes ip_address = 1;\n /**\n * <code>required bytes ip_address = 1;</code>\n */\n boolean hasIpAddress();\n /**\n * <code>required bytes ip_address = 1;</code>\n */\n com.google.protobuf.ByteString getIpAddress();\n\n // required uint32 port = 2;\n /**\n * <code>required uint32 port = 2;</code>\n */\n boolean hasPort();\n /**\n * <code>required uint32 port = 2;</code>\n */\n int getPort();\n\n // required uint64 services = 3;\n /**\n * <code>required uint64 services = 3;</code>\n */\n boolean hasServices();\n /**\n * <code>required uint64 services = 3;</code>\n */\n long getServices();\n }\n /**\n * Protobuf type {@code wallet.PeerAddress}\n */\n public static final class PeerAddress extends\n com.google.protobuf.GeneratedMessage\n implements PeerAddressOrBuilder {\n // Use PeerAddress.newBuilder() to construct.\n private PeerAddress(com.google.protobuf.GeneratedMessage.Builder<?> builder) {\n super(builder);\n this.unknownFields = builder.getUnknownFields();\n }\n private PeerAddress(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }\n\n private static final PeerAddress defaultInstance;\n public static PeerAddress getDefaultInstance() {\n return defaultInstance;\n }\n\n public PeerAddress getDefaultInstanceForType() {\n return defaultInstance;\n }\n\n private final com.google.protobuf.UnknownFieldSet unknownFields;\n @java.lang.Override\n public final com.google.protobuf.UnknownFieldSet\n getUnknownFields() {\n return this.unknownFields;\n }\n private PeerAddress(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n initFields();\n int mutable_bitField0_ = 0;\n com.google.protobuf.UnknownFieldSet.Builder unknownFields =\n com.google.protobuf.UnknownFieldSet.newBuilder();\n try {\n boolean done = false;\n while (!done) {\n int tag = input.readTag();\n switch (tag) {\n case 0:\n done = true;\n break;\n default: {\n if (!parseUnknownField(input, unknownFields,\n extensionRegistry, tag)) {\n done = true;\n }\n break;\n }\n case 10: {\n bitField0_ |= 0x00000001;\n ipAddress_ = input.readBytes();\n break;\n }\n case 16: {\n bitField0_ |= 0x00000002;\n port_ = input.readUInt32();\n break;\n }\n case 24: {\n bitField0_ |= 0x00000004;\n services_ = input.readUInt64();\n break;\n }\n }\n }\n } catch (com.google.protobuf.InvalidProtocolBufferException e) {\n throw e.setUnfinishedMessage(this);\n } catch (java.io.IOException e) {\n throw new com.google.protobuf.InvalidProtocolBufferException(\n e.getMessage()).setUnfinishedMessage(this);\n } finally {\n this.unknownFields = unknownFields.build();\n makeExtensionsImmutable();\n }\n }\n public static final com.google.protobuf.Descriptors.Descriptor\n getDescriptor() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_PeerAddress_descriptor;\n }\n\n protected com.google.protobuf.GeneratedMessage.FieldAccessorTable\n internalGetFieldAccessorTable() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_PeerAddress_fieldAccessorTable\n .ensureFieldAccessorsInitialized(\n org.bitcoinj.wallet.Protos.PeerAddress.class, org.bitcoinj.wallet.Protos.PeerAddress.Builder.class);\n }\n\n public static com.google.protobuf.Parser<PeerAddress> PARSER =\n new com.google.protobuf.AbstractParser<PeerAddress>() {\n public PeerAddress parsePartialFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return new PeerAddress(input, extensionRegistry);\n }\n };\n\n @java.lang.Override\n public com.google.protobuf.Parser<PeerAddress> getParserForType() {\n return PARSER;\n }\n\n private int bitField0_;\n // required bytes ip_address = 1;\n public static final int IP_ADDRESS_FIELD_NUMBER = 1;\n private com.google.protobuf.ByteString ipAddress_;\n /**\n * <code>required bytes ip_address = 1;</code>\n */\n public boolean hasIpAddress() {\n return ((bitField0_ & 0x00000001) == 0x00000001);\n }\n /**\n * <code>required bytes ip_address = 1;</code>\n */\n public com.google.protobuf.ByteString getIpAddress() {\n return ipAddress_;\n }\n\n // required uint32 port = 2;\n public static final int PORT_FIELD_NUMBER = 2;\n private int port_;\n /**\n * <code>required uint32 port = 2;</code>\n */\n public boolean hasPort() {\n return ((bitField0_ & 0x00000002) == 0x00000002);\n }\n /**\n * <code>required uint32 port = 2;</code>\n */\n public int getPort() {\n return port_;\n }\n\n // required uint64 services = 3;\n public static final int SERVICES_FIELD_NUMBER = 3;\n private long services_;\n /**\n * <code>required uint64 services = 3;</code>\n */\n public boolean hasServices() {\n return ((bitField0_ & 0x00000004) == 0x00000004);\n }\n /**\n * <code>required uint64 services = 3;</code>\n */\n public long getServices() {\n return services_;\n }\n\n private void initFields() {\n ipAddress_ = com.google.protobuf.ByteString.EMPTY;\n port_ = 0;\n services_ = 0L;\n }\n private byte memoizedIsInitialized = -1;\n public final boolean isInitialized() {\n byte isInitialized = memoizedIsInitialized;\n if (isInitialized != -1) return isInitialized == 1;\n\n if (!hasIpAddress()) {\n memoizedIsInitialized = 0;\n return false;\n }\n if (!hasPort()) {\n memoizedIsInitialized = 0;\n return false;\n }\n if (!hasServices()) {\n memoizedIsInitialized = 0;\n return false;\n }\n memoizedIsInitialized = 1;\n return true;\n }\n\n public void writeTo(com.google.protobuf.CodedOutputStream output)\n throws java.io.IOException {\n getSerializedSize();\n if (((bitField0_ & 0x00000001) == 0x00000001)) {\n output.writeBytes(1, ipAddress_);\n }\n if (((bitField0_ & 0x00000002) == 0x00000002)) {\n output.writeUInt32(2, port_);\n }\n if (((bitField0_ & 0x00000004) == 0x00000004)) {\n output.writeUInt64(3, services_);\n }\n getUnknownFields().writeTo(output);\n }\n\n private int memoizedSerializedSize = -1;\n public int getSerializedSize() {\n int size = memoizedSerializedSize;\n if (size != -1) return size;\n\n size = 0;\n if (((bitField0_ & 0x00000001) == 0x00000001)) {\n size += com.google.protobuf.CodedOutputStream\n .computeBytesSize(1, ipAddress_);\n }\n if (((bitField0_ & 0x00000002) == 0x00000002)) {\n size += com.google.protobuf.CodedOutputStream\n .computeUInt32Size(2, port_);\n }\n if (((bitField0_ & 0x00000004) == 0x00000004)) {\n size += com.google.protobuf.CodedOutputStream\n .computeUInt64Size(3, services_);\n }\n size += getUnknownFields().getSerializedSize();\n memoizedSerializedSize = size;\n return size;\n }\n\n private static final long serialVersionUID = 0L;\n @java.lang.Override\n protected java.lang.Object writeReplace()\n throws java.io.ObjectStreamException {\n return super.writeReplace();\n }\n\n public static org.bitcoinj.wallet.Protos.PeerAddress parseFrom(\n com.google.protobuf.ByteString data)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n public static org.bitcoinj.wallet.Protos.PeerAddress parseFrom(\n com.google.protobuf.ByteString data,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n public static org.bitcoinj.wallet.Protos.PeerAddress parseFrom(byte[] data)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n public static org.bitcoinj.wallet.Protos.PeerAddress parseFrom(\n byte[] data,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n public static org.bitcoinj.wallet.Protos.PeerAddress parseFrom(java.io.InputStream input)\n throws java.io.IOException {\n return PARSER.parseFrom(input);\n }\n public static org.bitcoinj.wallet.Protos.PeerAddress parseFrom(\n java.io.InputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return PARSER.parseFrom(input, extensionRegistry);\n }\n public static org.bitcoinj.wallet.Protos.PeerAddress parseDelimitedFrom(java.io.InputStream input)\n throws java.io.IOException {\n return PARSER.parseDelimitedFrom(input);\n }\n public static org.bitcoinj.wallet.Protos.PeerAddress parseDelimitedFrom(\n java.io.InputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return PARSER.parseDelimitedFrom(input, extensionRegistry);\n }\n public static org.bitcoinj.wallet.Protos.PeerAddress parseFrom(\n com.google.protobuf.CodedInputStream input)\n throws java.io.IOException {\n return PARSER.parseFrom(input);\n }\n public static org.bitcoinj.wallet.Protos.PeerAddress parseFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return PARSER.parseFrom(input, extensionRegistry);\n }\n\n public static Builder newBuilder() { return Builder.create(); }\n public Builder newBuilderForType() { return newBuilder(); }\n public static Builder newBuilder(org.bitcoinj.wallet.Protos.PeerAddress prototype) {\n return newBuilder().mergeFrom(prototype);\n }\n public Builder toBuilder() { return newBuilder(this); }\n\n @java.lang.Override\n protected Builder newBuilderForType(\n com.google.protobuf.GeneratedMessage.BuilderParent parent) {\n Builder builder = new Builder(parent);\n return builder;\n }\n /**\n * Protobuf type {@code wallet.PeerAddress}\n */\n public static final class Builder extends\n com.google.protobuf.GeneratedMessage.Builder<Builder>\n implements org.bitcoinj.wallet.Protos.PeerAddressOrBuilder {\n public static final com.google.protobuf.Descriptors.Descriptor\n getDescriptor() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_PeerAddress_descriptor;\n }\n\n protected com.google.protobuf.GeneratedMessage.FieldAccessorTable\n internalGetFieldAccessorTable() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_PeerAddress_fieldAccessorTable\n .ensureFieldAccessorsInitialized(\n org.bitcoinj.wallet.Protos.PeerAddress.class, org.bitcoinj.wallet.Protos.PeerAddress.Builder.class);\n }\n\n // Construct using org.bitcoinj.wallet.Protos.PeerAddress.newBuilder()\n private Builder() {\n maybeForceBuilderInitialization();\n }\n\n private Builder(\n com.google.protobuf.GeneratedMessage.BuilderParent parent) {\n super(parent);\n maybeForceBuilderInitialization();\n }\n private void maybeForceBuilderInitialization() {\n if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {\n }\n }\n private static Builder create() {\n return new Builder();\n }\n\n public Builder clear() {\n super.clear();\n ipAddress_ = com.google.protobuf.ByteString.EMPTY;\n bitField0_ = (bitField0_ & ~0x00000001);\n port_ = 0;\n bitField0_ = (bitField0_ & ~0x00000002);\n services_ = 0L;\n bitField0_ = (bitField0_ & ~0x00000004);\n return this;\n }\n\n public Builder clone() {\n return create().mergeFrom(buildPartial());\n }\n\n public com.google.protobuf.Descriptors.Descriptor\n getDescriptorForType() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_PeerAddress_descriptor;\n }\n\n public org.bitcoinj.wallet.Protos.PeerAddress getDefaultInstanceForType() {\n return org.bitcoinj.wallet.Protos.PeerAddress.getDefaultInstance();\n }\n\n public org.bitcoinj.wallet.Protos.PeerAddress build() {\n org.bitcoinj.wallet.Protos.PeerAddress result = buildPartial();\n if (!result.isInitialized()) {\n throw newUninitializedMessageException(result);\n }\n return result;\n }\n\n public org.bitcoinj.wallet.Protos.PeerAddress buildPartial() {\n org.bitcoinj.wallet.Protos.PeerAddress result = new org.bitcoinj.wallet.Protos.PeerAddress(this);\n int from_bitField0_ = bitField0_;\n int to_bitField0_ = 0;\n if (((from_bitField0_ & 0x00000001) == 0x00000001)) {\n to_bitField0_ |= 0x00000001;\n }\n result.ipAddress_ = ipAddress_;\n if (((from_bitField0_ & 0x00000002) == 0x00000002)) {\n to_bitField0_ |= 0x00000002;\n }\n result.port_ = port_;\n if (((from_bitField0_ & 0x00000004) == 0x00000004)) {\n to_bitField0_ |= 0x00000004;\n }\n result.services_ = services_;\n result.bitField0_ = to_bitField0_;\n onBuilt();\n return result;\n }\n\n public Builder mergeFrom(com.google.protobuf.Message other) {\n if (other instanceof org.bitcoinj.wallet.Protos.PeerAddress) {\n return mergeFrom((org.bitcoinj.wallet.Protos.PeerAddress)other);\n } else {\n super.mergeFrom(other);\n return this;\n }\n }\n\n public Builder mergeFrom(org.bitcoinj.wallet.Protos.PeerAddress other) {\n if (other == org.bitcoinj.wallet.Protos.PeerAddress.getDefaultInstance()) return this;\n if (other.hasIpAddress()) {\n setIpAddress(other.getIpAddress());\n }\n if (other.hasPort()) {\n setPort(other.getPort());\n }\n if (other.hasServices()) {\n setServices(other.getServices());\n }\n this.mergeUnknownFields(other.getUnknownFields());\n return this;\n }\n\n public final boolean isInitialized() {\n if (!hasIpAddress()) {\n \n return false;\n }\n if (!hasPort()) {\n \n return false;\n }\n if (!hasServices()) {\n \n return false;\n }\n return true;\n }\n\n public Builder mergeFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n org.bitcoinj.wallet.Protos.PeerAddress parsedMessage = null;\n try {\n parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);\n } catch (com.google.protobuf.InvalidProtocolBufferException e) {\n parsedMessage = (org.bitcoinj.wallet.Protos.PeerAddress) e.getUnfinishedMessage();\n throw e;\n } finally {\n if (parsedMessage != null) {\n mergeFrom(parsedMessage);\n }\n }\n return this;\n }\n private int bitField0_;\n\n // required bytes ip_address = 1;\n private com.google.protobuf.ByteString ipAddress_ = com.google.protobuf.ByteString.EMPTY;\n /**\n * <code>required bytes ip_address = 1;</code>\n */\n public boolean hasIpAddress() {\n return ((bitField0_ & 0x00000001) == 0x00000001);\n }\n /**\n * <code>required bytes ip_address = 1;</code>\n */\n public com.google.protobuf.ByteString getIpAddress() {\n return ipAddress_;\n }\n /**\n * <code>required bytes ip_address = 1;</code>\n */\n public Builder setIpAddress(com.google.protobuf.ByteString value) {\n if (value == null) {\n throw new NullPointerException();\n }\n bitField0_ |= 0x00000001;\n ipAddress_ = value;\n onChanged();\n return this;\n }\n /**\n * <code>required bytes ip_address = 1;</code>\n */\n public Builder clearIpAddress() {\n bitField0_ = (bitField0_ & ~0x00000001);\n ipAddress_ = getDefaultInstance().getIpAddress();\n onChanged();\n return this;\n }\n\n // required uint32 port = 2;\n private int port_ ;\n /**\n * <code>required uint32 port = 2;</code>\n */\n public boolean hasPort() {\n return ((bitField0_ & 0x00000002) == 0x00000002);\n }\n /**\n * <code>required uint32 port = 2;</code>\n */\n public int getPort() {\n return port_;\n }\n /**\n * <code>required uint32 port = 2;</code>\n */\n public Builder setPort(int value) {\n bitField0_ |= 0x00000002;\n port_ = value;\n onChanged();\n return this;\n }\n /**\n * <code>required uint32 port = 2;</code>\n */\n public Builder clearPort() {\n bitField0_ = (bitField0_ & ~0x00000002);\n port_ = 0;\n onChanged();\n return this;\n }\n\n // required uint64 services = 3;\n private long services_ ;\n /**\n * <code>required uint64 services = 3;</code>\n */\n public boolean hasServices() {\n return ((bitField0_ & 0x00000004) == 0x00000004);\n }\n /**\n * <code>required uint64 services = 3;</code>\n */\n public long getServices() {\n return services_;\n }\n /**\n * <code>required uint64 services = 3;</code>\n */\n public Builder setServices(long value) {\n bitField0_ |= 0x00000004;\n services_ = value;\n onChanged();\n return this;\n }\n /**\n * <code>required uint64 services = 3;</code>\n */\n public Builder clearServices() {\n bitField0_ = (bitField0_ & ~0x00000004);\n services_ = 0L;\n onChanged();\n return this;\n }\n\n // @@protoc_insertion_point(builder_scope:wallet.PeerAddress)\n }\n\n static {\n defaultInstance = new PeerAddress(true);\n defaultInstance.initFields();\n }\n\n // @@protoc_insertion_point(class_scope:wallet.PeerAddress)\n }\n\n public interface EncryptedPrivateKeyOrBuilder\n extends com.google.protobuf.MessageOrBuilder {\n\n // required bytes initialisation_vector = 1;\n /**\n * <code>required bytes initialisation_vector = 1;</code>\n *\n * <pre>\n * The initialisation vector for the AES encryption (16 bytes)\n * </pre>\n */\n boolean hasInitialisationVector();\n /**\n * <code>required bytes initialisation_vector = 1;</code>\n *\n * <pre>\n * The initialisation vector for the AES encryption (16 bytes)\n * </pre>\n */\n com.google.protobuf.ByteString getInitialisationVector();\n\n // required bytes encrypted_private_key = 2;\n /**\n * <code>required bytes encrypted_private_key = 2;</code>\n *\n * <pre>\n * The encrypted private key\n * </pre>\n */\n boolean hasEncryptedPrivateKey();\n /**\n * <code>required bytes encrypted_private_key = 2;</code>\n *\n * <pre>\n * The encrypted private key\n * </pre>\n */\n com.google.protobuf.ByteString getEncryptedPrivateKey();\n }\n /**\n * Protobuf type {@code wallet.EncryptedPrivateKey}\n *\n * <pre>\n **\n * The data to store a private key encrypted with Scrypt and AES\n * </pre>\n */\n public static final class EncryptedPrivateKey extends\n com.google.protobuf.GeneratedMessage\n implements EncryptedPrivateKeyOrBuilder {\n // Use EncryptedPrivateKey.newBuilder() to construct.\n private EncryptedPrivateKey(com.google.protobuf.GeneratedMessage.Builder<?> builder) {\n super(builder);\n this.unknownFields = builder.getUnknownFields();\n }\n private EncryptedPrivateKey(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }\n\n private static final EncryptedPrivateKey defaultInstance;\n public static EncryptedPrivateKey getDefaultInstance() {\n return defaultInstance;\n }\n\n public EncryptedPrivateKey getDefaultInstanceForType() {\n return defaultInstance;\n }\n\n private final com.google.protobuf.UnknownFieldSet unknownFields;\n @java.lang.Override\n public final com.google.protobuf.UnknownFieldSet\n getUnknownFields() {\n return this.unknownFields;\n }\n private EncryptedPrivateKey(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n initFields();\n int mutable_bitField0_ = 0;\n com.google.protobuf.UnknownFieldSet.Builder unknownFields =\n com.google.protobuf.UnknownFieldSet.newBuilder();\n try {\n boolean done = false;\n while (!done) {\n int tag = input.readTag();\n switch (tag) {\n case 0:\n done = true;\n break;\n default: {\n if (!parseUnknownField(input, unknownFields,\n extensionRegistry, tag)) {\n done = true;\n }\n break;\n }\n case 10: {\n bitField0_ |= 0x00000001;\n initialisationVector_ = input.readBytes();\n break;\n }\n case 18: {\n bitField0_ |= 0x00000002;\n encryptedPrivateKey_ = input.readBytes();\n break;\n }\n }\n }\n } catch (com.google.protobuf.InvalidProtocolBufferException e) {\n throw e.setUnfinishedMessage(this);\n } catch (java.io.IOException e) {\n throw new com.google.protobuf.InvalidProtocolBufferException(\n e.getMessage()).setUnfinishedMessage(this);\n } finally {\n this.unknownFields = unknownFields.build();\n makeExtensionsImmutable();\n }\n }\n public static final com.google.protobuf.Descriptors.Descriptor\n getDescriptor() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_EncryptedPrivateKey_descriptor;\n }\n\n protected com.google.protobuf.GeneratedMessage.FieldAccessorTable\n internalGetFieldAccessorTable() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_EncryptedPrivateKey_fieldAccessorTable\n .ensureFieldAccessorsInitialized(\n org.bitcoinj.wallet.Protos.EncryptedPrivateKey.class, org.bitcoinj.wallet.Protos.EncryptedPrivateKey.Builder.class);\n }\n\n public static com.google.protobuf.Parser<EncryptedPrivateKey> PARSER =\n new com.google.protobuf.AbstractParser<EncryptedPrivateKey>() {\n public EncryptedPrivateKey parsePartialFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return new EncryptedPrivateKey(input, extensionRegistry);\n }\n };\n\n @java.lang.Override\n public com.google.protobuf.Parser<EncryptedPrivateKey> getParserForType() {\n return PARSER;\n }\n\n private int bitField0_;\n // required bytes initialisation_vector = 1;\n public static final int INITIALISATION_VECTOR_FIELD_NUMBER = 1;\n private com.google.protobuf.ByteString initialisationVector_;\n /**\n * <code>required bytes initialisation_vector = 1;</code>\n *\n * <pre>\n * The initialisation vector for the AES encryption (16 bytes)\n * </pre>\n */\n public boolean hasInitialisationVector() {\n return ((bitField0_ & 0x00000001) == 0x00000001);\n }\n /**\n * <code>required bytes initialisation_vector = 1;</code>\n *\n * <pre>\n * The initialisation vector for the AES encryption (16 bytes)\n * </pre>\n */\n public com.google.protobuf.ByteString getInitialisationVector() {\n return initialisationVector_;\n }\n\n // required bytes encrypted_private_key = 2;\n public static final int ENCRYPTED_PRIVATE_KEY_FIELD_NUMBER = 2;\n private com.google.protobuf.ByteString encryptedPrivateKey_;\n /**\n * <code>required bytes encrypted_private_key = 2;</code>\n *\n * <pre>\n * The encrypted private key\n * </pre>\n */\n public boolean hasEncryptedPrivateKey() {\n return ((bitField0_ & 0x00000002) == 0x00000002);\n }\n /**\n * <code>required bytes encrypted_private_key = 2;</code>\n *\n * <pre>\n * The encrypted private key\n * </pre>\n */\n public com.google.protobuf.ByteString getEncryptedPrivateKey() {\n return encryptedPrivateKey_;\n }\n\n private void initFields() {\n initialisationVector_ = com.google.protobuf.ByteString.EMPTY;\n encryptedPrivateKey_ = com.google.protobuf.ByteString.EMPTY;\n }\n private byte memoizedIsInitialized = -1;\n public final boolean isInitialized() {\n byte isInitialized = memoizedIsInitialized;\n if (isInitialized != -1) return isInitialized == 1;\n\n if (!hasInitialisationVector()) {\n memoizedIsInitialized = 0;\n return false;\n }\n if (!hasEncryptedPrivateKey()) {\n memoizedIsInitialized = 0;\n return false;\n }\n memoizedIsInitialized = 1;\n return true;\n }\n\n public void writeTo(com.google.protobuf.CodedOutputStream output)\n throws java.io.IOException {\n getSerializedSize();\n if (((bitField0_ & 0x00000001) == 0x00000001)) {\n output.writeBytes(1, initialisationVector_);\n }\n if (((bitField0_ & 0x00000002) == 0x00000002)) {\n output.writeBytes(2, encryptedPrivateKey_);\n }\n getUnknownFields().writeTo(output);\n }\n\n private int memoizedSerializedSize = -1;\n public int getSerializedSize() {\n int size = memoizedSerializedSize;\n if (size != -1) return size;\n\n size = 0;\n if (((bitField0_ & 0x00000001) == 0x00000001)) {\n size += com.google.protobuf.CodedOutputStream\n .computeBytesSize(1, initialisationVector_);\n }\n if (((bitField0_ & 0x00000002) == 0x00000002)) {\n size += com.google.protobuf.CodedOutputStream\n .computeBytesSize(2, encryptedPrivateKey_);\n }\n size += getUnknownFields().getSerializedSize();\n memoizedSerializedSize = size;\n return size;\n }\n\n private static final long serialVersionUID = 0L;\n @java.lang.Override\n protected java.lang.Object writeReplace()\n throws java.io.ObjectStreamException {\n return super.writeReplace();\n }\n\n public static org.bitcoinj.wallet.Protos.EncryptedPrivateKey parseFrom(\n com.google.protobuf.ByteString data)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n public static org.bitcoinj.wallet.Protos.EncryptedPrivateKey parseFrom(\n com.google.protobuf.ByteString data,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n public static org.bitcoinj.wallet.Protos.EncryptedPrivateKey parseFrom(byte[] data)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n public static org.bitcoinj.wallet.Protos.EncryptedPrivateKey parseFrom(\n byte[] data,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n public static org.bitcoinj.wallet.Protos.EncryptedPrivateKey parseFrom(java.io.InputStream input)\n throws java.io.IOException {\n return PARSER.parseFrom(input);\n }\n public static org.bitcoinj.wallet.Protos.EncryptedPrivateKey parseFrom(\n java.io.InputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return PARSER.parseFrom(input, extensionRegistry);\n }\n public static org.bitcoinj.wallet.Protos.EncryptedPrivateKey parseDelimitedFrom(java.io.InputStream input)\n throws java.io.IOException {\n return PARSER.parseDelimitedFrom(input);\n }\n public static org.bitcoinj.wallet.Protos.EncryptedPrivateKey parseDelimitedFrom(\n java.io.InputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return PARSER.parseDelimitedFrom(input, extensionRegistry);\n }\n public static org.bitcoinj.wallet.Protos.EncryptedPrivateKey parseFrom(\n com.google.protobuf.CodedInputStream input)\n throws java.io.IOException {\n return PARSER.parseFrom(input);\n }\n public static org.bitcoinj.wallet.Protos.EncryptedPrivateKey parseFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return PARSER.parseFrom(input, extensionRegistry);\n }\n\n public static Builder newBuilder() { return Builder.create(); }\n public Builder newBuilderForType() { return newBuilder(); }\n public static Builder newBuilder(org.bitcoinj.wallet.Protos.EncryptedPrivateKey prototype) {\n return newBuilder().mergeFrom(prototype);\n }\n public Builder toBuilder() { return newBuilder(this); }\n\n @java.lang.Override\n protected Builder newBuilderForType(\n com.google.protobuf.GeneratedMessage.BuilderParent parent) {\n Builder builder = new Builder(parent);\n return builder;\n }\n /**\n * Protobuf type {@code wallet.EncryptedPrivateKey}\n *\n * <pre>\n **\n * The data to store a private key encrypted with Scrypt and AES\n * </pre>\n */\n public static final class Builder extends\n com.google.protobuf.GeneratedMessage.Builder<Builder>\n implements org.bitcoinj.wallet.Protos.EncryptedPrivateKeyOrBuilder {\n public static final com.google.protobuf.Descriptors.Descriptor\n getDescriptor() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_EncryptedPrivateKey_descriptor;\n }\n\n protected com.google.protobuf.GeneratedMessage.FieldAccessorTable\n internalGetFieldAccessorTable() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_EncryptedPrivateKey_fieldAccessorTable\n .ensureFieldAccessorsInitialized(\n org.bitcoinj.wallet.Protos.EncryptedPrivateKey.class, org.bitcoinj.wallet.Protos.EncryptedPrivateKey.Builder.class);\n }\n\n // Construct using org.bitcoinj.wallet.Protos.EncryptedPrivateKey.newBuilder()\n private Builder() {\n maybeForceBuilderInitialization();\n }\n\n private Builder(\n com.google.protobuf.GeneratedMessage.BuilderParent parent) {\n super(parent);\n maybeForceBuilderInitialization();\n }\n private void maybeForceBuilderInitialization() {\n if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {\n }\n }\n private static Builder create() {\n return new Builder();\n }\n\n public Builder clear() {\n super.clear();\n initialisationVector_ = com.google.protobuf.ByteString.EMPTY;\n bitField0_ = (bitField0_ & ~0x00000001);\n encryptedPrivateKey_ = com.google.protobuf.ByteString.EMPTY;\n bitField0_ = (bitField0_ & ~0x00000002);\n return this;\n }\n\n public Builder clone() {\n return create().mergeFrom(buildPartial());\n }\n\n public com.google.protobuf.Descriptors.Descriptor\n getDescriptorForType() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_EncryptedPrivateKey_descriptor;\n }\n\n public org.bitcoinj.wallet.Protos.EncryptedPrivateKey getDefaultInstanceForType() {\n return org.bitcoinj.wallet.Protos.EncryptedPrivateKey.getDefaultInstance();\n }\n\n public org.bitcoinj.wallet.Protos.EncryptedPrivateKey build() {\n org.bitcoinj.wallet.Protos.EncryptedPrivateKey result = buildPartial();\n if (!result.isInitialized()) {\n throw newUninitializedMessageException(result);\n }\n return result;\n }\n\n public org.bitcoinj.wallet.Protos.EncryptedPrivateKey buildPartial() {\n org.bitcoinj.wallet.Protos.EncryptedPrivateKey result = new org.bitcoinj.wallet.Protos.EncryptedPrivateKey(this);\n int from_bitField0_ = bitField0_;\n int to_bitField0_ = 0;\n if (((from_bitField0_ & 0x00000001) == 0x00000001)) {\n to_bitField0_ |= 0x00000001;\n }\n result.initialisationVector_ = initialisationVector_;\n if (((from_bitField0_ & 0x00000002) == 0x00000002)) {\n to_bitField0_ |= 0x00000002;\n }\n result.encryptedPrivateKey_ = encryptedPrivateKey_;\n result.bitField0_ = to_bitField0_;\n onBuilt();\n return result;\n }\n\n public Builder mergeFrom(com.google.protobuf.Message other) {\n if (other instanceof org.bitcoinj.wallet.Protos.EncryptedPrivateKey) {\n return mergeFrom((org.bitcoinj.wallet.Protos.EncryptedPrivateKey)other);\n } else {\n super.mergeFrom(other);\n return this;\n }\n }\n\n public Builder mergeFrom(org.bitcoinj.wallet.Protos.EncryptedPrivateKey other) {\n if (other == org.bitcoinj.wallet.Protos.EncryptedPrivateKey.getDefaultInstance()) return this;\n if (other.hasInitialisationVector()) {\n setInitialisationVector(other.getInitialisationVector());\n }\n if (other.hasEncryptedPrivateKey()) {\n setEncryptedPrivateKey(other.getEncryptedPrivateKey());\n }\n this.mergeUnknownFields(other.getUnknownFields());\n return this;\n }\n\n public final boolean isInitialized() {\n if (!hasInitialisationVector()) {\n \n return false;\n }\n if (!hasEncryptedPrivateKey()) {\n \n return false;\n }\n return true;\n }\n\n public Builder mergeFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n org.bitcoinj.wallet.Protos.EncryptedPrivateKey parsedMessage = null;\n try {\n parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);\n } catch (com.google.protobuf.InvalidProtocolBufferException e) {\n parsedMessage = (org.bitcoinj.wallet.Protos.EncryptedPrivateKey) e.getUnfinishedMessage();\n throw e;\n } finally {\n if (parsedMessage != null) {\n mergeFrom(parsedMessage);\n }\n }\n return this;\n }\n private int bitField0_;\n\n // required bytes initialisation_vector = 1;\n private com.google.protobuf.ByteString initialisationVector_ = com.google.protobuf.ByteString.EMPTY;\n /**\n * <code>required bytes initialisation_vector = 1;</code>\n *\n * <pre>\n * The initialisation vector for the AES encryption (16 bytes)\n * </pre>\n */\n public boolean hasInitialisationVector() {\n return ((bitField0_ & 0x00000001) == 0x00000001);\n }\n /**\n * <code>required bytes initialisation_vector = 1;</code>\n *\n * <pre>\n * The initialisation vector for the AES encryption (16 bytes)\n * </pre>\n */\n public com.google.protobuf.ByteString getInitialisationVector() {\n return initialisationVector_;\n }\n /**\n * <code>required bytes initialisation_vector = 1;</code>\n *\n * <pre>\n * The initialisation vector for the AES encryption (16 bytes)\n * </pre>\n */\n public Builder setInitialisationVector(com.google.protobuf.ByteString value) {\n if (value == null) {\n throw new NullPointerException();\n }\n bitField0_ |= 0x00000001;\n initialisationVector_ = value;\n onChanged();\n return this;\n }\n /**\n * <code>required bytes initialisation_vector = 1;</code>\n *\n * <pre>\n * The initialisation vector for the AES encryption (16 bytes)\n * </pre>\n */\n public Builder clearInitialisationVector() {\n bitField0_ = (bitField0_ & ~0x00000001);\n initialisationVector_ = getDefaultInstance().getInitialisationVector();\n onChanged();\n return this;\n }\n\n // required bytes encrypted_private_key = 2;\n private com.google.protobuf.ByteString encryptedPrivateKey_ = com.google.protobuf.ByteString.EMPTY;\n /**\n * <code>required bytes encrypted_private_key = 2;</code>\n *\n * <pre>\n * The encrypted private key\n * </pre>\n */\n public boolean hasEncryptedPrivateKey() {\n return ((bitField0_ & 0x00000002) == 0x00000002);\n }\n /**\n * <code>required bytes encrypted_private_key = 2;</code>\n *\n * <pre>\n * The encrypted private key\n * </pre>\n */\n public com.google.protobuf.ByteString getEncryptedPrivateKey() {\n return encryptedPrivateKey_;\n }\n /**\n * <code>required bytes encrypted_private_key = 2;</code>\n *\n * <pre>\n * The encrypted private key\n * </pre>\n */\n public Builder setEncryptedPrivateKey(com.google.protobuf.ByteString value) {\n if (value == null) {\n throw new NullPointerException();\n }\n bitField0_ |= 0x00000002;\n encryptedPrivateKey_ = value;\n onChanged();\n return this;\n }\n /**\n * <code>required bytes encrypted_private_key = 2;</code>\n *\n * <pre>\n * The encrypted private key\n * </pre>\n */\n public Builder clearEncryptedPrivateKey() {\n bitField0_ = (bitField0_ & ~0x00000002);\n encryptedPrivateKey_ = getDefaultInstance().getEncryptedPrivateKey();\n onChanged();\n return this;\n }\n\n // @@protoc_insertion_point(builder_scope:wallet.EncryptedPrivateKey)\n }\n\n static {\n defaultInstance = new EncryptedPrivateKey(true);\n defaultInstance.initFields();\n }\n\n // @@protoc_insertion_point(class_scope:wallet.EncryptedPrivateKey)\n }\n\n public interface KeyOrBuilder\n extends com.google.protobuf.MessageOrBuilder {\n\n // required .wallet.Key.Type type = 1;\n /**\n * <code>required .wallet.Key.Type type = 1;</code>\n */\n boolean hasType();\n /**\n * <code>required .wallet.Key.Type type = 1;</code>\n */\n org.bitcoinj.wallet.Protos.Key.Type getType();\n\n // optional bytes private_key = 2;\n /**\n * <code>optional bytes private_key = 2;</code>\n *\n * <pre>\n * The private EC key bytes without any ASN.1 wrapping.\n * </pre>\n */\n boolean hasPrivateKey();\n /**\n * <code>optional bytes private_key = 2;</code>\n *\n * <pre>\n * The private EC key bytes without any ASN.1 wrapping.\n * </pre>\n */\n com.google.protobuf.ByteString getPrivateKey();\n\n // optional .wallet.EncryptedPrivateKey encrypted_private_key = 6;\n /**\n * <code>optional .wallet.EncryptedPrivateKey encrypted_private_key = 6;</code>\n *\n * <pre>\n * The message containing the encrypted private EC key information.\n * When an EncryptedPrivateKey is present then the (unencrypted) private_key will be a zero length byte array or contain all zeroes.\n * This is for security of the private key information.\n * </pre>\n */\n boolean hasEncryptedPrivateKey();\n /**\n * <code>optional .wallet.EncryptedPrivateKey encrypted_private_key = 6;</code>\n *\n * <pre>\n * The message containing the encrypted private EC key information.\n * When an EncryptedPrivateKey is present then the (unencrypted) private_key will be a zero length byte array or contain all zeroes.\n * This is for security of the private key information.\n * </pre>\n */\n org.bitcoinj.wallet.Protos.EncryptedPrivateKey getEncryptedPrivateKey();\n /**\n * <code>optional .wallet.EncryptedPrivateKey encrypted_private_key = 6;</code>\n *\n * <pre>\n * The message containing the encrypted private EC key information.\n * When an EncryptedPrivateKey is present then the (unencrypted) private_key will be a zero length byte array or contain all zeroes.\n * This is for security of the private key information.\n * </pre>\n */\n org.bitcoinj.wallet.Protos.EncryptedPrivateKeyOrBuilder getEncryptedPrivateKeyOrBuilder();\n\n // optional bytes public_key = 3;\n /**\n * <code>optional bytes public_key = 3;</code>\n *\n * <pre>\n * The public EC key derived from the private key. We allow both to be stored to avoid mobile clients having to\n * do lots of slow EC math on startup.\n * </pre>\n */\n boolean hasPublicKey();\n /**\n * <code>optional bytes public_key = 3;</code>\n *\n * <pre>\n * The public EC key derived from the private key. We allow both to be stored to avoid mobile clients having to\n * do lots of slow EC math on startup.\n * </pre>\n */\n com.google.protobuf.ByteString getPublicKey();\n\n // optional string label = 4;\n /**\n * <code>optional string label = 4;</code>\n *\n * <pre>\n * User-provided label associated with the key.\n * </pre>\n */\n boolean hasLabel();\n /**\n * <code>optional string label = 4;</code>\n *\n * <pre>\n * User-provided label associated with the key.\n * </pre>\n */\n java.lang.String getLabel();\n /**\n * <code>optional string label = 4;</code>\n *\n * <pre>\n * User-provided label associated with the key.\n * </pre>\n */\n com.google.protobuf.ByteString\n getLabelBytes();\n\n // optional int64 creation_timestamp = 5;\n /**\n * <code>optional int64 creation_timestamp = 5;</code>\n *\n * <pre>\n * Timestamp stored as millis since epoch. Useful for skipping block bodies before this point.\n * </pre>\n */\n boolean hasCreationTimestamp();\n /**\n * <code>optional int64 creation_timestamp = 5;</code>\n *\n * <pre>\n * Timestamp stored as millis since epoch. Useful for skipping block bodies before this point.\n * </pre>\n */\n long getCreationTimestamp();\n }\n /**\n * Protobuf type {@code wallet.Key}\n *\n * <pre>\n **\n * A key used to control Bitcoin spending.\n *\n * Either the private key, the public key or both may be present. It is recommended that\n * if the private key is provided that the public key is provided too because deriving it is slow.\n *\n * If only the public key is provided, the key can only be used to watch the blockchain and verify\n * transactions, and not for spending.\n * </pre>\n */\n public static final class Key extends\n com.google.protobuf.GeneratedMessage\n implements KeyOrBuilder {\n // Use Key.newBuilder() to construct.\n private Key(com.google.protobuf.GeneratedMessage.Builder<?> builder) {\n super(builder);\n this.unknownFields = builder.getUnknownFields();\n }\n private Key(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }\n\n private static final Key defaultInstance;\n public static Key getDefaultInstance() {\n return defaultInstance;\n }\n\n public Key getDefaultInstanceForType() {\n return defaultInstance;\n }\n\n private final com.google.protobuf.UnknownFieldSet unknownFields;\n @java.lang.Override\n public final com.google.protobuf.UnknownFieldSet\n getUnknownFields() {\n return this.unknownFields;\n }\n private Key(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n initFields();\n int mutable_bitField0_ = 0;\n com.google.protobuf.UnknownFieldSet.Builder unknownFields =\n com.google.protobuf.UnknownFieldSet.newBuilder();\n try {\n boolean done = false;\n while (!done) {\n int tag = input.readTag();\n switch (tag) {\n case 0:\n done = true;\n break;\n default: {\n if (!parseUnknownField(input, unknownFields,\n extensionRegistry, tag)) {\n done = true;\n }\n break;\n }\n case 8: {\n int rawValue = input.readEnum();\n org.bitcoinj.wallet.Protos.Key.Type value = org.bitcoinj.wallet.Protos.Key.Type.valueOf(rawValue);\n if (value == null) {\n unknownFields.mergeVarintField(1, rawValue);\n } else {\n bitField0_ |= 0x00000001;\n type_ = value;\n }\n break;\n }\n case 18: {\n bitField0_ |= 0x00000002;\n privateKey_ = input.readBytes();\n break;\n }\n case 26: {\n bitField0_ |= 0x00000008;\n publicKey_ = input.readBytes();\n break;\n }\n case 34: {\n bitField0_ |= 0x00000010;\n label_ = input.readBytes();\n break;\n }\n case 40: {\n bitField0_ |= 0x00000020;\n creationTimestamp_ = input.readInt64();\n break;\n }\n case 50: {\n org.bitcoinj.wallet.Protos.EncryptedPrivateKey.Builder subBuilder = null;\n if (((bitField0_ & 0x00000004) == 0x00000004)) {\n subBuilder = encryptedPrivateKey_.toBuilder();\n }\n encryptedPrivateKey_ = input.readMessage(org.bitcoinj.wallet.Protos.EncryptedPrivateKey.PARSER, extensionRegistry);\n if (subBuilder != null) {\n subBuilder.mergeFrom(encryptedPrivateKey_);\n encryptedPrivateKey_ = subBuilder.buildPartial();\n }\n bitField0_ |= 0x00000004;\n break;\n }\n }\n }\n } catch (com.google.protobuf.InvalidProtocolBufferException e) {\n throw e.setUnfinishedMessage(this);\n } catch (java.io.IOException e) {\n throw new com.google.protobuf.InvalidProtocolBufferException(\n e.getMessage()).setUnfinishedMessage(this);\n } finally {\n this.unknownFields = unknownFields.build();\n makeExtensionsImmutable();\n }\n }\n public static final com.google.protobuf.Descriptors.Descriptor\n getDescriptor() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_Key_descriptor;\n }\n\n protected com.google.protobuf.GeneratedMessage.FieldAccessorTable\n internalGetFieldAccessorTable() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_Key_fieldAccessorTable\n .ensureFieldAccessorsInitialized(\n org.bitcoinj.wallet.Protos.Key.class, org.bitcoinj.wallet.Protos.Key.Builder.class);\n }\n\n public static com.google.protobuf.Parser<Key> PARSER =\n new com.google.protobuf.AbstractParser<Key>() {\n public Key parsePartialFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return new Key(input, extensionRegistry);\n }\n };\n\n @java.lang.Override\n public com.google.protobuf.Parser<Key> getParserForType() {\n return PARSER;\n }\n\n /**\n * Protobuf enum {@code wallet.Key.Type}\n */\n public enum Type\n implements com.google.protobuf.ProtocolMessageEnum {\n /**\n * <code>ORIGINAL = 1;</code>\n *\n * <pre>\n * Unencrypted - Original bitcoin secp256k1 curve\n * </pre>\n */\n ORIGINAL(0, 1),\n /**\n * <code>ENCRYPTED_SCRYPT_AES = 2;</code>\n *\n * <pre>\n * Encrypted with Scrypt and AES - - Original bitcoin secp256k1 curve\n * </pre>\n */\n ENCRYPTED_SCRYPT_AES(1, 2),\n ;\n\n /**\n * <code>ORIGINAL = 1;</code>\n *\n * <pre>\n * Unencrypted - Original bitcoin secp256k1 curve\n * </pre>\n */\n public static final int ORIGINAL_VALUE = 1;\n /**\n * <code>ENCRYPTED_SCRYPT_AES = 2;</code>\n *\n * <pre>\n * Encrypted with Scrypt and AES - - Original bitcoin secp256k1 curve\n * </pre>\n */\n public static final int ENCRYPTED_SCRYPT_AES_VALUE = 2;\n\n\n public final int getNumber() { return value; }\n\n public static Type valueOf(int value) {\n switch (value) {\n case 1: return ORIGINAL;\n case 2: return ENCRYPTED_SCRYPT_AES;\n default: return null;\n }\n }\n\n public static com.google.protobuf.Internal.EnumLiteMap<Type>\n internalGetValueMap() {\n return internalValueMap;\n }\n private static com.google.protobuf.Internal.EnumLiteMap<Type>\n internalValueMap =\n new com.google.protobuf.Internal.EnumLiteMap<Type>() {\n public Type findValueByNumber(int number) {\n return Type.valueOf(number);\n }\n };\n\n public final com.google.protobuf.Descriptors.EnumValueDescriptor\n getValueDescriptor() {\n return getDescriptor().getValues().get(index);\n }\n public final com.google.protobuf.Descriptors.EnumDescriptor\n getDescriptorForType() {\n return getDescriptor();\n }\n public static final com.google.protobuf.Descriptors.EnumDescriptor\n getDescriptor() {\n return org.bitcoinj.wallet.Protos.Key.getDescriptor().getEnumTypes().get(0);\n }\n\n private static final Type[] VALUES = values();\n\n public static Type valueOf(\n com.google.protobuf.Descriptors.EnumValueDescriptor desc) {\n if (desc.getType() != getDescriptor()) {\n throw new java.lang.IllegalArgumentException(\n \"EnumValueDescriptor is not for this type.\");\n }\n return VALUES[desc.getIndex()];\n }\n\n private final int index;\n private final int value;\n\n private Type(int index, int value) {\n this.index = index;\n this.value = value;\n }\n\n // @@protoc_insertion_point(enum_scope:wallet.Key.Type)\n }\n\n private int bitField0_;\n // required .wallet.Key.Type type = 1;\n public static final int TYPE_FIELD_NUMBER = 1;\n private org.bitcoinj.wallet.Protos.Key.Type type_;\n /**\n * <code>required .wallet.Key.Type type = 1;</code>\n */\n public boolean hasType() {\n return ((bitField0_ & 0x00000001) == 0x00000001);\n }\n /**\n * <code>required .wallet.Key.Type type = 1;</code>\n */\n public org.bitcoinj.wallet.Protos.Key.Type getType() {\n return type_;\n }\n\n // optional bytes private_key = 2;\n public static final int PRIVATE_KEY_FIELD_NUMBER = 2;\n private com.google.protobuf.ByteString privateKey_;\n /**\n * <code>optional bytes private_key = 2;</code>\n *\n * <pre>\n * The private EC key bytes without any ASN.1 wrapping.\n * </pre>\n */\n public boolean hasPrivateKey() {\n return ((bitField0_ & 0x00000002) == 0x00000002);\n }\n /**\n * <code>optional bytes private_key = 2;</code>\n *\n * <pre>\n * The private EC key bytes without any ASN.1 wrapping.\n * </pre>\n */\n public com.google.protobuf.ByteString getPrivateKey() {\n return privateKey_;\n }\n\n // optional .wallet.EncryptedPrivateKey encrypted_private_key = 6;\n public static final int ENCRYPTED_PRIVATE_KEY_FIELD_NUMBER = 6;\n private org.bitcoinj.wallet.Protos.EncryptedPrivateKey encryptedPrivateKey_;\n /**\n * <code>optional .wallet.EncryptedPrivateKey encrypted_private_key = 6;</code>\n *\n * <pre>\n * The message containing the encrypted private EC key information.\n * When an EncryptedPrivateKey is present then the (unencrypted) private_key will be a zero length byte array or contain all zeroes.\n * This is for security of the private key information.\n * </pre>\n */\n public boolean hasEncryptedPrivateKey() {\n return ((bitField0_ & 0x00000004) == 0x00000004);\n }\n /**\n * <code>optional .wallet.EncryptedPrivateKey encrypted_private_key = 6;</code>\n *\n * <pre>\n * The message containing the encrypted private EC key information.\n * When an EncryptedPrivateKey is present then the (unencrypted) private_key will be a zero length byte array or contain all zeroes.\n * This is for security of the private key information.\n * </pre>\n */\n public org.bitcoinj.wallet.Protos.EncryptedPrivateKey getEncryptedPrivateKey() {\n return encryptedPrivateKey_;\n }\n /**\n * <code>optional .wallet.EncryptedPrivateKey encrypted_private_key = 6;</code>\n *\n * <pre>\n * The message containing the encrypted private EC key information.\n * When an EncryptedPrivateKey is present then the (unencrypted) private_key will be a zero length byte array or contain all zeroes.\n * This is for security of the private key information.\n * </pre>\n */\n public org.bitcoinj.wallet.Protos.EncryptedPrivateKeyOrBuilder getEncryptedPrivateKeyOrBuilder() {\n return encryptedPrivateKey_;\n }\n\n // optional bytes public_key = 3;\n public static final int PUBLIC_KEY_FIELD_NUMBER = 3;\n private com.google.protobuf.ByteString publicKey_;\n /**\n * <code>optional bytes public_key = 3;</code>\n *\n * <pre>\n * The public EC key derived from the private key. We allow both to be stored to avoid mobile clients having to\n * do lots of slow EC math on startup.\n * </pre>\n */\n public boolean hasPublicKey() {\n return ((bitField0_ & 0x00000008) == 0x00000008);\n }\n /**\n * <code>optional bytes public_key = 3;</code>\n *\n * <pre>\n * The public EC key derived from the private key. We allow both to be stored to avoid mobile clients having to\n * do lots of slow EC math on startup.\n * </pre>\n */\n public com.google.protobuf.ByteString getPublicKey() {\n return publicKey_;\n }\n\n // optional string label = 4;\n public static final int LABEL_FIELD_NUMBER = 4;\n private java.lang.Object label_;\n /**\n * <code>optional string label = 4;</code>\n *\n * <pre>\n * User-provided label associated with the key.\n * </pre>\n */\n public boolean hasLabel() {\n return ((bitField0_ & 0x00000010) == 0x00000010);\n }\n /**\n * <code>optional string label = 4;</code>\n *\n * <pre>\n * User-provided label associated with the key.\n * </pre>\n */\n public java.lang.String getLabel() {\n java.lang.Object ref = label_;\n if (ref instanceof java.lang.String) {\n return (java.lang.String) ref;\n } else {\n com.google.protobuf.ByteString bs = \n (com.google.protobuf.ByteString) ref;\n java.lang.String s = bs.toStringUtf8();\n if (bs.isValidUtf8()) {\n label_ = s;\n }\n return s;\n }\n }\n /**\n * <code>optional string label = 4;</code>\n *\n * <pre>\n * User-provided label associated with the key.\n * </pre>\n */\n public com.google.protobuf.ByteString\n getLabelBytes() {\n java.lang.Object ref = label_;\n if (ref instanceof java.lang.String) {\n com.google.protobuf.ByteString b = \n com.google.protobuf.ByteString.copyFromUtf8(\n (java.lang.String) ref);\n label_ = b;\n return b;\n } else {\n return (com.google.protobuf.ByteString) ref;\n }\n }\n\n // optional int64 creation_timestamp = 5;\n public static final int CREATION_TIMESTAMP_FIELD_NUMBER = 5;\n private long creationTimestamp_;\n /**\n * <code>optional int64 creation_timestamp = 5;</code>\n *\n * <pre>\n * Timestamp stored as millis since epoch. Useful for skipping block bodies before this point.\n * </pre>\n */\n public boolean hasCreationTimestamp() {\n return ((bitField0_ & 0x00000020) == 0x00000020);\n }\n /**\n * <code>optional int64 creation_timestamp = 5;</code>\n *\n * <pre>\n * Timestamp stored as millis since epoch. Useful for skipping block bodies before this point.\n * </pre>\n */\n public long getCreationTimestamp() {\n return creationTimestamp_;\n }\n\n private void initFields() {\n type_ = org.bitcoinj.wallet.Protos.Key.Type.ORIGINAL;\n privateKey_ = com.google.protobuf.ByteString.EMPTY;\n encryptedPrivateKey_ = org.bitcoinj.wallet.Protos.EncryptedPrivateKey.getDefaultInstance();\n publicKey_ = com.google.protobuf.ByteString.EMPTY;\n label_ = \"\";\n creationTimestamp_ = 0L;\n }\n private byte memoizedIsInitialized = -1;\n public final boolean isInitialized() {\n byte isInitialized = memoizedIsInitialized;\n if (isInitialized != -1) return isInitialized == 1;\n\n if (!hasType()) {\n memoizedIsInitialized = 0;\n return false;\n }\n if (hasEncryptedPrivateKey()) {\n if (!getEncryptedPrivateKey().isInitialized()) {\n memoizedIsInitialized = 0;\n return false;\n }\n }\n memoizedIsInitialized = 1;\n return true;\n }\n\n public void writeTo(com.google.protobuf.CodedOutputStream output)\n throws java.io.IOException {\n getSerializedSize();\n if (((bitField0_ & 0x00000001) == 0x00000001)) {\n output.writeEnum(1, type_.getNumber());\n }\n if (((bitField0_ & 0x00000002) == 0x00000002)) {\n output.writeBytes(2, privateKey_);\n }\n if (((bitField0_ & 0x00000008) == 0x00000008)) {\n output.writeBytes(3, publicKey_);\n }\n if (((bitField0_ & 0x00000010) == 0x00000010)) {\n output.writeBytes(4, getLabelBytes());\n }\n if (((bitField0_ & 0x00000020) == 0x00000020)) {\n output.writeInt64(5, creationTimestamp_);\n }\n if (((bitField0_ & 0x00000004) == 0x00000004)) {\n output.writeMessage(6, encryptedPrivateKey_);\n }\n getUnknownFields().writeTo(output);\n }\n\n private int memoizedSerializedSize = -1;\n public int getSerializedSize() {\n int size = memoizedSerializedSize;\n if (size != -1) return size;\n\n size = 0;\n if (((bitField0_ & 0x00000001) == 0x00000001)) {\n size += com.google.protobuf.CodedOutputStream\n .computeEnumSize(1, type_.getNumber());\n }\n if (((bitField0_ & 0x00000002) == 0x00000002)) {\n size += com.google.protobuf.CodedOutputStream\n .computeBytesSize(2, privateKey_);\n }\n if (((bitField0_ & 0x00000008) == 0x00000008)) {\n size += com.google.protobuf.CodedOutputStream\n .computeBytesSize(3, publicKey_);\n }\n if (((bitField0_ & 0x00000010) == 0x00000010)) {\n size += com.google.protobuf.CodedOutputStream\n .computeBytesSize(4, getLabelBytes());\n }\n if (((bitField0_ & 0x00000020) == 0x00000020)) {\n size += com.google.protobuf.CodedOutputStream\n .computeInt64Size(5, creationTimestamp_);\n }\n if (((bitField0_ & 0x00000004) == 0x00000004)) {\n size += com.google.protobuf.CodedOutputStream\n .computeMessageSize(6, encryptedPrivateKey_);\n }\n size += getUnknownFields().getSerializedSize();\n memoizedSerializedSize = size;\n return size;\n }\n\n private static final long serialVersionUID = 0L;\n @java.lang.Override\n protected java.lang.Object writeReplace()\n throws java.io.ObjectStreamException {\n return super.writeReplace();\n }\n\n public static org.bitcoinj.wallet.Protos.Key parseFrom(\n com.google.protobuf.ByteString data)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n public static org.bitcoinj.wallet.Protos.Key parseFrom(\n com.google.protobuf.ByteString data,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n public static org.bitcoinj.wallet.Protos.Key parseFrom(byte[] data)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n public static org.bitcoinj.wallet.Protos.Key parseFrom(\n byte[] data,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n public static org.bitcoinj.wallet.Protos.Key parseFrom(java.io.InputStream input)\n throws java.io.IOException {\n return PARSER.parseFrom(input);\n }\n public static org.bitcoinj.wallet.Protos.Key parseFrom(\n java.io.InputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return PARSER.parseFrom(input, extensionRegistry);\n }\n public static org.bitcoinj.wallet.Protos.Key parseDelimitedFrom(java.io.InputStream input)\n throws java.io.IOException {\n return PARSER.parseDelimitedFrom(input);\n }\n public static org.bitcoinj.wallet.Protos.Key parseDelimitedFrom(\n java.io.InputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return PARSER.parseDelimitedFrom(input, extensionRegistry);\n }\n public static org.bitcoinj.wallet.Protos.Key parseFrom(\n com.google.protobuf.CodedInputStream input)\n throws java.io.IOException {\n return PARSER.parseFrom(input);\n }\n public static org.bitcoinj.wallet.Protos.Key parseFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return PARSER.parseFrom(input, extensionRegistry);\n }\n\n public static Builder newBuilder() { return Builder.create(); }\n public Builder newBuilderForType() { return newBuilder(); }\n public static Builder newBuilder(org.bitcoinj.wallet.Protos.Key prototype) {\n return newBuilder().mergeFrom(prototype);\n }\n public Builder toBuilder() { return newBuilder(this); }\n\n @java.lang.Override\n protected Builder newBuilderForType(\n com.google.protobuf.GeneratedMessage.BuilderParent parent) {\n Builder builder = new Builder(parent);\n return builder;\n }\n /**\n * Protobuf type {@code wallet.Key}\n *\n * <pre>\n **\n * A key used to control Bitcoin spending.\n *\n * Either the private key, the public key or both may be present. It is recommended that\n * if the private key is provided that the public key is provided too because deriving it is slow.\n *\n * If only the public key is provided, the key can only be used to watch the blockchain and verify\n * transactions, and not for spending.\n * </pre>\n */\n public static final class Builder extends\n com.google.protobuf.GeneratedMessage.Builder<Builder>\n implements org.bitcoinj.wallet.Protos.KeyOrBuilder {\n public static final com.google.protobuf.Descriptors.Descriptor\n getDescriptor() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_Key_descriptor;\n }\n\n protected com.google.protobuf.GeneratedMessage.FieldAccessorTable\n internalGetFieldAccessorTable() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_Key_fieldAccessorTable\n .ensureFieldAccessorsInitialized(\n org.bitcoinj.wallet.Protos.Key.class, org.bitcoinj.wallet.Protos.Key.Builder.class);\n }\n\n // Construct using org.bitcoinj.wallet.Protos.Key.newBuilder()\n private Builder() {\n maybeForceBuilderInitialization();\n }\n\n private Builder(\n com.google.protobuf.GeneratedMessage.BuilderParent parent) {\n super(parent);\n maybeForceBuilderInitialization();\n }\n private void maybeForceBuilderInitialization() {\n if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {\n getEncryptedPrivateKeyFieldBuilder();\n }\n }\n private static Builder create() {\n return new Builder();\n }\n\n public Builder clear() {\n super.clear();\n type_ = org.bitcoinj.wallet.Protos.Key.Type.ORIGINAL;\n bitField0_ = (bitField0_ & ~0x00000001);\n privateKey_ = com.google.protobuf.ByteString.EMPTY;\n bitField0_ = (bitField0_ & ~0x00000002);\n if (encryptedPrivateKeyBuilder_ == null) {\n encryptedPrivateKey_ = org.bitcoinj.wallet.Protos.EncryptedPrivateKey.getDefaultInstance();\n } else {\n encryptedPrivateKeyBuilder_.clear();\n }\n bitField0_ = (bitField0_ & ~0x00000004);\n publicKey_ = com.google.protobuf.ByteString.EMPTY;\n bitField0_ = (bitField0_ & ~0x00000008);\n label_ = \"\";\n bitField0_ = (bitField0_ & ~0x00000010);\n creationTimestamp_ = 0L;\n bitField0_ = (bitField0_ & ~0x00000020);\n return this;\n }\n\n public Builder clone() {\n return create().mergeFrom(buildPartial());\n }\n\n public com.google.protobuf.Descriptors.Descriptor\n getDescriptorForType() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_Key_descriptor;\n }\n\n public org.bitcoinj.wallet.Protos.Key getDefaultInstanceForType() {\n return org.bitcoinj.wallet.Protos.Key.getDefaultInstance();\n }\n\n public org.bitcoinj.wallet.Protos.Key build() {\n org.bitcoinj.wallet.Protos.Key result = buildPartial();\n if (!result.isInitialized()) {\n throw newUninitializedMessageException(result);\n }\n return result;\n }\n\n public org.bitcoinj.wallet.Protos.Key buildPartial() {\n org.bitcoinj.wallet.Protos.Key result = new org.bitcoinj.wallet.Protos.Key(this);\n int from_bitField0_ = bitField0_;\n int to_bitField0_ = 0;\n if (((from_bitField0_ & 0x00000001) == 0x00000001)) {\n to_bitField0_ |= 0x00000001;\n }\n result.type_ = type_;\n if (((from_bitField0_ & 0x00000002) == 0x00000002)) {\n to_bitField0_ |= 0x00000002;\n }\n result.privateKey_ = privateKey_;\n if (((from_bitField0_ & 0x00000004) == 0x00000004)) {\n to_bitField0_ |= 0x00000004;\n }\n if (encryptedPrivateKeyBuilder_ == null) {\n result.encryptedPrivateKey_ = encryptedPrivateKey_;\n } else {\n result.encryptedPrivateKey_ = encryptedPrivateKeyBuilder_.build();\n }\n if (((from_bitField0_ & 0x00000008) == 0x00000008)) {\n to_bitField0_ |= 0x00000008;\n }\n result.publicKey_ = publicKey_;\n if (((from_bitField0_ & 0x00000010) == 0x00000010)) {\n to_bitField0_ |= 0x00000010;\n }\n result.label_ = label_;\n if (((from_bitField0_ & 0x00000020) == 0x00000020)) {\n to_bitField0_ |= 0x00000020;\n }\n result.creationTimestamp_ = creationTimestamp_;\n result.bitField0_ = to_bitField0_;\n onBuilt();\n return result;\n }\n\n public Builder mergeFrom(com.google.protobuf.Message other) {\n if (other instanceof org.bitcoinj.wallet.Protos.Key) {\n return mergeFrom((org.bitcoinj.wallet.Protos.Key)other);\n } else {\n super.mergeFrom(other);\n return this;\n }\n }\n\n public Builder mergeFrom(org.bitcoinj.wallet.Protos.Key other) {\n if (other == org.bitcoinj.wallet.Protos.Key.getDefaultInstance()) return this;\n if (other.hasType()) {\n setType(other.getType());\n }\n if (other.hasPrivateKey()) {\n setPrivateKey(other.getPrivateKey());\n }\n if (other.hasEncryptedPrivateKey()) {\n mergeEncryptedPrivateKey(other.getEncryptedPrivateKey());\n }\n if (other.hasPublicKey()) {\n setPublicKey(other.getPublicKey());\n }\n if (other.hasLabel()) {\n bitField0_ |= 0x00000010;\n label_ = other.label_;\n onChanged();\n }\n if (other.hasCreationTimestamp()) {\n setCreationTimestamp(other.getCreationTimestamp());\n }\n this.mergeUnknownFields(other.getUnknownFields());\n return this;\n }\n\n public final boolean isInitialized() {\n if (!hasType()) {\n \n return false;\n }\n if (hasEncryptedPrivateKey()) {\n if (!getEncryptedPrivateKey().isInitialized()) {\n \n return false;\n }\n }\n return true;\n }\n\n public Builder mergeFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n org.bitcoinj.wallet.Protos.Key parsedMessage = null;\n try {\n parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);\n } catch (com.google.protobuf.InvalidProtocolBufferException e) {\n parsedMessage = (org.bitcoinj.wallet.Protos.Key) e.getUnfinishedMessage();\n throw e;\n } finally {\n if (parsedMessage != null) {\n mergeFrom(parsedMessage);\n }\n }\n return this;\n }\n private int bitField0_;\n\n // required .wallet.Key.Type type = 1;\n private org.bitcoinj.wallet.Protos.Key.Type type_ = org.bitcoinj.wallet.Protos.Key.Type.ORIGINAL;\n /**\n * <code>required .wallet.Key.Type type = 1;</code>\n */\n public boolean hasType() {\n return ((bitField0_ & 0x00000001) == 0x00000001);\n }\n /**\n * <code>required .wallet.Key.Type type = 1;</code>\n */\n public org.bitcoinj.wallet.Protos.Key.Type getType() {\n return type_;\n }\n /**\n * <code>required .wallet.Key.Type type = 1;</code>\n */\n public Builder setType(org.bitcoinj.wallet.Protos.Key.Type value) {\n if (value == null) {\n throw new NullPointerException();\n }\n bitField0_ |= 0x00000001;\n type_ = value;\n onChanged();\n return this;\n }\n /**\n * <code>required .wallet.Key.Type type = 1;</code>\n */\n public Builder clearType() {\n bitField0_ = (bitField0_ & ~0x00000001);\n type_ = org.bitcoinj.wallet.Protos.Key.Type.ORIGINAL;\n onChanged();\n return this;\n }\n\n // optional bytes private_key = 2;\n private com.google.protobuf.ByteString privateKey_ = com.google.protobuf.ByteString.EMPTY;\n /**\n * <code>optional bytes private_key = 2;</code>\n *\n * <pre>\n * The private EC key bytes without any ASN.1 wrapping.\n * </pre>\n */\n public boolean hasPrivateKey() {\n return ((bitField0_ & 0x00000002) == 0x00000002);\n }\n /**\n * <code>optional bytes private_key = 2;</code>\n *\n * <pre>\n * The private EC key bytes without any ASN.1 wrapping.\n * </pre>\n */\n public com.google.protobuf.ByteString getPrivateKey() {\n return privateKey_;\n }\n /**\n * <code>optional bytes private_key = 2;</code>\n *\n * <pre>\n * The private EC key bytes without any ASN.1 wrapping.\n * </pre>\n */\n public Builder setPrivateKey(com.google.protobuf.ByteString value) {\n if (value == null) {\n throw new NullPointerException();\n }\n bitField0_ |= 0x00000002;\n privateKey_ = value;\n onChanged();\n return this;\n }\n /**\n * <code>optional bytes private_key = 2;</code>\n *\n * <pre>\n * The private EC key bytes without any ASN.1 wrapping.\n * </pre>\n */\n public Builder clearPrivateKey() {\n bitField0_ = (bitField0_ & ~0x00000002);\n privateKey_ = getDefaultInstance().getPrivateKey();\n onChanged();\n return this;\n }\n\n // optional .wallet.EncryptedPrivateKey encrypted_private_key = 6;\n private org.bitcoinj.wallet.Protos.EncryptedPrivateKey encryptedPrivateKey_ = org.bitcoinj.wallet.Protos.EncryptedPrivateKey.getDefaultInstance();\n private com.google.protobuf.SingleFieldBuilder<\n org.bitcoinj.wallet.Protos.EncryptedPrivateKey, org.bitcoinj.wallet.Protos.EncryptedPrivateKey.Builder, org.bitcoinj.wallet.Protos.EncryptedPrivateKeyOrBuilder> encryptedPrivateKeyBuilder_;\n /**\n * <code>optional .wallet.EncryptedPrivateKey encrypted_private_key = 6;</code>\n *\n * <pre>\n * The message containing the encrypted private EC key information.\n * When an EncryptedPrivateKey is present then the (unencrypted) private_key will be a zero length byte array or contain all zeroes.\n * This is for security of the private key information.\n * </pre>\n */\n public boolean hasEncryptedPrivateKey() {\n return ((bitField0_ & 0x00000004) == 0x00000004);\n }\n /**\n * <code>optional .wallet.EncryptedPrivateKey encrypted_private_key = 6;</code>\n *\n * <pre>\n * The message containing the encrypted private EC key information.\n * When an EncryptedPrivateKey is present then the (unencrypted) private_key will be a zero length byte array or contain all zeroes.\n * This is for security of the private key information.\n * </pre>\n */\n public org.bitcoinj.wallet.Protos.EncryptedPrivateKey getEncryptedPrivateKey() {\n if (encryptedPrivateKeyBuilder_ == null) {\n return encryptedPrivateKey_;\n } else {\n return encryptedPrivateKeyBuilder_.getMessage();\n }\n }\n /**\n * <code>optional .wallet.EncryptedPrivateKey encrypted_private_key = 6;</code>\n *\n * <pre>\n * The message containing the encrypted private EC key information.\n * When an EncryptedPrivateKey is present then the (unencrypted) private_key will be a zero length byte array or contain all zeroes.\n * This is for security of the private key information.\n * </pre>\n */\n public Builder setEncryptedPrivateKey(org.bitcoinj.wallet.Protos.EncryptedPrivateKey value) {\n if (encryptedPrivateKeyBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n encryptedPrivateKey_ = value;\n onChanged();\n } else {\n encryptedPrivateKeyBuilder_.setMessage(value);\n }\n bitField0_ |= 0x00000004;\n return this;\n }\n /**\n * <code>optional .wallet.EncryptedPrivateKey encrypted_private_key = 6;</code>\n *\n * <pre>\n * The message containing the encrypted private EC key information.\n * When an EncryptedPrivateKey is present then the (unencrypted) private_key will be a zero length byte array or contain all zeroes.\n * This is for security of the private key information.\n * </pre>\n */\n public Builder setEncryptedPrivateKey(\n org.bitcoinj.wallet.Protos.EncryptedPrivateKey.Builder builderForValue) {\n if (encryptedPrivateKeyBuilder_ == null) {\n encryptedPrivateKey_ = builderForValue.build();\n onChanged();\n } else {\n encryptedPrivateKeyBuilder_.setMessage(builderForValue.build());\n }\n bitField0_ |= 0x00000004;\n return this;\n }\n /**\n * <code>optional .wallet.EncryptedPrivateKey encrypted_private_key = 6;</code>\n *\n * <pre>\n * The message containing the encrypted private EC key information.\n * When an EncryptedPrivateKey is present then the (unencrypted) private_key will be a zero length byte array or contain all zeroes.\n * This is for security of the private key information.\n * </pre>\n */\n public Builder mergeEncryptedPrivateKey(org.bitcoinj.wallet.Protos.EncryptedPrivateKey value) {\n if (encryptedPrivateKeyBuilder_ == null) {\n if (((bitField0_ & 0x00000004) == 0x00000004) &&\n encryptedPrivateKey_ != org.bitcoinj.wallet.Protos.EncryptedPrivateKey.getDefaultInstance()) {\n encryptedPrivateKey_ =\n org.bitcoinj.wallet.Protos.EncryptedPrivateKey.newBuilder(encryptedPrivateKey_).mergeFrom(value).buildPartial();\n } else {\n encryptedPrivateKey_ = value;\n }\n onChanged();\n } else {\n encryptedPrivateKeyBuilder_.mergeFrom(value);\n }\n bitField0_ |= 0x00000004;\n return this;\n }\n /**\n * <code>optional .wallet.EncryptedPrivateKey encrypted_private_key = 6;</code>\n *\n * <pre>\n * The message containing the encrypted private EC key information.\n * When an EncryptedPrivateKey is present then the (unencrypted) private_key will be a zero length byte array or contain all zeroes.\n * This is for security of the private key information.\n * </pre>\n */\n public Builder clearEncryptedPrivateKey() {\n if (encryptedPrivateKeyBuilder_ == null) {\n encryptedPrivateKey_ = org.bitcoinj.wallet.Protos.EncryptedPrivateKey.getDefaultInstance();\n onChanged();\n } else {\n encryptedPrivateKeyBuilder_.clear();\n }\n bitField0_ = (bitField0_ & ~0x00000004);\n return this;\n }\n /**\n * <code>optional .wallet.EncryptedPrivateKey encrypted_private_key = 6;</code>\n *\n * <pre>\n * The message containing the encrypted private EC key information.\n * When an EncryptedPrivateKey is present then the (unencrypted) private_key will be a zero length byte array or contain all zeroes.\n * This is for security of the private key information.\n * </pre>\n */\n public org.bitcoinj.wallet.Protos.EncryptedPrivateKey.Builder getEncryptedPrivateKeyBuilder() {\n bitField0_ |= 0x00000004;\n onChanged();\n return getEncryptedPrivateKeyFieldBuilder().getBuilder();\n }\n /**\n * <code>optional .wallet.EncryptedPrivateKey encrypted_private_key = 6;</code>\n *\n * <pre>\n * The message containing the encrypted private EC key information.\n * When an EncryptedPrivateKey is present then the (unencrypted) private_key will be a zero length byte array or contain all zeroes.\n * This is for security of the private key information.\n * </pre>\n */\n public org.bitcoinj.wallet.Protos.EncryptedPrivateKeyOrBuilder getEncryptedPrivateKeyOrBuilder() {\n if (encryptedPrivateKeyBuilder_ != null) {\n return encryptedPrivateKeyBuilder_.getMessageOrBuilder();\n } else {\n return encryptedPrivateKey_;\n }\n }\n /**\n * <code>optional .wallet.EncryptedPrivateKey encrypted_private_key = 6;</code>\n *\n * <pre>\n * The message containing the encrypted private EC key information.\n * When an EncryptedPrivateKey is present then the (unencrypted) private_key will be a zero length byte array or contain all zeroes.\n * This is for security of the private key information.\n * </pre>\n */\n private com.google.protobuf.SingleFieldBuilder<\n org.bitcoinj.wallet.Protos.EncryptedPrivateKey, org.bitcoinj.wallet.Protos.EncryptedPrivateKey.Builder, org.bitcoinj.wallet.Protos.EncryptedPrivateKeyOrBuilder> \n getEncryptedPrivateKeyFieldBuilder() {\n if (encryptedPrivateKeyBuilder_ == null) {\n encryptedPrivateKeyBuilder_ = new com.google.protobuf.SingleFieldBuilder<\n org.bitcoinj.wallet.Protos.EncryptedPrivateKey, org.bitcoinj.wallet.Protos.EncryptedPrivateKey.Builder, org.bitcoinj.wallet.Protos.EncryptedPrivateKeyOrBuilder>(\n encryptedPrivateKey_,\n getParentForChildren(),\n isClean());\n encryptedPrivateKey_ = null;\n }\n return encryptedPrivateKeyBuilder_;\n }\n\n // optional bytes public_key = 3;\n private com.google.protobuf.ByteString publicKey_ = com.google.protobuf.ByteString.EMPTY;\n /**\n * <code>optional bytes public_key = 3;</code>\n *\n * <pre>\n * The public EC key derived from the private key. We allow both to be stored to avoid mobile clients having to\n * do lots of slow EC math on startup.\n * </pre>\n */\n public boolean hasPublicKey() {\n return ((bitField0_ & 0x00000008) == 0x00000008);\n }\n /**\n * <code>optional bytes public_key = 3;</code>\n *\n * <pre>\n * The public EC key derived from the private key. We allow both to be stored to avoid mobile clients having to\n * do lots of slow EC math on startup.\n * </pre>\n */\n public com.google.protobuf.ByteString getPublicKey() {\n return publicKey_;\n }\n /**\n * <code>optional bytes public_key = 3;</code>\n *\n * <pre>\n * The public EC key derived from the private key. We allow both to be stored to avoid mobile clients having to\n * do lots of slow EC math on startup.\n * </pre>\n */\n public Builder setPublicKey(com.google.protobuf.ByteString value) {\n if (value == null) {\n throw new NullPointerException();\n }\n bitField0_ |= 0x00000008;\n publicKey_ = value;\n onChanged();\n return this;\n }\n /**\n * <code>optional bytes public_key = 3;</code>\n *\n * <pre>\n * The public EC key derived from the private key. We allow both to be stored to avoid mobile clients having to\n * do lots of slow EC math on startup.\n * </pre>\n */\n public Builder clearPublicKey() {\n bitField0_ = (bitField0_ & ~0x00000008);\n publicKey_ = getDefaultInstance().getPublicKey();\n onChanged();\n return this;\n }\n\n // optional string label = 4;\n private java.lang.Object label_ = \"\";\n /**\n * <code>optional string label = 4;</code>\n *\n * <pre>\n * User-provided label associated with the key.\n * </pre>\n */\n public boolean hasLabel() {\n return ((bitField0_ & 0x00000010) == 0x00000010);\n }\n /**\n * <code>optional string label = 4;</code>\n *\n * <pre>\n * User-provided label associated with the key.\n * </pre>\n */\n public java.lang.String getLabel() {\n java.lang.Object ref = label_;\n if (!(ref instanceof java.lang.String)) {\n java.lang.String s = ((com.google.protobuf.ByteString) ref)\n .toStringUtf8();\n label_ = s;\n return s;\n } else {\n return (java.lang.String) ref;\n }\n }\n /**\n * <code>optional string label = 4;</code>\n *\n * <pre>\n * User-provided label associated with the key.\n * </pre>\n */\n public com.google.protobuf.ByteString\n getLabelBytes() {\n java.lang.Object ref = label_;\n if (ref instanceof String) {\n com.google.protobuf.ByteString b = \n com.google.protobuf.ByteString.copyFromUtf8(\n (java.lang.String) ref);\n label_ = b;\n return b;\n } else {\n return (com.google.protobuf.ByteString) ref;\n }\n }\n /**\n * <code>optional string label = 4;</code>\n *\n * <pre>\n * User-provided label associated with the key.\n * </pre>\n */\n public Builder setLabel(\n java.lang.String value) {\n if (value == null) {\n throw new NullPointerException();\n }\n bitField0_ |= 0x00000010;\n label_ = value;\n onChanged();\n return this;\n }\n /**\n * <code>optional string label = 4;</code>\n *\n * <pre>\n * User-provided label associated with the key.\n * </pre>\n */\n public Builder clearLabel() {\n bitField0_ = (bitField0_ & ~0x00000010);\n label_ = getDefaultInstance().getLabel();\n onChanged();\n return this;\n }\n /**\n * <code>optional string label = 4;</code>\n *\n * <pre>\n * User-provided label associated with the key.\n * </pre>\n */\n public Builder setLabelBytes(\n com.google.protobuf.ByteString value) {\n if (value == null) {\n throw new NullPointerException();\n }\n bitField0_ |= 0x00000010;\n label_ = value;\n onChanged();\n return this;\n }\n\n // optional int64 creation_timestamp = 5;\n private long creationTimestamp_ ;\n /**\n * <code>optional int64 creation_timestamp = 5;</code>\n *\n * <pre>\n * Timestamp stored as millis since epoch. Useful for skipping block bodies before this point.\n * </pre>\n */\n public boolean hasCreationTimestamp() {\n return ((bitField0_ & 0x00000020) == 0x00000020);\n }\n /**\n * <code>optional int64 creation_timestamp = 5;</code>\n *\n * <pre>\n * Timestamp stored as millis since epoch. Useful for skipping block bodies before this point.\n * </pre>\n */\n public long getCreationTimestamp() {\n return creationTimestamp_;\n }\n /**\n * <code>optional int64 creation_timestamp = 5;</code>\n *\n * <pre>\n * Timestamp stored as millis since epoch. Useful for skipping block bodies before this point.\n * </pre>\n */\n public Builder setCreationTimestamp(long value) {\n bitField0_ |= 0x00000020;\n creationTimestamp_ = value;\n onChanged();\n return this;\n }\n /**\n * <code>optional int64 creation_timestamp = 5;</code>\n *\n * <pre>\n * Timestamp stored as millis since epoch. Useful for skipping block bodies before this point.\n * </pre>\n */\n public Builder clearCreationTimestamp() {\n bitField0_ = (bitField0_ & ~0x00000020);\n creationTimestamp_ = 0L;\n onChanged();\n return this;\n }\n\n // @@protoc_insertion_point(builder_scope:wallet.Key)\n }\n\n static {\n defaultInstance = new Key(true);\n defaultInstance.initFields();\n }\n\n // @@protoc_insertion_point(class_scope:wallet.Key)\n }\n\n public interface ScriptOrBuilder\n extends com.google.protobuf.MessageOrBuilder {\n\n // required bytes program = 1;\n /**\n * <code>required bytes program = 1;</code>\n */\n boolean hasProgram();\n /**\n * <code>required bytes program = 1;</code>\n */\n com.google.protobuf.ByteString getProgram();\n\n // required int64 creation_timestamp = 2;\n /**\n * <code>required int64 creation_timestamp = 2;</code>\n *\n * <pre>\n * Timestamp stored as millis since epoch. Useful for skipping block bodies before this point\n * when watching for scripts on the blockchain.\n * </pre>\n */\n boolean hasCreationTimestamp();\n /**\n * <code>required int64 creation_timestamp = 2;</code>\n *\n * <pre>\n * Timestamp stored as millis since epoch. Useful for skipping block bodies before this point\n * when watching for scripts on the blockchain.\n * </pre>\n */\n long getCreationTimestamp();\n }\n /**\n * Protobuf type {@code wallet.Script}\n */\n public static final class Script extends\n com.google.protobuf.GeneratedMessage\n implements ScriptOrBuilder {\n // Use Script.newBuilder() to construct.\n private Script(com.google.protobuf.GeneratedMessage.Builder<?> builder) {\n super(builder);\n this.unknownFields = builder.getUnknownFields();\n }\n private Script(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }\n\n private static final Script defaultInstance;\n public static Script getDefaultInstance() {\n return defaultInstance;\n }\n\n public Script getDefaultInstanceForType() {\n return defaultInstance;\n }\n\n private final com.google.protobuf.UnknownFieldSet unknownFields;\n @java.lang.Override\n public final com.google.protobuf.UnknownFieldSet\n getUnknownFields() {\n return this.unknownFields;\n }\n private Script(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n initFields();\n int mutable_bitField0_ = 0;\n com.google.protobuf.UnknownFieldSet.Builder unknownFields =\n com.google.protobuf.UnknownFieldSet.newBuilder();\n try {\n boolean done = false;\n while (!done) {\n int tag = input.readTag();\n switch (tag) {\n case 0:\n done = true;\n break;\n default: {\n if (!parseUnknownField(input, unknownFields,\n extensionRegistry, tag)) {\n done = true;\n }\n break;\n }\n case 10: {\n bitField0_ |= 0x00000001;\n program_ = input.readBytes();\n break;\n }\n case 16: {\n bitField0_ |= 0x00000002;\n creationTimestamp_ = input.readInt64();\n break;\n }\n }\n }\n } catch (com.google.protobuf.InvalidProtocolBufferException e) {\n throw e.setUnfinishedMessage(this);\n } catch (java.io.IOException e) {\n throw new com.google.protobuf.InvalidProtocolBufferException(\n e.getMessage()).setUnfinishedMessage(this);\n } finally {\n this.unknownFields = unknownFields.build();\n makeExtensionsImmutable();\n }\n }\n public static final com.google.protobuf.Descriptors.Descriptor\n getDescriptor() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_Script_descriptor;\n }\n\n protected com.google.protobuf.GeneratedMessage.FieldAccessorTable\n internalGetFieldAccessorTable() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_Script_fieldAccessorTable\n .ensureFieldAccessorsInitialized(\n org.bitcoinj.wallet.Protos.Script.class, org.bitcoinj.wallet.Protos.Script.Builder.class);\n }\n\n public static com.google.protobuf.Parser<Script> PARSER =\n new com.google.protobuf.AbstractParser<Script>() {\n public Script parsePartialFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return new Script(input, extensionRegistry);\n }\n };\n\n @java.lang.Override\n public com.google.protobuf.Parser<Script> getParserForType() {\n return PARSER;\n }\n\n private int bitField0_;\n // required bytes program = 1;\n public static final int PROGRAM_FIELD_NUMBER = 1;\n private com.google.protobuf.ByteString program_;\n /**\n * <code>required bytes program = 1;</code>\n */\n public boolean hasProgram() {\n return ((bitField0_ & 0x00000001) == 0x00000001);\n }\n /**\n * <code>required bytes program = 1;</code>\n */\n public com.google.protobuf.ByteString getProgram() {\n return program_;\n }\n\n // required int64 creation_timestamp = 2;\n public static final int CREATION_TIMESTAMP_FIELD_NUMBER = 2;\n private long creationTimestamp_;\n /**\n * <code>required int64 creation_timestamp = 2;</code>\n *\n * <pre>\n * Timestamp stored as millis since epoch. Useful for skipping block bodies before this point\n * when watching for scripts on the blockchain.\n * </pre>\n */\n public boolean hasCreationTimestamp() {\n return ((bitField0_ & 0x00000002) == 0x00000002);\n }\n /**\n * <code>required int64 creation_timestamp = 2;</code>\n *\n * <pre>\n * Timestamp stored as millis since epoch. Useful for skipping block bodies before this point\n * when watching for scripts on the blockchain.\n * </pre>\n */\n public long getCreationTimestamp() {\n return creationTimestamp_;\n }\n\n private void initFields() {\n program_ = com.google.protobuf.ByteString.EMPTY;\n creationTimestamp_ = 0L;\n }\n private byte memoizedIsInitialized = -1;\n public final boolean isInitialized() {\n byte isInitialized = memoizedIsInitialized;\n if (isInitialized != -1) return isInitialized == 1;\n\n if (!hasProgram()) {\n memoizedIsInitialized = 0;\n return false;\n }\n if (!hasCreationTimestamp()) {\n memoizedIsInitialized = 0;\n return false;\n }\n memoizedIsInitialized = 1;\n return true;\n }\n\n public void writeTo(com.google.protobuf.CodedOutputStream output)\n throws java.io.IOException {\n getSerializedSize();\n if (((bitField0_ & 0x00000001) == 0x00000001)) {\n output.writeBytes(1, program_);\n }\n if (((bitField0_ & 0x00000002) == 0x00000002)) {\n output.writeInt64(2, creationTimestamp_);\n }\n getUnknownFields().writeTo(output);\n }\n\n private int memoizedSerializedSize = -1;\n public int getSerializedSize() {\n int size = memoizedSerializedSize;\n if (size != -1) return size;\n\n size = 0;\n if (((bitField0_ & 0x00000001) == 0x00000001)) {\n size += com.google.protobuf.CodedOutputStream\n .computeBytesSize(1, program_);\n }\n if (((bitField0_ & 0x00000002) == 0x00000002)) {\n size += com.google.protobuf.CodedOutputStream\n .computeInt64Size(2, creationTimestamp_);\n }\n size += getUnknownFields().getSerializedSize();\n memoizedSerializedSize = size;\n return size;\n }\n\n private static final long serialVersionUID = 0L;\n @java.lang.Override\n protected java.lang.Object writeReplace()\n throws java.io.ObjectStreamException {\n return super.writeReplace();\n }\n\n public static org.bitcoinj.wallet.Protos.Script parseFrom(\n com.google.protobuf.ByteString data)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n public static org.bitcoinj.wallet.Protos.Script parseFrom(\n com.google.protobuf.ByteString data,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n public static org.bitcoinj.wallet.Protos.Script parseFrom(byte[] data)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n public static org.bitcoinj.wallet.Protos.Script parseFrom(\n byte[] data,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n public static org.bitcoinj.wallet.Protos.Script parseFrom(java.io.InputStream input)\n throws java.io.IOException {\n return PARSER.parseFrom(input);\n }\n public static org.bitcoinj.wallet.Protos.Script parseFrom(\n java.io.InputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return PARSER.parseFrom(input, extensionRegistry);\n }\n public static org.bitcoinj.wallet.Protos.Script parseDelimitedFrom(java.io.InputStream input)\n throws java.io.IOException {\n return PARSER.parseDelimitedFrom(input);\n }\n public static org.bitcoinj.wallet.Protos.Script parseDelimitedFrom(\n java.io.InputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return PARSER.parseDelimitedFrom(input, extensionRegistry);\n }\n public static org.bitcoinj.wallet.Protos.Script parseFrom(\n com.google.protobuf.CodedInputStream input)\n throws java.io.IOException {\n return PARSER.parseFrom(input);\n }\n public static org.bitcoinj.wallet.Protos.Script parseFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return PARSER.parseFrom(input, extensionRegistry);\n }\n\n public static Builder newBuilder() { return Builder.create(); }\n public Builder newBuilderForType() { return newBuilder(); }\n public static Builder newBuilder(org.bitcoinj.wallet.Protos.Script prototype) {\n return newBuilder().mergeFrom(prototype);\n }\n public Builder toBuilder() { return newBuilder(this); }\n\n @java.lang.Override\n protected Builder newBuilderForType(\n com.google.protobuf.GeneratedMessage.BuilderParent parent) {\n Builder builder = new Builder(parent);\n return builder;\n }\n /**\n * Protobuf type {@code wallet.Script}\n */\n public static final class Builder extends\n com.google.protobuf.GeneratedMessage.Builder<Builder>\n implements org.bitcoinj.wallet.Protos.ScriptOrBuilder {\n public static final com.google.protobuf.Descriptors.Descriptor\n getDescriptor() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_Script_descriptor;\n }\n\n protected com.google.protobuf.GeneratedMessage.FieldAccessorTable\n internalGetFieldAccessorTable() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_Script_fieldAccessorTable\n .ensureFieldAccessorsInitialized(\n org.bitcoinj.wallet.Protos.Script.class, org.bitcoinj.wallet.Protos.Script.Builder.class);\n }\n\n // Construct using org.bitcoinj.wallet.Protos.Script.newBuilder()\n private Builder() {\n maybeForceBuilderInitialization();\n }\n\n private Builder(\n com.google.protobuf.GeneratedMessage.BuilderParent parent) {\n super(parent);\n maybeForceBuilderInitialization();\n }\n private void maybeForceBuilderInitialization() {\n if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {\n }\n }\n private static Builder create() {\n return new Builder();\n }\n\n public Builder clear() {\n super.clear();\n program_ = com.google.protobuf.ByteString.EMPTY;\n bitField0_ = (bitField0_ & ~0x00000001);\n creationTimestamp_ = 0L;\n bitField0_ = (bitField0_ & ~0x00000002);\n return this;\n }\n\n public Builder clone() {\n return create().mergeFrom(buildPartial());\n }\n\n public com.google.protobuf.Descriptors.Descriptor\n getDescriptorForType() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_Script_descriptor;\n }\n\n public org.bitcoinj.wallet.Protos.Script getDefaultInstanceForType() {\n return org.bitcoinj.wallet.Protos.Script.getDefaultInstance();\n }\n\n public org.bitcoinj.wallet.Protos.Script build() {\n org.bitcoinj.wallet.Protos.Script result = buildPartial();\n if (!result.isInitialized()) {\n throw newUninitializedMessageException(result);\n }\n return result;\n }\n\n public org.bitcoinj.wallet.Protos.Script buildPartial() {\n org.bitcoinj.wallet.Protos.Script result = new org.bitcoinj.wallet.Protos.Script(this);\n int from_bitField0_ = bitField0_;\n int to_bitField0_ = 0;\n if (((from_bitField0_ & 0x00000001) == 0x00000001)) {\n to_bitField0_ |= 0x00000001;\n }\n result.program_ = program_;\n if (((from_bitField0_ & 0x00000002) == 0x00000002)) {\n to_bitField0_ |= 0x00000002;\n }\n result.creationTimestamp_ = creationTimestamp_;\n result.bitField0_ = to_bitField0_;\n onBuilt();\n return result;\n }\n\n public Builder mergeFrom(com.google.protobuf.Message other) {\n if (other instanceof org.bitcoinj.wallet.Protos.Script) {\n return mergeFrom((org.bitcoinj.wallet.Protos.Script)other);\n } else {\n super.mergeFrom(other);\n return this;\n }\n }\n\n public Builder mergeFrom(org.bitcoinj.wallet.Protos.Script other) {\n if (other == org.bitcoinj.wallet.Protos.Script.getDefaultInstance()) return this;\n if (other.hasProgram()) {\n setProgram(other.getProgram());\n }\n if (other.hasCreationTimestamp()) {\n setCreationTimestamp(other.getCreationTimestamp());\n }\n this.mergeUnknownFields(other.getUnknownFields());\n return this;\n }\n\n public final boolean isInitialized() {\n if (!hasProgram()) {\n \n return false;\n }\n if (!hasCreationTimestamp()) {\n \n return false;\n }\n return true;\n }\n\n public Builder mergeFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n org.bitcoinj.wallet.Protos.Script parsedMessage = null;\n try {\n parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);\n } catch (com.google.protobuf.InvalidProtocolBufferException e) {\n parsedMessage = (org.bitcoinj.wallet.Protos.Script) e.getUnfinishedMessage();\n throw e;\n } finally {\n if (parsedMessage != null) {\n mergeFrom(parsedMessage);\n }\n }\n return this;\n }\n private int bitField0_;\n\n // required bytes program = 1;\n private com.google.protobuf.ByteString program_ = com.google.protobuf.ByteString.EMPTY;\n /**\n * <code>required bytes program = 1;</code>\n */\n public boolean hasProgram() {\n return ((bitField0_ & 0x00000001) == 0x00000001);\n }\n /**\n * <code>required bytes program = 1;</code>\n */\n public com.google.protobuf.ByteString getProgram() {\n return program_;\n }\n /**\n * <code>required bytes program = 1;</code>\n */\n public Builder setProgram(com.google.protobuf.ByteString value) {\n if (value == null) {\n throw new NullPointerException();\n }\n bitField0_ |= 0x00000001;\n program_ = value;\n onChanged();\n return this;\n }\n /**\n * <code>required bytes program = 1;</code>\n */\n public Builder clearProgram() {\n bitField0_ = (bitField0_ & ~0x00000001);\n program_ = getDefaultInstance().getProgram();\n onChanged();\n return this;\n }\n\n // required int64 creation_timestamp = 2;\n private long creationTimestamp_ ;\n /**\n * <code>required int64 creation_timestamp = 2;</code>\n *\n * <pre>\n * Timestamp stored as millis since epoch. Useful for skipping block bodies before this point\n * when watching for scripts on the blockchain.\n * </pre>\n */\n public boolean hasCreationTimestamp() {\n return ((bitField0_ & 0x00000002) == 0x00000002);\n }\n /**\n * <code>required int64 creation_timestamp = 2;</code>\n *\n * <pre>\n * Timestamp stored as millis since epoch. Useful for skipping block bodies before this point\n * when watching for scripts on the blockchain.\n * </pre>\n */\n public long getCreationTimestamp() {\n return creationTimestamp_;\n }\n /**\n * <code>required int64 creation_timestamp = 2;</code>\n *\n * <pre>\n * Timestamp stored as millis since epoch. Useful for skipping block bodies before this point\n * when watching for scripts on the blockchain.\n * </pre>\n */\n public Builder setCreationTimestamp(long value) {\n bitField0_ |= 0x00000002;\n creationTimestamp_ = value;\n onChanged();\n return this;\n }\n /**\n * <code>required int64 creation_timestamp = 2;</code>\n *\n * <pre>\n * Timestamp stored as millis since epoch. Useful for skipping block bodies before this point\n * when watching for scripts on the blockchain.\n * </pre>\n */\n public Builder clearCreationTimestamp() {\n bitField0_ = (bitField0_ & ~0x00000002);\n creationTimestamp_ = 0L;\n onChanged();\n return this;\n }\n\n // @@protoc_insertion_point(builder_scope:wallet.Script)\n }\n\n static {\n defaultInstance = new Script(true);\n defaultInstance.initFields();\n }\n\n // @@protoc_insertion_point(class_scope:wallet.Script)\n }\n\n public interface TransactionInputOrBuilder\n extends com.google.protobuf.MessageOrBuilder {\n\n // required bytes transaction_out_point_hash = 1;\n /**\n * <code>required bytes transaction_out_point_hash = 1;</code>\n *\n * <pre>\n * Hash of the transaction this input is using.\n * </pre>\n */\n boolean hasTransactionOutPointHash();\n /**\n * <code>required bytes transaction_out_point_hash = 1;</code>\n *\n * <pre>\n * Hash of the transaction this input is using.\n * </pre>\n */\n com.google.protobuf.ByteString getTransactionOutPointHash();\n\n // required uint32 transaction_out_point_index = 2;\n /**\n * <code>required uint32 transaction_out_point_index = 2;</code>\n *\n * <pre>\n * Index of transaction output used by this input.\n * </pre>\n */\n boolean hasTransactionOutPointIndex();\n /**\n * <code>required uint32 transaction_out_point_index = 2;</code>\n *\n * <pre>\n * Index of transaction output used by this input.\n * </pre>\n */\n int getTransactionOutPointIndex();\n\n // required bytes script_bytes = 3;\n /**\n * <code>required bytes script_bytes = 3;</code>\n *\n * <pre>\n * Script that contains the signatures/pubkeys.\n * </pre>\n */\n boolean hasScriptBytes();\n /**\n * <code>required bytes script_bytes = 3;</code>\n *\n * <pre>\n * Script that contains the signatures/pubkeys.\n * </pre>\n */\n com.google.protobuf.ByteString getScriptBytes();\n\n // optional uint32 sequence = 4;\n /**\n * <code>optional uint32 sequence = 4;</code>\n *\n * <pre>\n * Sequence number. Currently unused, but intended for contracts in future.\n * </pre>\n */\n boolean hasSequence();\n /**\n * <code>optional uint32 sequence = 4;</code>\n *\n * <pre>\n * Sequence number. Currently unused, but intended for contracts in future.\n * </pre>\n */\n int getSequence();\n }\n /**\n * Protobuf type {@code wallet.TransactionInput}\n */\n public static final class TransactionInput extends\n com.google.protobuf.GeneratedMessage\n implements TransactionInputOrBuilder {\n // Use TransactionInput.newBuilder() to construct.\n private TransactionInput(com.google.protobuf.GeneratedMessage.Builder<?> builder) {\n super(builder);\n this.unknownFields = builder.getUnknownFields();\n }\n private TransactionInput(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }\n\n private static final TransactionInput defaultInstance;\n public static TransactionInput getDefaultInstance() {\n return defaultInstance;\n }\n\n public TransactionInput getDefaultInstanceForType() {\n return defaultInstance;\n }\n\n private final com.google.protobuf.UnknownFieldSet unknownFields;\n @java.lang.Override\n public final com.google.protobuf.UnknownFieldSet\n getUnknownFields() {\n return this.unknownFields;\n }\n private TransactionInput(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n initFields();\n int mutable_bitField0_ = 0;\n com.google.protobuf.UnknownFieldSet.Builder unknownFields =\n com.google.protobuf.UnknownFieldSet.newBuilder();\n try {\n boolean done = false;\n while (!done) {\n int tag = input.readTag();\n switch (tag) {\n case 0:\n done = true;\n break;\n default: {\n if (!parseUnknownField(input, unknownFields,\n extensionRegistry, tag)) {\n done = true;\n }\n break;\n }\n case 10: {\n bitField0_ |= 0x00000001;\n transactionOutPointHash_ = input.readBytes();\n break;\n }\n case 16: {\n bitField0_ |= 0x00000002;\n transactionOutPointIndex_ = input.readUInt32();\n break;\n }\n case 26: {\n bitField0_ |= 0x00000004;\n scriptBytes_ = input.readBytes();\n break;\n }\n case 32: {\n bitField0_ |= 0x00000008;\n sequence_ = input.readUInt32();\n break;\n }\n }\n }\n } catch (com.google.protobuf.InvalidProtocolBufferException e) {\n throw e.setUnfinishedMessage(this);\n } catch (java.io.IOException e) {\n throw new com.google.protobuf.InvalidProtocolBufferException(\n e.getMessage()).setUnfinishedMessage(this);\n } finally {\n this.unknownFields = unknownFields.build();\n makeExtensionsImmutable();\n }\n }\n public static final com.google.protobuf.Descriptors.Descriptor\n getDescriptor() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_TransactionInput_descriptor;\n }\n\n protected com.google.protobuf.GeneratedMessage.FieldAccessorTable\n internalGetFieldAccessorTable() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_TransactionInput_fieldAccessorTable\n .ensureFieldAccessorsInitialized(\n org.bitcoinj.wallet.Protos.TransactionInput.class, org.bitcoinj.wallet.Protos.TransactionInput.Builder.class);\n }\n\n public static com.google.protobuf.Parser<TransactionInput> PARSER =\n new com.google.protobuf.AbstractParser<TransactionInput>() {\n public TransactionInput parsePartialFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return new TransactionInput(input, extensionRegistry);\n }\n };\n\n @java.lang.Override\n public com.google.protobuf.Parser<TransactionInput> getParserForType() {\n return PARSER;\n }\n\n private int bitField0_;\n // required bytes transaction_out_point_hash = 1;\n public static final int TRANSACTION_OUT_POINT_HASH_FIELD_NUMBER = 1;\n private com.google.protobuf.ByteString transactionOutPointHash_;\n /**\n * <code>required bytes transaction_out_point_hash = 1;</code>\n *\n * <pre>\n * Hash of the transaction this input is using.\n * </pre>\n */\n public boolean hasTransactionOutPointHash() {\n return ((bitField0_ & 0x00000001) == 0x00000001);\n }\n /**\n * <code>required bytes transaction_out_point_hash = 1;</code>\n *\n * <pre>\n * Hash of the transaction this input is using.\n * </pre>\n */\n public com.google.protobuf.ByteString getTransactionOutPointHash() {\n return transactionOutPointHash_;\n }\n\n // required uint32 transaction_out_point_index = 2;\n public static final int TRANSACTION_OUT_POINT_INDEX_FIELD_NUMBER = 2;\n private int transactionOutPointIndex_;\n /**\n * <code>required uint32 transaction_out_point_index = 2;</code>\n *\n * <pre>\n * Index of transaction output used by this input.\n * </pre>\n */\n public boolean hasTransactionOutPointIndex() {\n return ((bitField0_ & 0x00000002) == 0x00000002);\n }\n /**\n * <code>required uint32 transaction_out_point_index = 2;</code>\n *\n * <pre>\n * Index of transaction output used by this input.\n * </pre>\n */\n public int getTransactionOutPointIndex() {\n return transactionOutPointIndex_;\n }\n\n // required bytes script_bytes = 3;\n public static final int SCRIPT_BYTES_FIELD_NUMBER = 3;\n private com.google.protobuf.ByteString scriptBytes_;\n /**\n * <code>required bytes script_bytes = 3;</code>\n *\n * <pre>\n * Script that contains the signatures/pubkeys.\n * </pre>\n */\n public boolean hasScriptBytes() {\n return ((bitField0_ & 0x00000004) == 0x00000004);\n }\n /**\n * <code>required bytes script_bytes = 3;</code>\n *\n * <pre>\n * Script that contains the signatures/pubkeys.\n * </pre>\n */\n public com.google.protobuf.ByteString getScriptBytes() {\n return scriptBytes_;\n }\n\n // optional uint32 sequence = 4;\n public static final int SEQUENCE_FIELD_NUMBER = 4;\n private int sequence_;\n /**\n * <code>optional uint32 sequence = 4;</code>\n *\n * <pre>\n * Sequence number. Currently unused, but intended for contracts in future.\n * </pre>\n */\n public boolean hasSequence() {\n return ((bitField0_ & 0x00000008) == 0x00000008);\n }\n /**\n * <code>optional uint32 sequence = 4;</code>\n *\n * <pre>\n * Sequence number. Currently unused, but intended for contracts in future.\n * </pre>\n */\n public int getSequence() {\n return sequence_;\n }\n\n private void initFields() {\n transactionOutPointHash_ = com.google.protobuf.ByteString.EMPTY;\n transactionOutPointIndex_ = 0;\n scriptBytes_ = com.google.protobuf.ByteString.EMPTY;\n sequence_ = 0;\n }\n private byte memoizedIsInitialized = -1;\n public final boolean isInitialized() {\n byte isInitialized = memoizedIsInitialized;\n if (isInitialized != -1) return isInitialized == 1;\n\n if (!hasTransactionOutPointHash()) {\n memoizedIsInitialized = 0;\n return false;\n }\n if (!hasTransactionOutPointIndex()) {\n memoizedIsInitialized = 0;\n return false;\n }\n if (!hasScriptBytes()) {\n memoizedIsInitialized = 0;\n return false;\n }\n memoizedIsInitialized = 1;\n return true;\n }\n\n public void writeTo(com.google.protobuf.CodedOutputStream output)\n throws java.io.IOException {\n getSerializedSize();\n if (((bitField0_ & 0x00000001) == 0x00000001)) {\n output.writeBytes(1, transactionOutPointHash_);\n }\n if (((bitField0_ & 0x00000002) == 0x00000002)) {\n output.writeUInt32(2, transactionOutPointIndex_);\n }\n if (((bitField0_ & 0x00000004) == 0x00000004)) {\n output.writeBytes(3, scriptBytes_);\n }\n if (((bitField0_ & 0x00000008) == 0x00000008)) {\n output.writeUInt32(4, sequence_);\n }\n getUnknownFields().writeTo(output);\n }\n\n private int memoizedSerializedSize = -1;\n public int getSerializedSize() {\n int size = memoizedSerializedSize;\n if (size != -1) return size;\n\n size = 0;\n if (((bitField0_ & 0x00000001) == 0x00000001)) {\n size += com.google.protobuf.CodedOutputStream\n .computeBytesSize(1, transactionOutPointHash_);\n }\n if (((bitField0_ & 0x00000002) == 0x00000002)) {\n size += com.google.protobuf.CodedOutputStream\n .computeUInt32Size(2, transactionOutPointIndex_);\n }\n if (((bitField0_ & 0x00000004) == 0x00000004)) {\n size += com.google.protobuf.CodedOutputStream\n .computeBytesSize(3, scriptBytes_);\n }\n if (((bitField0_ & 0x00000008) == 0x00000008)) {\n size += com.google.protobuf.CodedOutputStream\n .computeUInt32Size(4, sequence_);\n }\n size += getUnknownFields().getSerializedSize();\n memoizedSerializedSize = size;\n return size;\n }\n\n private static final long serialVersionUID = 0L;\n @java.lang.Override\n protected java.lang.Object writeReplace()\n throws java.io.ObjectStreamException {\n return super.writeReplace();\n }\n\n public static org.bitcoinj.wallet.Protos.TransactionInput parseFrom(\n com.google.protobuf.ByteString data)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n public static org.bitcoinj.wallet.Protos.TransactionInput parseFrom(\n com.google.protobuf.ByteString data,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n public static org.bitcoinj.wallet.Protos.TransactionInput parseFrom(byte[] data)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n public static org.bitcoinj.wallet.Protos.TransactionInput parseFrom(\n byte[] data,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n public static org.bitcoinj.wallet.Protos.TransactionInput parseFrom(java.io.InputStream input)\n throws java.io.IOException {\n return PARSER.parseFrom(input);\n }\n public static org.bitcoinj.wallet.Protos.TransactionInput parseFrom(\n java.io.InputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return PARSER.parseFrom(input, extensionRegistry);\n }\n public static org.bitcoinj.wallet.Protos.TransactionInput parseDelimitedFrom(java.io.InputStream input)\n throws java.io.IOException {\n return PARSER.parseDelimitedFrom(input);\n }\n public static org.bitcoinj.wallet.Protos.TransactionInput parseDelimitedFrom(\n java.io.InputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return PARSER.parseDelimitedFrom(input, extensionRegistry);\n }\n public static org.bitcoinj.wallet.Protos.TransactionInput parseFrom(\n com.google.protobuf.CodedInputStream input)\n throws java.io.IOException {\n return PARSER.parseFrom(input);\n }\n public static org.bitcoinj.wallet.Protos.TransactionInput parseFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return PARSER.parseFrom(input, extensionRegistry);\n }\n\n public static Builder newBuilder() { return Builder.create(); }\n public Builder newBuilderForType() { return newBuilder(); }\n public static Builder newBuilder(org.bitcoinj.wallet.Protos.TransactionInput prototype) {\n return newBuilder().mergeFrom(prototype);\n }\n public Builder toBuilder() { return newBuilder(this); }\n\n @java.lang.Override\n protected Builder newBuilderForType(\n com.google.protobuf.GeneratedMessage.BuilderParent parent) {\n Builder builder = new Builder(parent);\n return builder;\n }\n /**\n * Protobuf type {@code wallet.TransactionInput}\n */\n public static final class Builder extends\n com.google.protobuf.GeneratedMessage.Builder<Builder>\n implements org.bitcoinj.wallet.Protos.TransactionInputOrBuilder {\n public static final com.google.protobuf.Descriptors.Descriptor\n getDescriptor() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_TransactionInput_descriptor;\n }\n\n protected com.google.protobuf.GeneratedMessage.FieldAccessorTable\n internalGetFieldAccessorTable() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_TransactionInput_fieldAccessorTable\n .ensureFieldAccessorsInitialized(\n org.bitcoinj.wallet.Protos.TransactionInput.class, org.bitcoinj.wallet.Protos.TransactionInput.Builder.class);\n }\n\n // Construct using org.bitcoinj.wallet.Protos.TransactionInput.newBuilder()\n private Builder() {\n maybeForceBuilderInitialization();\n }\n\n private Builder(\n com.google.protobuf.GeneratedMessage.BuilderParent parent) {\n super(parent);\n maybeForceBuilderInitialization();\n }\n private void maybeForceBuilderInitialization() {\n if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {\n }\n }\n private static Builder create() {\n return new Builder();\n }\n\n public Builder clear() {\n super.clear();\n transactionOutPointHash_ = com.google.protobuf.ByteString.EMPTY;\n bitField0_ = (bitField0_ & ~0x00000001);\n transactionOutPointIndex_ = 0;\n bitField0_ = (bitField0_ & ~0x00000002);\n scriptBytes_ = com.google.protobuf.ByteString.EMPTY;\n bitField0_ = (bitField0_ & ~0x00000004);\n sequence_ = 0;\n bitField0_ = (bitField0_ & ~0x00000008);\n return this;\n }\n\n public Builder clone() {\n return create().mergeFrom(buildPartial());\n }\n\n public com.google.protobuf.Descriptors.Descriptor\n getDescriptorForType() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_TransactionInput_descriptor;\n }\n\n public org.bitcoinj.wallet.Protos.TransactionInput getDefaultInstanceForType() {\n return org.bitcoinj.wallet.Protos.TransactionInput.getDefaultInstance();\n }\n\n public org.bitcoinj.wallet.Protos.TransactionInput build() {\n org.bitcoinj.wallet.Protos.TransactionInput result = buildPartial();\n if (!result.isInitialized()) {\n throw newUninitializedMessageException(result);\n }\n return result;\n }\n\n public org.bitcoinj.wallet.Protos.TransactionInput buildPartial() {\n org.bitcoinj.wallet.Protos.TransactionInput result = new org.bitcoinj.wallet.Protos.TransactionInput(this);\n int from_bitField0_ = bitField0_;\n int to_bitField0_ = 0;\n if (((from_bitField0_ & 0x00000001) == 0x00000001)) {\n to_bitField0_ |= 0x00000001;\n }\n result.transactionOutPointHash_ = transactionOutPointHash_;\n if (((from_bitField0_ & 0x00000002) == 0x00000002)) {\n to_bitField0_ |= 0x00000002;\n }\n result.transactionOutPointIndex_ = transactionOutPointIndex_;\n if (((from_bitField0_ & 0x00000004) == 0x00000004)) {\n to_bitField0_ |= 0x00000004;\n }\n result.scriptBytes_ = scriptBytes_;\n if (((from_bitField0_ & 0x00000008) == 0x00000008)) {\n to_bitField0_ |= 0x00000008;\n }\n result.sequence_ = sequence_;\n result.bitField0_ = to_bitField0_;\n onBuilt();\n return result;\n }\n\n public Builder mergeFrom(com.google.protobuf.Message other) {\n if (other instanceof org.bitcoinj.wallet.Protos.TransactionInput) {\n return mergeFrom((org.bitcoinj.wallet.Protos.TransactionInput)other);\n } else {\n super.mergeFrom(other);\n return this;\n }\n }\n\n public Builder mergeFrom(org.bitcoinj.wallet.Protos.TransactionInput other) {\n if (other == org.bitcoinj.wallet.Protos.TransactionInput.getDefaultInstance()) return this;\n if (other.hasTransactionOutPointHash()) {\n setTransactionOutPointHash(other.getTransactionOutPointHash());\n }\n if (other.hasTransactionOutPointIndex()) {\n setTransactionOutPointIndex(other.getTransactionOutPointIndex());\n }\n if (other.hasScriptBytes()) {\n setScriptBytes(other.getScriptBytes());\n }\n if (other.hasSequence()) {\n setSequence(other.getSequence());\n }\n this.mergeUnknownFields(other.getUnknownFields());\n return this;\n }\n\n public final boolean isInitialized() {\n if (!hasTransactionOutPointHash()) {\n \n return false;\n }\n if (!hasTransactionOutPointIndex()) {\n \n return false;\n }\n if (!hasScriptBytes()) {\n \n return false;\n }\n return true;\n }\n\n public Builder mergeFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n org.bitcoinj.wallet.Protos.TransactionInput parsedMessage = null;\n try {\n parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);\n } catch (com.google.protobuf.InvalidProtocolBufferException e) {\n parsedMessage = (org.bitcoinj.wallet.Protos.TransactionInput) e.getUnfinishedMessage();\n throw e;\n } finally {\n if (parsedMessage != null) {\n mergeFrom(parsedMessage);\n }\n }\n return this;\n }\n private int bitField0_;\n\n // required bytes transaction_out_point_hash = 1;\n private com.google.protobuf.ByteString transactionOutPointHash_ = com.google.protobuf.ByteString.EMPTY;\n /**\n * <code>required bytes transaction_out_point_hash = 1;</code>\n *\n * <pre>\n * Hash of the transaction this input is using.\n * </pre>\n */\n public boolean hasTransactionOutPointHash() {\n return ((bitField0_ & 0x00000001) == 0x00000001);\n }\n /**\n * <code>required bytes transaction_out_point_hash = 1;</code>\n *\n * <pre>\n * Hash of the transaction this input is using.\n * </pre>\n */\n public com.google.protobuf.ByteString getTransactionOutPointHash() {\n return transactionOutPointHash_;\n }\n /**\n * <code>required bytes transaction_out_point_hash = 1;</code>\n *\n * <pre>\n * Hash of the transaction this input is using.\n * </pre>\n */\n public Builder setTransactionOutPointHash(com.google.protobuf.ByteString value) {\n if (value == null) {\n throw new NullPointerException();\n }\n bitField0_ |= 0x00000001;\n transactionOutPointHash_ = value;\n onChanged();\n return this;\n }\n /**\n * <code>required bytes transaction_out_point_hash = 1;</code>\n *\n * <pre>\n * Hash of the transaction this input is using.\n * </pre>\n */\n public Builder clearTransactionOutPointHash() {\n bitField0_ = (bitField0_ & ~0x00000001);\n transactionOutPointHash_ = getDefaultInstance().getTransactionOutPointHash();\n onChanged();\n return this;\n }\n\n // required uint32 transaction_out_point_index = 2;\n private int transactionOutPointIndex_ ;\n /**\n * <code>required uint32 transaction_out_point_index = 2;</code>\n *\n * <pre>\n * Index of transaction output used by this input.\n * </pre>\n */\n public boolean hasTransactionOutPointIndex() {\n return ((bitField0_ & 0x00000002) == 0x00000002);\n }\n /**\n * <code>required uint32 transaction_out_point_index = 2;</code>\n *\n * <pre>\n * Index of transaction output used by this input.\n * </pre>\n */\n public int getTransactionOutPointIndex() {\n return transactionOutPointIndex_;\n }\n /**\n * <code>required uint32 transaction_out_point_index = 2;</code>\n *\n * <pre>\n * Index of transaction output used by this input.\n * </pre>\n */\n public Builder setTransactionOutPointIndex(int value) {\n bitField0_ |= 0x00000002;\n transactionOutPointIndex_ = value;\n onChanged();\n return this;\n }\n /**\n * <code>required uint32 transaction_out_point_index = 2;</code>\n *\n * <pre>\n * Index of transaction output used by this input.\n * </pre>\n */\n public Builder clearTransactionOutPointIndex() {\n bitField0_ = (bitField0_ & ~0x00000002);\n transactionOutPointIndex_ = 0;\n onChanged();\n return this;\n }\n\n // required bytes script_bytes = 3;\n private com.google.protobuf.ByteString scriptBytes_ = com.google.protobuf.ByteString.EMPTY;\n /**\n * <code>required bytes script_bytes = 3;</code>\n *\n * <pre>\n * Script that contains the signatures/pubkeys.\n * </pre>\n */\n public boolean hasScriptBytes() {\n return ((bitField0_ & 0x00000004) == 0x00000004);\n }\n /**\n * <code>required bytes script_bytes = 3;</code>\n *\n * <pre>\n * Script that contains the signatures/pubkeys.\n * </pre>\n */\n public com.google.protobuf.ByteString getScriptBytes() {\n return scriptBytes_;\n }\n /**\n * <code>required bytes script_bytes = 3;</code>\n *\n * <pre>\n * Script that contains the signatures/pubkeys.\n * </pre>\n */\n public Builder setScriptBytes(com.google.protobuf.ByteString value) {\n if (value == null) {\n throw new NullPointerException();\n }\n bitField0_ |= 0x00000004;\n scriptBytes_ = value;\n onChanged();\n return this;\n }\n /**\n * <code>required bytes script_bytes = 3;</code>\n *\n * <pre>\n * Script that contains the signatures/pubkeys.\n * </pre>\n */\n public Builder clearScriptBytes() {\n bitField0_ = (bitField0_ & ~0x00000004);\n scriptBytes_ = getDefaultInstance().getScriptBytes();\n onChanged();\n return this;\n }\n\n // optional uint32 sequence = 4;\n private int sequence_ ;\n /**\n * <code>optional uint32 sequence = 4;</code>\n *\n * <pre>\n * Sequence number. Currently unused, but intended for contracts in future.\n * </pre>\n */\n public boolean hasSequence() {\n return ((bitField0_ & 0x00000008) == 0x00000008);\n }\n /**\n * <code>optional uint32 sequence = 4;</code>\n *\n * <pre>\n * Sequence number. Currently unused, but intended for contracts in future.\n * </pre>\n */\n public int getSequence() {\n return sequence_;\n }\n /**\n * <code>optional uint32 sequence = 4;</code>\n *\n * <pre>\n * Sequence number. Currently unused, but intended for contracts in future.\n * </pre>\n */\n public Builder setSequence(int value) {\n bitField0_ |= 0x00000008;\n sequence_ = value;\n onChanged();\n return this;\n }\n /**\n * <code>optional uint32 sequence = 4;</code>\n *\n * <pre>\n * Sequence number. Currently unused, but intended for contracts in future.\n * </pre>\n */\n public Builder clearSequence() {\n bitField0_ = (bitField0_ & ~0x00000008);\n sequence_ = 0;\n onChanged();\n return this;\n }\n\n // @@protoc_insertion_point(builder_scope:wallet.TransactionInput)\n }\n\n static {\n defaultInstance = new TransactionInput(true);\n defaultInstance.initFields();\n }\n\n // @@protoc_insertion_point(class_scope:wallet.TransactionInput)\n }\n\n public interface TransactionOutputOrBuilder\n extends com.google.protobuf.MessageOrBuilder {\n\n // required int64 value = 1;\n /**\n * <code>required int64 value = 1;</code>\n */\n boolean hasValue();\n /**\n * <code>required int64 value = 1;</code>\n */\n long getValue();\n\n // required bytes script_bytes = 2;\n /**\n * <code>required bytes script_bytes = 2;</code>\n *\n * <pre>\n * script of transaction output\n * </pre>\n */\n boolean hasScriptBytes();\n /**\n * <code>required bytes script_bytes = 2;</code>\n *\n * <pre>\n * script of transaction output\n * </pre>\n */\n com.google.protobuf.ByteString getScriptBytes();\n\n // optional bytes spent_by_transaction_hash = 3;\n /**\n * <code>optional bytes spent_by_transaction_hash = 3;</code>\n *\n * <pre>\n * If spent, the hash of the transaction doing the spend.\n * </pre>\n */\n boolean hasSpentByTransactionHash();\n /**\n * <code>optional bytes spent_by_transaction_hash = 3;</code>\n *\n * <pre>\n * If spent, the hash of the transaction doing the spend.\n * </pre>\n */\n com.google.protobuf.ByteString getSpentByTransactionHash();\n\n // optional int32 spent_by_transaction_index = 4;\n /**\n * <code>optional int32 spent_by_transaction_index = 4;</code>\n *\n * <pre>\n * If spent, the index of the transaction input of the transaction doing the spend.\n * </pre>\n */\n boolean hasSpentByTransactionIndex();\n /**\n * <code>optional int32 spent_by_transaction_index = 4;</code>\n *\n * <pre>\n * If spent, the index of the transaction input of the transaction doing the spend.\n * </pre>\n */\n int getSpentByTransactionIndex();\n }\n /**\n * Protobuf type {@code wallet.TransactionOutput}\n */\n public static final class TransactionOutput extends\n com.google.protobuf.GeneratedMessage\n implements TransactionOutputOrBuilder {\n // Use TransactionOutput.newBuilder() to construct.\n private TransactionOutput(com.google.protobuf.GeneratedMessage.Builder<?> builder) {\n super(builder);\n this.unknownFields = builder.getUnknownFields();\n }\n private TransactionOutput(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }\n\n private static final TransactionOutput defaultInstance;\n public static TransactionOutput getDefaultInstance() {\n return defaultInstance;\n }\n\n public TransactionOutput getDefaultInstanceForType() {\n return defaultInstance;\n }\n\n private final com.google.protobuf.UnknownFieldSet unknownFields;\n @java.lang.Override\n public final com.google.protobuf.UnknownFieldSet\n getUnknownFields() {\n return this.unknownFields;\n }\n private TransactionOutput(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n initFields();\n int mutable_bitField0_ = 0;\n com.google.protobuf.UnknownFieldSet.Builder unknownFields =\n com.google.protobuf.UnknownFieldSet.newBuilder();\n try {\n boolean done = false;\n while (!done) {\n int tag = input.readTag();\n switch (tag) {\n case 0:\n done = true;\n break;\n default: {\n if (!parseUnknownField(input, unknownFields,\n extensionRegistry, tag)) {\n done = true;\n }\n break;\n }\n case 8: {\n bitField0_ |= 0x00000001;\n value_ = input.readInt64();\n break;\n }\n case 18: {\n bitField0_ |= 0x00000002;\n scriptBytes_ = input.readBytes();\n break;\n }\n case 26: {\n bitField0_ |= 0x00000004;\n spentByTransactionHash_ = input.readBytes();\n break;\n }\n case 32: {\n bitField0_ |= 0x00000008;\n spentByTransactionIndex_ = input.readInt32();\n break;\n }\n }\n }\n } catch (com.google.protobuf.InvalidProtocolBufferException e) {\n throw e.setUnfinishedMessage(this);\n } catch (java.io.IOException e) {\n throw new com.google.protobuf.InvalidProtocolBufferException(\n e.getMessage()).setUnfinishedMessage(this);\n } finally {\n this.unknownFields = unknownFields.build();\n makeExtensionsImmutable();\n }\n }\n public static final com.google.protobuf.Descriptors.Descriptor\n getDescriptor() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_TransactionOutput_descriptor;\n }\n\n protected com.google.protobuf.GeneratedMessage.FieldAccessorTable\n internalGetFieldAccessorTable() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_TransactionOutput_fieldAccessorTable\n .ensureFieldAccessorsInitialized(\n org.bitcoinj.wallet.Protos.TransactionOutput.class, org.bitcoinj.wallet.Protos.TransactionOutput.Builder.class);\n }\n\n public static com.google.protobuf.Parser<TransactionOutput> PARSER =\n new com.google.protobuf.AbstractParser<TransactionOutput>() {\n public TransactionOutput parsePartialFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return new TransactionOutput(input, extensionRegistry);\n }\n };\n\n @java.lang.Override\n public com.google.protobuf.Parser<TransactionOutput> getParserForType() {\n return PARSER;\n }\n\n private int bitField0_;\n // required int64 value = 1;\n public static final int VALUE_FIELD_NUMBER = 1;\n private long value_;\n /**\n * <code>required int64 value = 1;</code>\n */\n public boolean hasValue() {\n return ((bitField0_ & 0x00000001) == 0x00000001);\n }\n /**\n * <code>required int64 value = 1;</code>\n */\n public long getValue() {\n return value_;\n }\n\n // required bytes script_bytes = 2;\n public static final int SCRIPT_BYTES_FIELD_NUMBER = 2;\n private com.google.protobuf.ByteString scriptBytes_;\n /**\n * <code>required bytes script_bytes = 2;</code>\n *\n * <pre>\n * script of transaction output\n * </pre>\n */\n public boolean hasScriptBytes() {\n return ((bitField0_ & 0x00000002) == 0x00000002);\n }\n /**\n * <code>required bytes script_bytes = 2;</code>\n *\n * <pre>\n * script of transaction output\n * </pre>\n */\n public com.google.protobuf.ByteString getScriptBytes() {\n return scriptBytes_;\n }\n\n // optional bytes spent_by_transaction_hash = 3;\n public static final int SPENT_BY_TRANSACTION_HASH_FIELD_NUMBER = 3;\n private com.google.protobuf.ByteString spentByTransactionHash_;\n /**\n * <code>optional bytes spent_by_transaction_hash = 3;</code>\n *\n * <pre>\n * If spent, the hash of the transaction doing the spend.\n * </pre>\n */\n public boolean hasSpentByTransactionHash() {\n return ((bitField0_ & 0x00000004) == 0x00000004);\n }\n /**\n * <code>optional bytes spent_by_transaction_hash = 3;</code>\n *\n * <pre>\n * If spent, the hash of the transaction doing the spend.\n * </pre>\n */\n public com.google.protobuf.ByteString getSpentByTransactionHash() {\n return spentByTransactionHash_;\n }\n\n // optional int32 spent_by_transaction_index = 4;\n public static final int SPENT_BY_TRANSACTION_INDEX_FIELD_NUMBER = 4;\n private int spentByTransactionIndex_;\n /**\n * <code>optional int32 spent_by_transaction_index = 4;</code>\n *\n * <pre>\n * If spent, the index of the transaction input of the transaction doing the spend.\n * </pre>\n */\n public boolean hasSpentByTransactionIndex() {\n return ((bitField0_ & 0x00000008) == 0x00000008);\n }\n /**\n * <code>optional int32 spent_by_transaction_index = 4;</code>\n *\n * <pre>\n * If spent, the index of the transaction input of the transaction doing the spend.\n * </pre>\n */\n public int getSpentByTransactionIndex() {\n return spentByTransactionIndex_;\n }\n\n private void initFields() {\n value_ = 0L;\n scriptBytes_ = com.google.protobuf.ByteString.EMPTY;\n spentByTransactionHash_ = com.google.protobuf.ByteString.EMPTY;\n spentByTransactionIndex_ = 0;\n }\n private byte memoizedIsInitialized = -1;\n public final boolean isInitialized() {\n byte isInitialized = memoizedIsInitialized;\n if (isInitialized != -1) return isInitialized == 1;\n\n if (!hasValue()) {\n memoizedIsInitialized = 0;\n return false;\n }\n if (!hasScriptBytes()) {\n memoizedIsInitialized = 0;\n return false;\n }\n memoizedIsInitialized = 1;\n return true;\n }\n\n public void writeTo(com.google.protobuf.CodedOutputStream output)\n throws java.io.IOException {\n getSerializedSize();\n if (((bitField0_ & 0x00000001) == 0x00000001)) {\n output.writeInt64(1, value_);\n }\n if (((bitField0_ & 0x00000002) == 0x00000002)) {\n output.writeBytes(2, scriptBytes_);\n }\n if (((bitField0_ & 0x00000004) == 0x00000004)) {\n output.writeBytes(3, spentByTransactionHash_);\n }\n if (((bitField0_ & 0x00000008) == 0x00000008)) {\n output.writeInt32(4, spentByTransactionIndex_);\n }\n getUnknownFields().writeTo(output);\n }\n\n private int memoizedSerializedSize = -1;\n public int getSerializedSize() {\n int size = memoizedSerializedSize;\n if (size != -1) return size;\n\n size = 0;\n if (((bitField0_ & 0x00000001) == 0x00000001)) {\n size += com.google.protobuf.CodedOutputStream\n .computeInt64Size(1, value_);\n }\n if (((bitField0_ & 0x00000002) == 0x00000002)) {\n size += com.google.protobuf.CodedOutputStream\n .computeBytesSize(2, scriptBytes_);\n }\n if (((bitField0_ & 0x00000004) == 0x00000004)) {\n size += com.google.protobuf.CodedOutputStream\n .computeBytesSize(3, spentByTransactionHash_);\n }\n if (((bitField0_ & 0x00000008) == 0x00000008)) {\n size += com.google.protobuf.CodedOutputStream\n .computeInt32Size(4, spentByTransactionIndex_);\n }\n size += getUnknownFields().getSerializedSize();\n memoizedSerializedSize = size;\n return size;\n }\n\n private static final long serialVersionUID = 0L;\n @java.lang.Override\n protected java.lang.Object writeReplace()\n throws java.io.ObjectStreamException {\n return super.writeReplace();\n }\n\n public static org.bitcoinj.wallet.Protos.TransactionOutput parseFrom(\n com.google.protobuf.ByteString data)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n public static org.bitcoinj.wallet.Protos.TransactionOutput parseFrom(\n com.google.protobuf.ByteString data,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n public static org.bitcoinj.wallet.Protos.TransactionOutput parseFrom(byte[] data)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n public static org.bitcoinj.wallet.Protos.TransactionOutput parseFrom(\n byte[] data,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n public static org.bitcoinj.wallet.Protos.TransactionOutput parseFrom(java.io.InputStream input)\n throws java.io.IOException {\n return PARSER.parseFrom(input);\n }\n public static org.bitcoinj.wallet.Protos.TransactionOutput parseFrom(\n java.io.InputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return PARSER.parseFrom(input, extensionRegistry);\n }\n public static org.bitcoinj.wallet.Protos.TransactionOutput parseDelimitedFrom(java.io.InputStream input)\n throws java.io.IOException {\n return PARSER.parseDelimitedFrom(input);\n }\n public static org.bitcoinj.wallet.Protos.TransactionOutput parseDelimitedFrom(\n java.io.InputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return PARSER.parseDelimitedFrom(input, extensionRegistry);\n }\n public static org.bitcoinj.wallet.Protos.TransactionOutput parseFrom(\n com.google.protobuf.CodedInputStream input)\n throws java.io.IOException {\n return PARSER.parseFrom(input);\n }\n public static org.bitcoinj.wallet.Protos.TransactionOutput parseFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return PARSER.parseFrom(input, extensionRegistry);\n }\n\n public static Builder newBuilder() { return Builder.create(); }\n public Builder newBuilderForType() { return newBuilder(); }\n public static Builder newBuilder(org.bitcoinj.wallet.Protos.TransactionOutput prototype) {\n return newBuilder().mergeFrom(prototype);\n }\n public Builder toBuilder() { return newBuilder(this); }\n\n @java.lang.Override\n protected Builder newBuilderForType(\n com.google.protobuf.GeneratedMessage.BuilderParent parent) {\n Builder builder = new Builder(parent);\n return builder;\n }\n /**\n * Protobuf type {@code wallet.TransactionOutput}\n */\n public static final class Builder extends\n com.google.protobuf.GeneratedMessage.Builder<Builder>\n implements org.bitcoinj.wallet.Protos.TransactionOutputOrBuilder {\n public static final com.google.protobuf.Descriptors.Descriptor\n getDescriptor() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_TransactionOutput_descriptor;\n }\n\n protected com.google.protobuf.GeneratedMessage.FieldAccessorTable\n internalGetFieldAccessorTable() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_TransactionOutput_fieldAccessorTable\n .ensureFieldAccessorsInitialized(\n org.bitcoinj.wallet.Protos.TransactionOutput.class, org.bitcoinj.wallet.Protos.TransactionOutput.Builder.class);\n }\n\n // Construct using org.bitcoinj.wallet.Protos.TransactionOutput.newBuilder()\n private Builder() {\n maybeForceBuilderInitialization();\n }\n\n private Builder(\n com.google.protobuf.GeneratedMessage.BuilderParent parent) {\n super(parent);\n maybeForceBuilderInitialization();\n }\n private void maybeForceBuilderInitialization() {\n if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {\n }\n }\n private static Builder create() {\n return new Builder();\n }\n\n public Builder clear() {\n super.clear();\n value_ = 0L;\n bitField0_ = (bitField0_ & ~0x00000001);\n scriptBytes_ = com.google.protobuf.ByteString.EMPTY;\n bitField0_ = (bitField0_ & ~0x00000002);\n spentByTransactionHash_ = com.google.protobuf.ByteString.EMPTY;\n bitField0_ = (bitField0_ & ~0x00000004);\n spentByTransactionIndex_ = 0;\n bitField0_ = (bitField0_ & ~0x00000008);\n return this;\n }\n\n public Builder clone() {\n return create().mergeFrom(buildPartial());\n }\n\n public com.google.protobuf.Descriptors.Descriptor\n getDescriptorForType() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_TransactionOutput_descriptor;\n }\n\n public org.bitcoinj.wallet.Protos.TransactionOutput getDefaultInstanceForType() {\n return org.bitcoinj.wallet.Protos.TransactionOutput.getDefaultInstance();\n }\n\n public org.bitcoinj.wallet.Protos.TransactionOutput build() {\n org.bitcoinj.wallet.Protos.TransactionOutput result = buildPartial();\n if (!result.isInitialized()) {\n throw newUninitializedMessageException(result);\n }\n return result;\n }\n\n public org.bitcoinj.wallet.Protos.TransactionOutput buildPartial() {\n org.bitcoinj.wallet.Protos.TransactionOutput result = new org.bitcoinj.wallet.Protos.TransactionOutput(this);\n int from_bitField0_ = bitField0_;\n int to_bitField0_ = 0;\n if (((from_bitField0_ & 0x00000001) == 0x00000001)) {\n to_bitField0_ |= 0x00000001;\n }\n result.value_ = value_;\n if (((from_bitField0_ & 0x00000002) == 0x00000002)) {\n to_bitField0_ |= 0x00000002;\n }\n result.scriptBytes_ = scriptBytes_;\n if (((from_bitField0_ & 0x00000004) == 0x00000004)) {\n to_bitField0_ |= 0x00000004;\n }\n result.spentByTransactionHash_ = spentByTransactionHash_;\n if (((from_bitField0_ & 0x00000008) == 0x00000008)) {\n to_bitField0_ |= 0x00000008;\n }\n result.spentByTransactionIndex_ = spentByTransactionIndex_;\n result.bitField0_ = to_bitField0_;\n onBuilt();\n return result;\n }\n\n public Builder mergeFrom(com.google.protobuf.Message other) {\n if (other instanceof org.bitcoinj.wallet.Protos.TransactionOutput) {\n return mergeFrom((org.bitcoinj.wallet.Protos.TransactionOutput)other);\n } else {\n super.mergeFrom(other);\n return this;\n }\n }\n\n public Builder mergeFrom(org.bitcoinj.wallet.Protos.TransactionOutput other) {\n if (other == org.bitcoinj.wallet.Protos.TransactionOutput.getDefaultInstance()) return this;\n if (other.hasValue()) {\n setValue(other.getValue());\n }\n if (other.hasScriptBytes()) {\n setScriptBytes(other.getScriptBytes());\n }\n if (other.hasSpentByTransactionHash()) {\n setSpentByTransactionHash(other.getSpentByTransactionHash());\n }\n if (other.hasSpentByTransactionIndex()) {\n setSpentByTransactionIndex(other.getSpentByTransactionIndex());\n }\n this.mergeUnknownFields(other.getUnknownFields());\n return this;\n }\n\n public final boolean isInitialized() {\n if (!hasValue()) {\n \n return false;\n }\n if (!hasScriptBytes()) {\n \n return false;\n }\n return true;\n }\n\n public Builder mergeFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n org.bitcoinj.wallet.Protos.TransactionOutput parsedMessage = null;\n try {\n parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);\n } catch (com.google.protobuf.InvalidProtocolBufferException e) {\n parsedMessage = (org.bitcoinj.wallet.Protos.TransactionOutput) e.getUnfinishedMessage();\n throw e;\n } finally {\n if (parsedMessage != null) {\n mergeFrom(parsedMessage);\n }\n }\n return this;\n }\n private int bitField0_;\n\n // required int64 value = 1;\n private long value_ ;\n /**\n * <code>required int64 value = 1;</code>\n */\n public boolean hasValue() {\n return ((bitField0_ & 0x00000001) == 0x00000001);\n }\n /**\n * <code>required int64 value = 1;</code>\n */\n public long getValue() {\n return value_;\n }\n /**\n * <code>required int64 value = 1;</code>\n */\n public Builder setValue(long value) {\n bitField0_ |= 0x00000001;\n value_ = value;\n onChanged();\n return this;\n }\n /**\n * <code>required int64 value = 1;</code>\n */\n public Builder clearValue() {\n bitField0_ = (bitField0_ & ~0x00000001);\n value_ = 0L;\n onChanged();\n return this;\n }\n\n // required bytes script_bytes = 2;\n private com.google.protobuf.ByteString scriptBytes_ = com.google.protobuf.ByteString.EMPTY;\n /**\n * <code>required bytes script_bytes = 2;</code>\n *\n * <pre>\n * script of transaction output\n * </pre>\n */\n public boolean hasScriptBytes() {\n return ((bitField0_ & 0x00000002) == 0x00000002);\n }\n /**\n * <code>required bytes script_bytes = 2;</code>\n *\n * <pre>\n * script of transaction output\n * </pre>\n */\n public com.google.protobuf.ByteString getScriptBytes() {\n return scriptBytes_;\n }\n /**\n * <code>required bytes script_bytes = 2;</code>\n *\n * <pre>\n * script of transaction output\n * </pre>\n */\n public Builder setScriptBytes(com.google.protobuf.ByteString value) {\n if (value == null) {\n throw new NullPointerException();\n }\n bitField0_ |= 0x00000002;\n scriptBytes_ = value;\n onChanged();\n return this;\n }\n /**\n * <code>required bytes script_bytes = 2;</code>\n *\n * <pre>\n * script of transaction output\n * </pre>\n */\n public Builder clearScriptBytes() {\n bitField0_ = (bitField0_ & ~0x00000002);\n scriptBytes_ = getDefaultInstance().getScriptBytes();\n onChanged();\n return this;\n }\n\n // optional bytes spent_by_transaction_hash = 3;\n private com.google.protobuf.ByteString spentByTransactionHash_ = com.google.protobuf.ByteString.EMPTY;\n /**\n * <code>optional bytes spent_by_transaction_hash = 3;</code>\n *\n * <pre>\n * If spent, the hash of the transaction doing the spend.\n * </pre>\n */\n public boolean hasSpentByTransactionHash() {\n return ((bitField0_ & 0x00000004) == 0x00000004);\n }\n /**\n * <code>optional bytes spent_by_transaction_hash = 3;</code>\n *\n * <pre>\n * If spent, the hash of the transaction doing the spend.\n * </pre>\n */\n public com.google.protobuf.ByteString getSpentByTransactionHash() {\n return spentByTransactionHash_;\n }\n /**\n * <code>optional bytes spent_by_transaction_hash = 3;</code>\n *\n * <pre>\n * If spent, the hash of the transaction doing the spend.\n * </pre>\n */\n public Builder setSpentByTransactionHash(com.google.protobuf.ByteString value) {\n if (value == null) {\n throw new NullPointerException();\n }\n bitField0_ |= 0x00000004;\n spentByTransactionHash_ = value;\n onChanged();\n return this;\n }\n /**\n * <code>optional bytes spent_by_transaction_hash = 3;</code>\n *\n * <pre>\n * If spent, the hash of the transaction doing the spend.\n * </pre>\n */\n public Builder clearSpentByTransactionHash() {\n bitField0_ = (bitField0_ & ~0x00000004);\n spentByTransactionHash_ = getDefaultInstance().getSpentByTransactionHash();\n onChanged();\n return this;\n }\n\n // optional int32 spent_by_transaction_index = 4;\n private int spentByTransactionIndex_ ;\n /**\n * <code>optional int32 spent_by_transaction_index = 4;</code>\n *\n * <pre>\n * If spent, the index of the transaction input of the transaction doing the spend.\n * </pre>\n */\n public boolean hasSpentByTransactionIndex() {\n return ((bitField0_ & 0x00000008) == 0x00000008);\n }\n /**\n * <code>optional int32 spent_by_transaction_index = 4;</code>\n *\n * <pre>\n * If spent, the index of the transaction input of the transaction doing the spend.\n * </pre>\n */\n public int getSpentByTransactionIndex() {\n return spentByTransactionIndex_;\n }\n /**\n * <code>optional int32 spent_by_transaction_index = 4;</code>\n *\n * <pre>\n * If spent, the index of the transaction input of the transaction doing the spend.\n * </pre>\n */\n public Builder setSpentByTransactionIndex(int value) {\n bitField0_ |= 0x00000008;\n spentByTransactionIndex_ = value;\n onChanged();\n return this;\n }\n /**\n * <code>optional int32 spent_by_transaction_index = 4;</code>\n *\n * <pre>\n * If spent, the index of the transaction input of the transaction doing the spend.\n * </pre>\n */\n public Builder clearSpentByTransactionIndex() {\n bitField0_ = (bitField0_ & ~0x00000008);\n spentByTransactionIndex_ = 0;\n onChanged();\n return this;\n }\n\n // @@protoc_insertion_point(builder_scope:wallet.TransactionOutput)\n }\n\n static {\n defaultInstance = new TransactionOutput(true);\n defaultInstance.initFields();\n }\n\n // @@protoc_insertion_point(class_scope:wallet.TransactionOutput)\n }\n\n public interface TransactionConfidenceOrBuilder\n extends com.google.protobuf.MessageOrBuilder {\n\n // optional .wallet.TransactionConfidence.Type type = 1;\n /**\n * <code>optional .wallet.TransactionConfidence.Type type = 1;</code>\n *\n * <pre>\n * This is optional in case we add confidence types to prevent parse errors - backwards compatible.\n * </pre>\n */\n boolean hasType();\n /**\n * <code>optional .wallet.TransactionConfidence.Type type = 1;</code>\n *\n * <pre>\n * This is optional in case we add confidence types to prevent parse errors - backwards compatible.\n * </pre>\n */\n org.bitcoinj.wallet.Protos.TransactionConfidence.Type getType();\n\n // optional int32 appeared_at_height = 2;\n /**\n * <code>optional int32 appeared_at_height = 2;</code>\n *\n * <pre>\n * If type == BUILDING then this is the chain height at which the transaction was included.\n * </pre>\n */\n boolean hasAppearedAtHeight();\n /**\n * <code>optional int32 appeared_at_height = 2;</code>\n *\n * <pre>\n * If type == BUILDING then this is the chain height at which the transaction was included.\n * </pre>\n */\n int getAppearedAtHeight();\n\n // optional bytes overriding_transaction = 3;\n /**\n * <code>optional bytes overriding_transaction = 3;</code>\n *\n * <pre>\n * If set, hash of the transaction that double spent this one into oblivion. A transaction can be double spent by\n * multiple transactions in the case of several inputs being re-spent by several transactions but we don't\n * bother to track them all, just the first. This only makes sense if type = DEAD.\n * </pre>\n */\n boolean hasOverridingTransaction();\n /**\n * <code>optional bytes overriding_transaction = 3;</code>\n *\n * <pre>\n * If set, hash of the transaction that double spent this one into oblivion. A transaction can be double spent by\n * multiple transactions in the case of several inputs being re-spent by several transactions but we don't\n * bother to track them all, just the first. This only makes sense if type = DEAD.\n * </pre>\n */\n com.google.protobuf.ByteString getOverridingTransaction();\n\n // optional int32 depth = 4;\n /**\n * <code>optional int32 depth = 4;</code>\n *\n * <pre>\n * If type == BUILDING then this is the depth of the transaction in the blockchain.\n * Zero confirmations: depth = 0, one confirmation: depth = 1 etc.\n * </pre>\n */\n boolean hasDepth();\n /**\n * <code>optional int32 depth = 4;</code>\n *\n * <pre>\n * If type == BUILDING then this is the depth of the transaction in the blockchain.\n * Zero confirmations: depth = 0, one confirmation: depth = 1 etc.\n * </pre>\n */\n int getDepth();\n\n // optional int64 work_done = 5;\n /**\n * <code>optional int64 work_done = 5;</code>\n *\n * <pre>\n * If type == BUILDING then this is the cumulative workDone for the block the transaction appears in, together with\n * all blocks that bury it.\n * </pre>\n */\n boolean hasWorkDone();\n /**\n * <code>optional int64 work_done = 5;</code>\n *\n * <pre>\n * If type == BUILDING then this is the cumulative workDone for the block the transaction appears in, together with\n * all blocks that bury it.\n * </pre>\n */\n long getWorkDone();\n\n // repeated .wallet.PeerAddress broadcast_by = 6;\n /**\n * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code>\n */\n java.util.List<org.bitcoinj.wallet.Protos.PeerAddress> \n getBroadcastByList();\n /**\n * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code>\n */\n org.bitcoinj.wallet.Protos.PeerAddress getBroadcastBy(int index);\n /**\n * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code>\n */\n int getBroadcastByCount();\n /**\n * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code>\n */\n java.util.List<? extends org.bitcoinj.wallet.Protos.PeerAddressOrBuilder> \n getBroadcastByOrBuilderList();\n /**\n * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code>\n */\n org.bitcoinj.wallet.Protos.PeerAddressOrBuilder getBroadcastByOrBuilder(\n int index);\n\n // optional .wallet.TransactionConfidence.Source source = 7;\n /**\n * <code>optional .wallet.TransactionConfidence.Source source = 7;</code>\n */\n boolean hasSource();\n /**\n * <code>optional .wallet.TransactionConfidence.Source source = 7;</code>\n */\n org.bitcoinj.wallet.Protos.TransactionConfidence.Source getSource();\n }\n /**\n * Protobuf type {@code wallet.TransactionConfidence}\n *\n * <pre>\n **\n * A description of the confidence we have that a transaction cannot be reversed in the future.\n *\n * Parsing should be lenient, since this could change for different applications yet we should\n * maintain backward compatibility.\n * </pre>\n */\n public static final class TransactionConfidence extends\n com.google.protobuf.GeneratedMessage\n implements TransactionConfidenceOrBuilder {\n // Use TransactionConfidence.newBuilder() to construct.\n private TransactionConfidence(com.google.protobuf.GeneratedMessage.Builder<?> builder) {\n super(builder);\n this.unknownFields = builder.getUnknownFields();\n }\n private TransactionConfidence(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }\n\n private static final TransactionConfidence defaultInstance;\n public static TransactionConfidence getDefaultInstance() {\n return defaultInstance;\n }\n\n public TransactionConfidence getDefaultInstanceForType() {\n return defaultInstance;\n }\n\n private final com.google.protobuf.UnknownFieldSet unknownFields;\n @java.lang.Override\n public final com.google.protobuf.UnknownFieldSet\n getUnknownFields() {\n return this.unknownFields;\n }\n private TransactionConfidence(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n initFields();\n int mutable_bitField0_ = 0;\n com.google.protobuf.UnknownFieldSet.Builder unknownFields =\n com.google.protobuf.UnknownFieldSet.newBuilder();\n try {\n boolean done = false;\n while (!done) {\n int tag = input.readTag();\n switch (tag) {\n case 0:\n done = true;\n break;\n default: {\n if (!parseUnknownField(input, unknownFields,\n extensionRegistry, tag)) {\n done = true;\n }\n break;\n }\n case 8: {\n int rawValue = input.readEnum();\n org.bitcoinj.wallet.Protos.TransactionConfidence.Type value = org.bitcoinj.wallet.Protos.TransactionConfidence.Type.valueOf(rawValue);\n if (value == null) {\n unknownFields.mergeVarintField(1, rawValue);\n } else {\n bitField0_ |= 0x00000001;\n type_ = value;\n }\n break;\n }\n case 16: {\n bitField0_ |= 0x00000002;\n appearedAtHeight_ = input.readInt32();\n break;\n }\n case 26: {\n bitField0_ |= 0x00000004;\n overridingTransaction_ = input.readBytes();\n break;\n }\n case 32: {\n bitField0_ |= 0x00000008;\n depth_ = input.readInt32();\n break;\n }\n case 40: {\n bitField0_ |= 0x00000010;\n workDone_ = input.readInt64();\n break;\n }\n case 50: {\n if (!((mutable_bitField0_ & 0x00000020) == 0x00000020)) {\n broadcastBy_ = new java.util.ArrayList<org.bitcoinj.wallet.Protos.PeerAddress>();\n mutable_bitField0_ |= 0x00000020;\n }\n broadcastBy_.add(input.readMessage(org.bitcoinj.wallet.Protos.PeerAddress.PARSER, extensionRegistry));\n break;\n }\n case 56: {\n int rawValue = input.readEnum();\n org.bitcoinj.wallet.Protos.TransactionConfidence.Source value = org.bitcoinj.wallet.Protos.TransactionConfidence.Source.valueOf(rawValue);\n if (value == null) {\n unknownFields.mergeVarintField(7, rawValue);\n } else {\n bitField0_ |= 0x00000020;\n source_ = value;\n }\n break;\n }\n }\n }\n } catch (com.google.protobuf.InvalidProtocolBufferException e) {\n throw e.setUnfinishedMessage(this);\n } catch (java.io.IOException e) {\n throw new com.google.protobuf.InvalidProtocolBufferException(\n e.getMessage()).setUnfinishedMessage(this);\n } finally {\n if (((mutable_bitField0_ & 0x00000020) == 0x00000020)) {\n broadcastBy_ = java.util.Collections.unmodifiableList(broadcastBy_);\n }\n this.unknownFields = unknownFields.build();\n makeExtensionsImmutable();\n }\n }\n public static final com.google.protobuf.Descriptors.Descriptor\n getDescriptor() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_TransactionConfidence_descriptor;\n }\n\n protected com.google.protobuf.GeneratedMessage.FieldAccessorTable\n internalGetFieldAccessorTable() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_TransactionConfidence_fieldAccessorTable\n .ensureFieldAccessorsInitialized(\n org.bitcoinj.wallet.Protos.TransactionConfidence.class, org.bitcoinj.wallet.Protos.TransactionConfidence.Builder.class);\n }\n\n public static com.google.protobuf.Parser<TransactionConfidence> PARSER =\n new com.google.protobuf.AbstractParser<TransactionConfidence>() {\n public TransactionConfidence parsePartialFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return new TransactionConfidence(input, extensionRegistry);\n }\n };\n\n @java.lang.Override\n public com.google.protobuf.Parser<TransactionConfidence> getParserForType() {\n return PARSER;\n }\n\n /**\n * Protobuf enum {@code wallet.TransactionConfidence.Type}\n */\n public enum Type\n implements com.google.protobuf.ProtocolMessageEnum {\n /**\n * <code>UNKNOWN = 0;</code>\n */\n UNKNOWN(0, 0),\n /**\n * <code>BUILDING = 1;</code>\n *\n * <pre>\n * In best chain. If and only if appeared_at_height is present.\n * </pre>\n */\n BUILDING(1, 1),\n /**\n * <code>PENDING = 2;</code>\n *\n * <pre>\n * Unconfirmed and sitting in the networks memory pools, waiting to be included in the chain.\n * </pre>\n */\n PENDING(2, 2),\n /**\n * <code>NOT_IN_BEST_CHAIN = 3;</code>\n *\n * <pre>\n * Deprecated: equivalent to PENDING.\n * </pre>\n */\n NOT_IN_BEST_CHAIN(3, 3),\n /**\n * <code>DEAD = 4;</code>\n *\n * <pre>\n * Either if overriding_transaction is present or transaction is dead coinbase\n * </pre>\n */\n DEAD(4, 4),\n ;\n\n /**\n * <code>UNKNOWN = 0;</code>\n */\n public static final int UNKNOWN_VALUE = 0;\n /**\n * <code>BUILDING = 1;</code>\n *\n * <pre>\n * In best chain. If and only if appeared_at_height is present.\n * </pre>\n */\n public static final int BUILDING_VALUE = 1;\n /**\n * <code>PENDING = 2;</code>\n *\n * <pre>\n * Unconfirmed and sitting in the networks memory pools, waiting to be included in the chain.\n * </pre>\n */\n public static final int PENDING_VALUE = 2;\n /**\n * <code>NOT_IN_BEST_CHAIN = 3;</code>\n *\n * <pre>\n * Deprecated: equivalent to PENDING.\n * </pre>\n */\n public static final int NOT_IN_BEST_CHAIN_VALUE = 3;\n /**\n * <code>DEAD = 4;</code>\n *\n * <pre>\n * Either if overriding_transaction is present or transaction is dead coinbase\n * </pre>\n */\n public static final int DEAD_VALUE = 4;\n\n\n public final int getNumber() { return value; }\n\n public static Type valueOf(int value) {\n switch (value) {\n case 0: return UNKNOWN;\n case 1: return BUILDING;\n case 2: return PENDING;\n case 3: return NOT_IN_BEST_CHAIN;\n case 4: return DEAD;\n default: return null;\n }\n }\n\n public static com.google.protobuf.Internal.EnumLiteMap<Type>\n internalGetValueMap() {\n return internalValueMap;\n }\n private static com.google.protobuf.Internal.EnumLiteMap<Type>\n internalValueMap =\n new com.google.protobuf.Internal.EnumLiteMap<Type>() {\n public Type findValueByNumber(int number) {\n return Type.valueOf(number);\n }\n };\n\n public final com.google.protobuf.Descriptors.EnumValueDescriptor\n getValueDescriptor() {\n return getDescriptor().getValues().get(index);\n }\n public final com.google.protobuf.Descriptors.EnumDescriptor\n getDescriptorForType() {\n return getDescriptor();\n }\n public static final com.google.protobuf.Descriptors.EnumDescriptor\n getDescriptor() {\n return org.bitcoinj.wallet.Protos.TransactionConfidence.getDescriptor().getEnumTypes().get(0);\n }\n\n private static final Type[] VALUES = values();\n\n public static Type valueOf(\n com.google.protobuf.Descriptors.EnumValueDescriptor desc) {\n if (desc.getType() != getDescriptor()) {\n throw new java.lang.IllegalArgumentException(\n \"EnumValueDescriptor is not for this type.\");\n }\n return VALUES[desc.getIndex()];\n }\n\n private final int index;\n private final int value;\n\n private Type(int index, int value) {\n this.index = index;\n this.value = value;\n }\n\n // @@protoc_insertion_point(enum_scope:wallet.TransactionConfidence.Type)\n }\n\n /**\n * Protobuf enum {@code wallet.TransactionConfidence.Source}\n *\n * <pre>\n * Where did we get this transaction from? Knowing the source may help us to risk analyze pending transactions.\n * </pre>\n */\n public enum Source\n implements com.google.protobuf.ProtocolMessageEnum {\n /**\n * <code>SOURCE_UNKNOWN = 0;</code>\n *\n * <pre>\n * We don't know where it came from, or this is a wallet from the future.\n * </pre>\n */\n SOURCE_UNKNOWN(0, 0),\n /**\n * <code>SOURCE_NETWORK = 1;</code>\n *\n * <pre>\n * We received it from a network broadcast. This is the normal way to get payments.\n * </pre>\n */\n SOURCE_NETWORK(1, 1),\n /**\n * <code>SOURCE_SELF = 2;</code>\n *\n * <pre>\n * We made it ourselves, so we know it should be valid.\n * </pre>\n */\n SOURCE_SELF(2, 2),\n ;\n\n /**\n * <code>SOURCE_UNKNOWN = 0;</code>\n *\n * <pre>\n * We don't know where it came from, or this is a wallet from the future.\n * </pre>\n */\n public static final int SOURCE_UNKNOWN_VALUE = 0;\n /**\n * <code>SOURCE_NETWORK = 1;</code>\n *\n * <pre>\n * We received it from a network broadcast. This is the normal way to get payments.\n * </pre>\n */\n public static final int SOURCE_NETWORK_VALUE = 1;\n /**\n * <code>SOURCE_SELF = 2;</code>\n *\n * <pre>\n * We made it ourselves, so we know it should be valid.\n * </pre>\n */\n public static final int SOURCE_SELF_VALUE = 2;\n\n\n public final int getNumber() { return value; }\n\n public static Source valueOf(int value) {\n switch (value) {\n case 0: return SOURCE_UNKNOWN;\n case 1: return SOURCE_NETWORK;\n case 2: return SOURCE_SELF;\n default: return null;\n }\n }\n\n public static com.google.protobuf.Internal.EnumLiteMap<Source>\n internalGetValueMap() {\n return internalValueMap;\n }\n private static com.google.protobuf.Internal.EnumLiteMap<Source>\n internalValueMap =\n new com.google.protobuf.Internal.EnumLiteMap<Source>() {\n public Source findValueByNumber(int number) {\n return Source.valueOf(number);\n }\n };\n\n public final com.google.protobuf.Descriptors.EnumValueDescriptor\n getValueDescriptor() {\n return getDescriptor().getValues().get(index);\n }\n public final com.google.protobuf.Descriptors.EnumDescriptor\n getDescriptorForType() {\n return getDescriptor();\n }\n public static final com.google.protobuf.Descriptors.EnumDescriptor\n getDescriptor() {\n return org.bitcoinj.wallet.Protos.TransactionConfidence.getDescriptor().getEnumTypes().get(1);\n }\n\n private static final Source[] VALUES = values();\n\n public static Source valueOf(\n com.google.protobuf.Descriptors.EnumValueDescriptor desc) {\n if (desc.getType() != getDescriptor()) {\n throw new java.lang.IllegalArgumentException(\n \"EnumValueDescriptor is not for this type.\");\n }\n return VALUES[desc.getIndex()];\n }\n\n private final int index;\n private final int value;\n\n private Source(int index, int value) {\n this.index = index;\n this.value = value;\n }\n\n // @@protoc_insertion_point(enum_scope:wallet.TransactionConfidence.Source)\n }\n\n private int bitField0_;\n // optional .wallet.TransactionConfidence.Type type = 1;\n public static final int TYPE_FIELD_NUMBER = 1;\n private org.bitcoinj.wallet.Protos.TransactionConfidence.Type type_;\n /**\n * <code>optional .wallet.TransactionConfidence.Type type = 1;</code>\n *\n * <pre>\n * This is optional in case we add confidence types to prevent parse errors - backwards compatible.\n * </pre>\n */\n public boolean hasType() {\n return ((bitField0_ & 0x00000001) == 0x00000001);\n }\n /**\n * <code>optional .wallet.TransactionConfidence.Type type = 1;</code>\n *\n * <pre>\n * This is optional in case we add confidence types to prevent parse errors - backwards compatible.\n * </pre>\n */\n public org.bitcoinj.wallet.Protos.TransactionConfidence.Type getType() {\n return type_;\n }\n\n // optional int32 appeared_at_height = 2;\n public static final int APPEARED_AT_HEIGHT_FIELD_NUMBER = 2;\n private int appearedAtHeight_;\n /**\n * <code>optional int32 appeared_at_height = 2;</code>\n *\n * <pre>\n * If type == BUILDING then this is the chain height at which the transaction was included.\n * </pre>\n */\n public boolean hasAppearedAtHeight() {\n return ((bitField0_ & 0x00000002) == 0x00000002);\n }\n /**\n * <code>optional int32 appeared_at_height = 2;</code>\n *\n * <pre>\n * If type == BUILDING then this is the chain height at which the transaction was included.\n * </pre>\n */\n public int getAppearedAtHeight() {\n return appearedAtHeight_;\n }\n\n // optional bytes overriding_transaction = 3;\n public static final int OVERRIDING_TRANSACTION_FIELD_NUMBER = 3;\n private com.google.protobuf.ByteString overridingTransaction_;\n /**\n * <code>optional bytes overriding_transaction = 3;</code>\n *\n * <pre>\n * If set, hash of the transaction that double spent this one into oblivion. A transaction can be double spent by\n * multiple transactions in the case of several inputs being re-spent by several transactions but we don't\n * bother to track them all, just the first. This only makes sense if type = DEAD.\n * </pre>\n */\n public boolean hasOverridingTransaction() {\n return ((bitField0_ & 0x00000004) == 0x00000004);\n }\n /**\n * <code>optional bytes overriding_transaction = 3;</code>\n *\n * <pre>\n * If set, hash of the transaction that double spent this one into oblivion. A transaction can be double spent by\n * multiple transactions in the case of several inputs being re-spent by several transactions but we don't\n * bother to track them all, just the first. This only makes sense if type = DEAD.\n * </pre>\n */\n public com.google.protobuf.ByteString getOverridingTransaction() {\n return overridingTransaction_;\n }\n\n // optional int32 depth = 4;\n public static final int DEPTH_FIELD_NUMBER = 4;\n private int depth_;\n /**\n * <code>optional int32 depth = 4;</code>\n *\n * <pre>\n * If type == BUILDING then this is the depth of the transaction in the blockchain.\n * Zero confirmations: depth = 0, one confirmation: depth = 1 etc.\n * </pre>\n */\n public boolean hasDepth() {\n return ((bitField0_ & 0x00000008) == 0x00000008);\n }\n /**\n * <code>optional int32 depth = 4;</code>\n *\n * <pre>\n * If type == BUILDING then this is the depth of the transaction in the blockchain.\n * Zero confirmations: depth = 0, one confirmation: depth = 1 etc.\n * </pre>\n */\n public int getDepth() {\n return depth_;\n }\n\n // optional int64 work_done = 5;\n public static final int WORK_DONE_FIELD_NUMBER = 5;\n private long workDone_;\n /**\n * <code>optional int64 work_done = 5;</code>\n *\n * <pre>\n * If type == BUILDING then this is the cumulative workDone for the block the transaction appears in, together with\n * all blocks that bury it.\n * </pre>\n */\n public boolean hasWorkDone() {\n return ((bitField0_ & 0x00000010) == 0x00000010);\n }\n /**\n * <code>optional int64 work_done = 5;</code>\n *\n * <pre>\n * If type == BUILDING then this is the cumulative workDone for the block the transaction appears in, together with\n * all blocks that bury it.\n * </pre>\n */\n public long getWorkDone() {\n return workDone_;\n }\n\n // repeated .wallet.PeerAddress broadcast_by = 6;\n public static final int BROADCAST_BY_FIELD_NUMBER = 6;\n private java.util.List<org.bitcoinj.wallet.Protos.PeerAddress> broadcastBy_;\n /**\n * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code>\n */\n public java.util.List<org.bitcoinj.wallet.Protos.PeerAddress> getBroadcastByList() {\n return broadcastBy_;\n }\n /**\n * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code>\n */\n public java.util.List<? extends org.bitcoinj.wallet.Protos.PeerAddressOrBuilder> \n getBroadcastByOrBuilderList() {\n return broadcastBy_;\n }\n /**\n * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code>\n */\n public int getBroadcastByCount() {\n return broadcastBy_.size();\n }\n /**\n * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code>\n */\n public org.bitcoinj.wallet.Protos.PeerAddress getBroadcastBy(int index) {\n return broadcastBy_.get(index);\n }\n /**\n * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code>\n */\n public org.bitcoinj.wallet.Protos.PeerAddressOrBuilder getBroadcastByOrBuilder(\n int index) {\n return broadcastBy_.get(index);\n }\n\n // optional .wallet.TransactionConfidence.Source source = 7;\n public static final int SOURCE_FIELD_NUMBER = 7;\n private org.bitcoinj.wallet.Protos.TransactionConfidence.Source source_;\n /**\n * <code>optional .wallet.TransactionConfidence.Source source = 7;</code>\n */\n public boolean hasSource() {\n return ((bitField0_ & 0x00000020) == 0x00000020);\n }\n /**\n * <code>optional .wallet.TransactionConfidence.Source source = 7;</code>\n */\n public org.bitcoinj.wallet.Protos.TransactionConfidence.Source getSource() {\n return source_;\n }\n\n private void initFields() {\n type_ = org.bitcoinj.wallet.Protos.TransactionConfidence.Type.UNKNOWN;\n appearedAtHeight_ = 0;\n overridingTransaction_ = com.google.protobuf.ByteString.EMPTY;\n depth_ = 0;\n workDone_ = 0L;\n broadcastBy_ = java.util.Collections.emptyList();\n source_ = org.bitcoinj.wallet.Protos.TransactionConfidence.Source.SOURCE_UNKNOWN;\n }\n private byte memoizedIsInitialized = -1;\n public final boolean isInitialized() {\n byte isInitialized = memoizedIsInitialized;\n if (isInitialized != -1) return isInitialized == 1;\n\n for (int i = 0; i < getBroadcastByCount(); i++) {\n if (!getBroadcastBy(i).isInitialized()) {\n memoizedIsInitialized = 0;\n return false;\n }\n }\n memoizedIsInitialized = 1;\n return true;\n }\n\n public void writeTo(com.google.protobuf.CodedOutputStream output)\n throws java.io.IOException {\n getSerializedSize();\n if (((bitField0_ & 0x00000001) == 0x00000001)) {\n output.writeEnum(1, type_.getNumber());\n }\n if (((bitField0_ & 0x00000002) == 0x00000002)) {\n output.writeInt32(2, appearedAtHeight_);\n }\n if (((bitField0_ & 0x00000004) == 0x00000004)) {\n output.writeBytes(3, overridingTransaction_);\n }\n if (((bitField0_ & 0x00000008) == 0x00000008)) {\n output.writeInt32(4, depth_);\n }\n if (((bitField0_ & 0x00000010) == 0x00000010)) {\n output.writeInt64(5, workDone_);\n }\n for (int i = 0; i < broadcastBy_.size(); i++) {\n output.writeMessage(6, broadcastBy_.get(i));\n }\n if (((bitField0_ & 0x00000020) == 0x00000020)) {\n output.writeEnum(7, source_.getNumber());\n }\n getUnknownFields().writeTo(output);\n }\n\n private int memoizedSerializedSize = -1;\n public int getSerializedSize() {\n int size = memoizedSerializedSize;\n if (size != -1) return size;\n\n size = 0;\n if (((bitField0_ & 0x00000001) == 0x00000001)) {\n size += com.google.protobuf.CodedOutputStream\n .computeEnumSize(1, type_.getNumber());\n }\n if (((bitField0_ & 0x00000002) == 0x00000002)) {\n size += com.google.protobuf.CodedOutputStream\n .computeInt32Size(2, appearedAtHeight_);\n }\n if (((bitField0_ & 0x00000004) == 0x00000004)) {\n size += com.google.protobuf.CodedOutputStream\n .computeBytesSize(3, overridingTransaction_);\n }\n if (((bitField0_ & 0x00000008) == 0x00000008)) {\n size += com.google.protobuf.CodedOutputStream\n .computeInt32Size(4, depth_);\n }\n if (((bitField0_ & 0x00000010) == 0x00000010)) {\n size += com.google.protobuf.CodedOutputStream\n .computeInt64Size(5, workDone_);\n }\n for (int i = 0; i < broadcastBy_.size(); i++) {\n size += com.google.protobuf.CodedOutputStream\n .computeMessageSize(6, broadcastBy_.get(i));\n }\n if (((bitField0_ & 0x00000020) == 0x00000020)) {\n size += com.google.protobuf.CodedOutputStream\n .computeEnumSize(7, source_.getNumber());\n }\n size += getUnknownFields().getSerializedSize();\n memoizedSerializedSize = size;\n return size;\n }\n\n private static final long serialVersionUID = 0L;\n @java.lang.Override\n protected java.lang.Object writeReplace()\n throws java.io.ObjectStreamException {\n return super.writeReplace();\n }\n\n public static org.bitcoinj.wallet.Protos.TransactionConfidence parseFrom(\n com.google.protobuf.ByteString data)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n public static org.bitcoinj.wallet.Protos.TransactionConfidence parseFrom(\n com.google.protobuf.ByteString data,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n public static org.bitcoinj.wallet.Protos.TransactionConfidence parseFrom(byte[] data)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n public static org.bitcoinj.wallet.Protos.TransactionConfidence parseFrom(\n byte[] data,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n public static org.bitcoinj.wallet.Protos.TransactionConfidence parseFrom(java.io.InputStream input)\n throws java.io.IOException {\n return PARSER.parseFrom(input);\n }\n public static org.bitcoinj.wallet.Protos.TransactionConfidence parseFrom(\n java.io.InputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return PARSER.parseFrom(input, extensionRegistry);\n }\n public static org.bitcoinj.wallet.Protos.TransactionConfidence parseDelimitedFrom(java.io.InputStream input)\n throws java.io.IOException {\n return PARSER.parseDelimitedFrom(input);\n }\n public static org.bitcoinj.wallet.Protos.TransactionConfidence parseDelimitedFrom(\n java.io.InputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return PARSER.parseDelimitedFrom(input, extensionRegistry);\n }\n public static org.bitcoinj.wallet.Protos.TransactionConfidence parseFrom(\n com.google.protobuf.CodedInputStream input)\n throws java.io.IOException {\n return PARSER.parseFrom(input);\n }\n public static org.bitcoinj.wallet.Protos.TransactionConfidence parseFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return PARSER.parseFrom(input, extensionRegistry);\n }\n\n public static Builder newBuilder() { return Builder.create(); }\n public Builder newBuilderForType() { return newBuilder(); }\n public static Builder newBuilder(org.bitcoinj.wallet.Protos.TransactionConfidence prototype) {\n return newBuilder().mergeFrom(prototype);\n }\n public Builder toBuilder() { return newBuilder(this); }\n\n @java.lang.Override\n protected Builder newBuilderForType(\n com.google.protobuf.GeneratedMessage.BuilderParent parent) {\n Builder builder = new Builder(parent);\n return builder;\n }\n /**\n * Protobuf type {@code wallet.TransactionConfidence}\n *\n * <pre>\n **\n * A description of the confidence we have that a transaction cannot be reversed in the future.\n *\n * Parsing should be lenient, since this could change for different applications yet we should\n * maintain backward compatibility.\n * </pre>\n */\n public static final class Builder extends\n com.google.protobuf.GeneratedMessage.Builder<Builder>\n implements org.bitcoinj.wallet.Protos.TransactionConfidenceOrBuilder {\n public static final com.google.protobuf.Descriptors.Descriptor\n getDescriptor() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_TransactionConfidence_descriptor;\n }\n\n protected com.google.protobuf.GeneratedMessage.FieldAccessorTable\n internalGetFieldAccessorTable() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_TransactionConfidence_fieldAccessorTable\n .ensureFieldAccessorsInitialized(\n org.bitcoinj.wallet.Protos.TransactionConfidence.class, org.bitcoinj.wallet.Protos.TransactionConfidence.Builder.class);\n }\n\n // Construct using org.bitcoinj.wallet.Protos.TransactionConfidence.newBuilder()\n private Builder() {\n maybeForceBuilderInitialization();\n }\n\n private Builder(\n com.google.protobuf.GeneratedMessage.BuilderParent parent) {\n super(parent);\n maybeForceBuilderInitialization();\n }\n private void maybeForceBuilderInitialization() {\n if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {\n getBroadcastByFieldBuilder();\n }\n }\n private static Builder create() {\n return new Builder();\n }\n\n public Builder clear() {\n super.clear();\n type_ = org.bitcoinj.wallet.Protos.TransactionConfidence.Type.UNKNOWN;\n bitField0_ = (bitField0_ & ~0x00000001);\n appearedAtHeight_ = 0;\n bitField0_ = (bitField0_ & ~0x00000002);\n overridingTransaction_ = com.google.protobuf.ByteString.EMPTY;\n bitField0_ = (bitField0_ & ~0x00000004);\n depth_ = 0;\n bitField0_ = (bitField0_ & ~0x00000008);\n workDone_ = 0L;\n bitField0_ = (bitField0_ & ~0x00000010);\n if (broadcastByBuilder_ == null) {\n broadcastBy_ = java.util.Collections.emptyList();\n bitField0_ = (bitField0_ & ~0x00000020);\n } else {\n broadcastByBuilder_.clear();\n }\n source_ = org.bitcoinj.wallet.Protos.TransactionConfidence.Source.SOURCE_UNKNOWN;\n bitField0_ = (bitField0_ & ~0x00000040);\n return this;\n }\n\n public Builder clone() {\n return create().mergeFrom(buildPartial());\n }\n\n public com.google.protobuf.Descriptors.Descriptor\n getDescriptorForType() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_TransactionConfidence_descriptor;\n }\n\n public org.bitcoinj.wallet.Protos.TransactionConfidence getDefaultInstanceForType() {\n return org.bitcoinj.wallet.Protos.TransactionConfidence.getDefaultInstance();\n }\n\n public org.bitcoinj.wallet.Protos.TransactionConfidence build() {\n org.bitcoinj.wallet.Protos.TransactionConfidence result = buildPartial();\n if (!result.isInitialized()) {\n throw newUninitializedMessageException(result);\n }\n return result;\n }\n\n public org.bitcoinj.wallet.Protos.TransactionConfidence buildPartial() {\n org.bitcoinj.wallet.Protos.TransactionConfidence result = new org.bitcoinj.wallet.Protos.TransactionConfidence(this);\n int from_bitField0_ = bitField0_;\n int to_bitField0_ = 0;\n if (((from_bitField0_ & 0x00000001) == 0x00000001)) {\n to_bitField0_ |= 0x00000001;\n }\n result.type_ = type_;\n if (((from_bitField0_ & 0x00000002) == 0x00000002)) {\n to_bitField0_ |= 0x00000002;\n }\n result.appearedAtHeight_ = appearedAtHeight_;\n if (((from_bitField0_ & 0x00000004) == 0x00000004)) {\n to_bitField0_ |= 0x00000004;\n }\n result.overridingTransaction_ = overridingTransaction_;\n if (((from_bitField0_ & 0x00000008) == 0x00000008)) {\n to_bitField0_ |= 0x00000008;\n }\n result.depth_ = depth_;\n if (((from_bitField0_ & 0x00000010) == 0x00000010)) {\n to_bitField0_ |= 0x00000010;\n }\n result.workDone_ = workDone_;\n if (broadcastByBuilder_ == null) {\n if (((bitField0_ & 0x00000020) == 0x00000020)) {\n broadcastBy_ = java.util.Collections.unmodifiableList(broadcastBy_);\n bitField0_ = (bitField0_ & ~0x00000020);\n }\n result.broadcastBy_ = broadcastBy_;\n } else {\n result.broadcastBy_ = broadcastByBuilder_.build();\n }\n if (((from_bitField0_ & 0x00000040) == 0x00000040)) {\n to_bitField0_ |= 0x00000020;\n }\n result.source_ = source_;\n result.bitField0_ = to_bitField0_;\n onBuilt();\n return result;\n }\n\n public Builder mergeFrom(com.google.protobuf.Message other) {\n if (other instanceof org.bitcoinj.wallet.Protos.TransactionConfidence) {\n return mergeFrom((org.bitcoinj.wallet.Protos.TransactionConfidence)other);\n } else {\n super.mergeFrom(other);\n return this;\n }\n }\n\n public Builder mergeFrom(org.bitcoinj.wallet.Protos.TransactionConfidence other) {\n if (other == org.bitcoinj.wallet.Protos.TransactionConfidence.getDefaultInstance()) return this;\n if (other.hasType()) {\n setType(other.getType());\n }\n if (other.hasAppearedAtHeight()) {\n setAppearedAtHeight(other.getAppearedAtHeight());\n }\n if (other.hasOverridingTransaction()) {\n setOverridingTransaction(other.getOverridingTransaction());\n }\n if (other.hasDepth()) {\n setDepth(other.getDepth());\n }\n if (other.hasWorkDone()) {\n setWorkDone(other.getWorkDone());\n }\n if (broadcastByBuilder_ == null) {\n if (!other.broadcastBy_.isEmpty()) {\n if (broadcastBy_.isEmpty()) {\n broadcastBy_ = other.broadcastBy_;\n bitField0_ = (bitField0_ & ~0x00000020);\n } else {\n ensureBroadcastByIsMutable();\n broadcastBy_.addAll(other.broadcastBy_);\n }\n onChanged();\n }\n } else {\n if (!other.broadcastBy_.isEmpty()) {\n if (broadcastByBuilder_.isEmpty()) {\n broadcastByBuilder_.dispose();\n broadcastByBuilder_ = null;\n broadcastBy_ = other.broadcastBy_;\n bitField0_ = (bitField0_ & ~0x00000020);\n broadcastByBuilder_ = \n com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ?\n getBroadcastByFieldBuilder() : null;\n } else {\n broadcastByBuilder_.addAllMessages(other.broadcastBy_);\n }\n }\n }\n if (other.hasSource()) {\n setSource(other.getSource());\n }\n this.mergeUnknownFields(other.getUnknownFields());\n return this;\n }\n\n public final boolean isInitialized() {\n for (int i = 0; i < getBroadcastByCount(); i++) {\n if (!getBroadcastBy(i).isInitialized()) {\n \n return false;\n }\n }\n return true;\n }\n\n public Builder mergeFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n org.bitcoinj.wallet.Protos.TransactionConfidence parsedMessage = null;\n try {\n parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);\n } catch (com.google.protobuf.InvalidProtocolBufferException e) {\n parsedMessage = (org.bitcoinj.wallet.Protos.TransactionConfidence) e.getUnfinishedMessage();\n throw e;\n } finally {\n if (parsedMessage != null) {\n mergeFrom(parsedMessage);\n }\n }\n return this;\n }\n private int bitField0_;\n\n // optional .wallet.TransactionConfidence.Type type = 1;\n private org.bitcoinj.wallet.Protos.TransactionConfidence.Type type_ = org.bitcoinj.wallet.Protos.TransactionConfidence.Type.UNKNOWN;\n /**\n * <code>optional .wallet.TransactionConfidence.Type type = 1;</code>\n *\n * <pre>\n * This is optional in case we add confidence types to prevent parse errors - backwards compatible.\n * </pre>\n */\n public boolean hasType() {\n return ((bitField0_ & 0x00000001) == 0x00000001);\n }\n /**\n * <code>optional .wallet.TransactionConfidence.Type type = 1;</code>\n *\n * <pre>\n * This is optional in case we add confidence types to prevent parse errors - backwards compatible.\n * </pre>\n */\n public org.bitcoinj.wallet.Protos.TransactionConfidence.Type getType() {\n return type_;\n }\n /**\n * <code>optional .wallet.TransactionConfidence.Type type = 1;</code>\n *\n * <pre>\n * This is optional in case we add confidence types to prevent parse errors - backwards compatible.\n * </pre>\n */\n public Builder setType(org.bitcoinj.wallet.Protos.TransactionConfidence.Type value) {\n if (value == null) {\n throw new NullPointerException();\n }\n bitField0_ |= 0x00000001;\n type_ = value;\n onChanged();\n return this;\n }\n /**\n * <code>optional .wallet.TransactionConfidence.Type type = 1;</code>\n *\n * <pre>\n * This is optional in case we add confidence types to prevent parse errors - backwards compatible.\n * </pre>\n */\n public Builder clearType() {\n bitField0_ = (bitField0_ & ~0x00000001);\n type_ = org.bitcoinj.wallet.Protos.TransactionConfidence.Type.UNKNOWN;\n onChanged();\n return this;\n }\n\n // optional int32 appeared_at_height = 2;\n private int appearedAtHeight_ ;\n /**\n * <code>optional int32 appeared_at_height = 2;</code>\n *\n * <pre>\n * If type == BUILDING then this is the chain height at which the transaction was included.\n * </pre>\n */\n public boolean hasAppearedAtHeight() {\n return ((bitField0_ & 0x00000002) == 0x00000002);\n }\n /**\n * <code>optional int32 appeared_at_height = 2;</code>\n *\n * <pre>\n * If type == BUILDING then this is the chain height at which the transaction was included.\n * </pre>\n */\n public int getAppearedAtHeight() {\n return appearedAtHeight_;\n }\n /**\n * <code>optional int32 appeared_at_height = 2;</code>\n *\n * <pre>\n * If type == BUILDING then this is the chain height at which the transaction was included.\n * </pre>\n */\n public Builder setAppearedAtHeight(int value) {\n bitField0_ |= 0x00000002;\n appearedAtHeight_ = value;\n onChanged();\n return this;\n }\n /**\n * <code>optional int32 appeared_at_height = 2;</code>\n *\n * <pre>\n * If type == BUILDING then this is the chain height at which the transaction was included.\n * </pre>\n */\n public Builder clearAppearedAtHeight() {\n bitField0_ = (bitField0_ & ~0x00000002);\n appearedAtHeight_ = 0;\n onChanged();\n return this;\n }\n\n // optional bytes overriding_transaction = 3;\n private com.google.protobuf.ByteString overridingTransaction_ = com.google.protobuf.ByteString.EMPTY;\n /**\n * <code>optional bytes overriding_transaction = 3;</code>\n *\n * <pre>\n * If set, hash of the transaction that double spent this one into oblivion. A transaction can be double spent by\n * multiple transactions in the case of several inputs being re-spent by several transactions but we don't\n * bother to track them all, just the first. This only makes sense if type = DEAD.\n * </pre>\n */\n public boolean hasOverridingTransaction() {\n return ((bitField0_ & 0x00000004) == 0x00000004);\n }\n /**\n * <code>optional bytes overriding_transaction = 3;</code>\n *\n * <pre>\n * If set, hash of the transaction that double spent this one into oblivion. A transaction can be double spent by\n * multiple transactions in the case of several inputs being re-spent by several transactions but we don't\n * bother to track them all, just the first. This only makes sense if type = DEAD.\n * </pre>\n */\n public com.google.protobuf.ByteString getOverridingTransaction() {\n return overridingTransaction_;\n }\n /**\n * <code>optional bytes overriding_transaction = 3;</code>\n *\n * <pre>\n * If set, hash of the transaction that double spent this one into oblivion. A transaction can be double spent by\n * multiple transactions in the case of several inputs being re-spent by several transactions but we don't\n * bother to track them all, just the first. This only makes sense if type = DEAD.\n * </pre>\n */\n public Builder setOverridingTransaction(com.google.protobuf.ByteString value) {\n if (value == null) {\n throw new NullPointerException();\n }\n bitField0_ |= 0x00000004;\n overridingTransaction_ = value;\n onChanged();\n return this;\n }\n /**\n * <code>optional bytes overriding_transaction = 3;</code>\n *\n * <pre>\n * If set, hash of the transaction that double spent this one into oblivion. A transaction can be double spent by\n * multiple transactions in the case of several inputs being re-spent by several transactions but we don't\n * bother to track them all, just the first. This only makes sense if type = DEAD.\n * </pre>\n */\n public Builder clearOverridingTransaction() {\n bitField0_ = (bitField0_ & ~0x00000004);\n overridingTransaction_ = getDefaultInstance().getOverridingTransaction();\n onChanged();\n return this;\n }\n\n // optional int32 depth = 4;\n private int depth_ ;\n /**\n * <code>optional int32 depth = 4;</code>\n *\n * <pre>\n * If type == BUILDING then this is the depth of the transaction in the blockchain.\n * Zero confirmations: depth = 0, one confirmation: depth = 1 etc.\n * </pre>\n */\n public boolean hasDepth() {\n return ((bitField0_ & 0x00000008) == 0x00000008);\n }\n /**\n * <code>optional int32 depth = 4;</code>\n *\n * <pre>\n * If type == BUILDING then this is the depth of the transaction in the blockchain.\n * Zero confirmations: depth = 0, one confirmation: depth = 1 etc.\n * </pre>\n */\n public int getDepth() {\n return depth_;\n }\n /**\n * <code>optional int32 depth = 4;</code>\n *\n * <pre>\n * If type == BUILDING then this is the depth of the transaction in the blockchain.\n * Zero confirmations: depth = 0, one confirmation: depth = 1 etc.\n * </pre>\n */\n public Builder setDepth(int value) {\n bitField0_ |= 0x00000008;\n depth_ = value;\n onChanged();\n return this;\n }\n /**\n * <code>optional int32 depth = 4;</code>\n *\n * <pre>\n * If type == BUILDING then this is the depth of the transaction in the blockchain.\n * Zero confirmations: depth = 0, one confirmation: depth = 1 etc.\n * </pre>\n */\n public Builder clearDepth() {\n bitField0_ = (bitField0_ & ~0x00000008);\n depth_ = 0;\n onChanged();\n return this;\n }\n\n // optional int64 work_done = 5;\n private long workDone_ ;\n /**\n * <code>optional int64 work_done = 5;</code>\n *\n * <pre>\n * If type == BUILDING then this is the cumulative workDone for the block the transaction appears in, together with\n * all blocks that bury it.\n * </pre>\n */\n public boolean hasWorkDone() {\n return ((bitField0_ & 0x00000010) == 0x00000010);\n }\n /**\n * <code>optional int64 work_done = 5;</code>\n *\n * <pre>\n * If type == BUILDING then this is the cumulative workDone for the block the transaction appears in, together with\n * all blocks that bury it.\n * </pre>\n */\n public long getWorkDone() {\n return workDone_;\n }\n /**\n * <code>optional int64 work_done = 5;</code>\n *\n * <pre>\n * If type == BUILDING then this is the cumulative workDone for the block the transaction appears in, together with\n * all blocks that bury it.\n * </pre>\n */\n public Builder setWorkDone(long value) {\n bitField0_ |= 0x00000010;\n workDone_ = value;\n onChanged();\n return this;\n }\n /**\n * <code>optional int64 work_done = 5;</code>\n *\n * <pre>\n * If type == BUILDING then this is the cumulative workDone for the block the transaction appears in, together with\n * all blocks that bury it.\n * </pre>\n */\n public Builder clearWorkDone() {\n bitField0_ = (bitField0_ & ~0x00000010);\n workDone_ = 0L;\n onChanged();\n return this;\n }\n\n // repeated .wallet.PeerAddress broadcast_by = 6;\n private java.util.List<org.bitcoinj.wallet.Protos.PeerAddress> broadcastBy_ =\n java.util.Collections.emptyList();\n private void ensureBroadcastByIsMutable() {\n if (!((bitField0_ & 0x00000020) == 0x00000020)) {\n broadcastBy_ = new java.util.ArrayList<org.bitcoinj.wallet.Protos.PeerAddress>(broadcastBy_);\n bitField0_ |= 0x00000020;\n }\n }\n\n private com.google.protobuf.RepeatedFieldBuilder<\n org.bitcoinj.wallet.Protos.PeerAddress, org.bitcoinj.wallet.Protos.PeerAddress.Builder, org.bitcoinj.wallet.Protos.PeerAddressOrBuilder> broadcastByBuilder_;\n\n /**\n * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code>\n */\n public java.util.List<org.bitcoinj.wallet.Protos.PeerAddress> getBroadcastByList() {\n if (broadcastByBuilder_ == null) {\n return java.util.Collections.unmodifiableList(broadcastBy_);\n } else {\n return broadcastByBuilder_.getMessageList();\n }\n }\n /**\n * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code>\n */\n public int getBroadcastByCount() {\n if (broadcastByBuilder_ == null) {\n return broadcastBy_.size();\n } else {\n return broadcastByBuilder_.getCount();\n }\n }\n /**\n * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code>\n */\n public org.bitcoinj.wallet.Protos.PeerAddress getBroadcastBy(int index) {\n if (broadcastByBuilder_ == null) {\n return broadcastBy_.get(index);\n } else {\n return broadcastByBuilder_.getMessage(index);\n }\n }\n /**\n * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code>\n */\n public Builder setBroadcastBy(\n int index, org.bitcoinj.wallet.Protos.PeerAddress value) {\n if (broadcastByBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureBroadcastByIsMutable();\n broadcastBy_.set(index, value);\n onChanged();\n } else {\n broadcastByBuilder_.setMessage(index, value);\n }\n return this;\n }\n /**\n * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code>\n */\n public Builder setBroadcastBy(\n int index, org.bitcoinj.wallet.Protos.PeerAddress.Builder builderForValue) {\n if (broadcastByBuilder_ == null) {\n ensureBroadcastByIsMutable();\n broadcastBy_.set(index, builderForValue.build());\n onChanged();\n } else {\n broadcastByBuilder_.setMessage(index, builderForValue.build());\n }\n return this;\n }\n /**\n * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code>\n */\n public Builder addBroadcastBy(org.bitcoinj.wallet.Protos.PeerAddress value) {\n if (broadcastByBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureBroadcastByIsMutable();\n broadcastBy_.add(value);\n onChanged();\n } else {\n broadcastByBuilder_.addMessage(value);\n }\n return this;\n }\n /**\n * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code>\n */\n public Builder addBroadcastBy(\n int index, org.bitcoinj.wallet.Protos.PeerAddress value) {\n if (broadcastByBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureBroadcastByIsMutable();\n broadcastBy_.add(index, value);\n onChanged();\n } else {\n broadcastByBuilder_.addMessage(index, value);\n }\n return this;\n }\n /**\n * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code>\n */\n public Builder addBroadcastBy(\n org.bitcoinj.wallet.Protos.PeerAddress.Builder builderForValue) {\n if (broadcastByBuilder_ == null) {\n ensureBroadcastByIsMutable();\n broadcastBy_.add(builderForValue.build());\n onChanged();\n } else {\n broadcastByBuilder_.addMessage(builderForValue.build());\n }\n return this;\n }\n /**\n * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code>\n */\n public Builder addBroadcastBy(\n int index, org.bitcoinj.wallet.Protos.PeerAddress.Builder builderForValue) {\n if (broadcastByBuilder_ == null) {\n ensureBroadcastByIsMutable();\n broadcastBy_.add(index, builderForValue.build());\n onChanged();\n } else {\n broadcastByBuilder_.addMessage(index, builderForValue.build());\n }\n return this;\n }\n /**\n * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code>\n */\n public Builder addAllBroadcastBy(\n java.lang.Iterable<? extends org.bitcoinj.wallet.Protos.PeerAddress> values) {\n if (broadcastByBuilder_ == null) {\n ensureBroadcastByIsMutable();\n super.addAll(values, broadcastBy_);\n onChanged();\n } else {\n broadcastByBuilder_.addAllMessages(values);\n }\n return this;\n }\n /**\n * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code>\n */\n public Builder clearBroadcastBy() {\n if (broadcastByBuilder_ == null) {\n broadcastBy_ = java.util.Collections.emptyList();\n bitField0_ = (bitField0_ & ~0x00000020);\n onChanged();\n } else {\n broadcastByBuilder_.clear();\n }\n return this;\n }\n /**\n * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code>\n */\n public Builder removeBroadcastBy(int index) {\n if (broadcastByBuilder_ == null) {\n ensureBroadcastByIsMutable();\n broadcastBy_.remove(index);\n onChanged();\n } else {\n broadcastByBuilder_.remove(index);\n }\n return this;\n }\n /**\n * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code>\n */\n public org.bitcoinj.wallet.Protos.PeerAddress.Builder getBroadcastByBuilder(\n int index) {\n return getBroadcastByFieldBuilder().getBuilder(index);\n }\n /**\n * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code>\n */\n public org.bitcoinj.wallet.Protos.PeerAddressOrBuilder getBroadcastByOrBuilder(\n int index) {\n if (broadcastByBuilder_ == null) {\n return broadcastBy_.get(index); } else {\n return broadcastByBuilder_.getMessageOrBuilder(index);\n }\n }\n /**\n * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code>\n */\n public java.util.List<? extends org.bitcoinj.wallet.Protos.PeerAddressOrBuilder> \n getBroadcastByOrBuilderList() {\n if (broadcastByBuilder_ != null) {\n return broadcastByBuilder_.getMessageOrBuilderList();\n } else {\n return java.util.Collections.unmodifiableList(broadcastBy_);\n }\n }\n /**\n * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code>\n */\n public org.bitcoinj.wallet.Protos.PeerAddress.Builder addBroadcastByBuilder() {\n return getBroadcastByFieldBuilder().addBuilder(\n org.bitcoinj.wallet.Protos.PeerAddress.getDefaultInstance());\n }\n /**\n * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code>\n */\n public org.bitcoinj.wallet.Protos.PeerAddress.Builder addBroadcastByBuilder(\n int index) {\n return getBroadcastByFieldBuilder().addBuilder(\n index, org.bitcoinj.wallet.Protos.PeerAddress.getDefaultInstance());\n }\n /**\n * <code>repeated .wallet.PeerAddress broadcast_by = 6;</code>\n */\n public java.util.List<org.bitcoinj.wallet.Protos.PeerAddress.Builder> \n getBroadcastByBuilderList() {\n return getBroadcastByFieldBuilder().getBuilderList();\n }\n private com.google.protobuf.RepeatedFieldBuilder<\n org.bitcoinj.wallet.Protos.PeerAddress, org.bitcoinj.wallet.Protos.PeerAddress.Builder, org.bitcoinj.wallet.Protos.PeerAddressOrBuilder> \n getBroadcastByFieldBuilder() {\n if (broadcastByBuilder_ == null) {\n broadcastByBuilder_ = new com.google.protobuf.RepeatedFieldBuilder<\n org.bitcoinj.wallet.Protos.PeerAddress, org.bitcoinj.wallet.Protos.PeerAddress.Builder, org.bitcoinj.wallet.Protos.PeerAddressOrBuilder>(\n broadcastBy_,\n ((bitField0_ & 0x00000020) == 0x00000020),\n getParentForChildren(),\n isClean());\n broadcastBy_ = null;\n }\n return broadcastByBuilder_;\n }\n\n // optional .wallet.TransactionConfidence.Source source = 7;\n private org.bitcoinj.wallet.Protos.TransactionConfidence.Source source_ = org.bitcoinj.wallet.Protos.TransactionConfidence.Source.SOURCE_UNKNOWN;\n /**\n * <code>optional .wallet.TransactionConfidence.Source source = 7;</code>\n */\n public boolean hasSource() {\n return ((bitField0_ & 0x00000040) == 0x00000040);\n }\n /**\n * <code>optional .wallet.TransactionConfidence.Source source = 7;</code>\n */\n public org.bitcoinj.wallet.Protos.TransactionConfidence.Source getSource() {\n return source_;\n }\n /**\n * <code>optional .wallet.TransactionConfidence.Source source = 7;</code>\n */\n public Builder setSource(org.bitcoinj.wallet.Protos.TransactionConfidence.Source value) {\n if (value == null) {\n throw new NullPointerException();\n }\n bitField0_ |= 0x00000040;\n source_ = value;\n onChanged();\n return this;\n }\n /**\n * <code>optional .wallet.TransactionConfidence.Source source = 7;</code>\n */\n public Builder clearSource() {\n bitField0_ = (bitField0_ & ~0x00000040);\n source_ = org.bitcoinj.wallet.Protos.TransactionConfidence.Source.SOURCE_UNKNOWN;\n onChanged();\n return this;\n }\n\n // @@protoc_insertion_point(builder_scope:wallet.TransactionConfidence)\n }\n\n static {\n defaultInstance = new TransactionConfidence(true);\n defaultInstance.initFields();\n }\n\n // @@protoc_insertion_point(class_scope:wallet.TransactionConfidence)\n }\n\n public interface TransactionOrBuilder\n extends com.google.protobuf.MessageOrBuilder {\n\n // required int32 version = 1;\n /**\n * <code>required int32 version = 1;</code>\n *\n * <pre>\n * See Wallet.java for detailed description of pool semantics\n * </pre>\n */\n boolean hasVersion();\n /**\n * <code>required int32 version = 1;</code>\n *\n * <pre>\n * See Wallet.java for detailed description of pool semantics\n * </pre>\n */\n int getVersion();\n\n // required bytes hash = 2;\n /**\n * <code>required bytes hash = 2;</code>\n */\n boolean hasHash();\n /**\n * <code>required bytes hash = 2;</code>\n */\n com.google.protobuf.ByteString getHash();\n\n // optional .wallet.Transaction.Pool pool = 3;\n /**\n * <code>optional .wallet.Transaction.Pool pool = 3;</code>\n *\n * <pre>\n * If pool is not present, that means either:\n * - This Transaction is either not in a wallet at all (the proto is re-used elsewhere)\n * - Or it is stored but for other purposes, for example, because it is the overriding transaction of a double spend.\n * - Or the Pool enum got a new value which your software is too old to parse.\n * </pre>\n */\n boolean hasPool();\n /**\n * <code>optional .wallet.Transaction.Pool pool = 3;</code>\n *\n * <pre>\n * If pool is not present, that means either:\n * - This Transaction is either not in a wallet at all (the proto is re-used elsewhere)\n * - Or it is stored but for other purposes, for example, because it is the overriding transaction of a double spend.\n * - Or the Pool enum got a new value which your software is too old to parse.\n * </pre>\n */\n org.bitcoinj.wallet.Protos.Transaction.Pool getPool();\n\n // optional uint32 lock_time = 4;\n /**\n * <code>optional uint32 lock_time = 4;</code>\n *\n * <pre>\n * The nLockTime field is useful for contracts.\n * </pre>\n */\n boolean hasLockTime();\n /**\n * <code>optional uint32 lock_time = 4;</code>\n *\n * <pre>\n * The nLockTime field is useful for contracts.\n * </pre>\n */\n int getLockTime();\n\n // optional int64 updated_at = 5;\n /**\n * <code>optional int64 updated_at = 5;</code>\n *\n * <pre>\n * millis since epoch the transaction was last updated\n * </pre>\n */\n boolean hasUpdatedAt();\n /**\n * <code>optional int64 updated_at = 5;</code>\n *\n * <pre>\n * millis since epoch the transaction was last updated\n * </pre>\n */\n long getUpdatedAt();\n\n // repeated .wallet.TransactionInput transaction_input = 6;\n /**\n * <code>repeated .wallet.TransactionInput transaction_input = 6;</code>\n */\n java.util.List<org.bitcoinj.wallet.Protos.TransactionInput> \n getTransactionInputList();\n /**\n * <code>repeated .wallet.TransactionInput transaction_input = 6;</code>\n */\n org.bitcoinj.wallet.Protos.TransactionInput getTransactionInput(int index);\n /**\n * <code>repeated .wallet.TransactionInput transaction_input = 6;</code>\n */\n int getTransactionInputCount();\n /**\n * <code>repeated .wallet.TransactionInput transaction_input = 6;</code>\n */\n java.util.List<? extends org.bitcoinj.wallet.Protos.TransactionInputOrBuilder> \n getTransactionInputOrBuilderList();\n /**\n * <code>repeated .wallet.TransactionInput transaction_input = 6;</code>\n */\n org.bitcoinj.wallet.Protos.TransactionInputOrBuilder getTransactionInputOrBuilder(\n int index);\n\n // repeated .wallet.TransactionOutput transaction_output = 7;\n /**\n * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code>\n */\n java.util.List<org.bitcoinj.wallet.Protos.TransactionOutput> \n getTransactionOutputList();\n /**\n * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code>\n */\n org.bitcoinj.wallet.Protos.TransactionOutput getTransactionOutput(int index);\n /**\n * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code>\n */\n int getTransactionOutputCount();\n /**\n * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code>\n */\n java.util.List<? extends org.bitcoinj.wallet.Protos.TransactionOutputOrBuilder> \n getTransactionOutputOrBuilderList();\n /**\n * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code>\n */\n org.bitcoinj.wallet.Protos.TransactionOutputOrBuilder getTransactionOutputOrBuilder(\n int index);\n\n // repeated bytes block_hash = 8;\n /**\n * <code>repeated bytes block_hash = 8;</code>\n *\n * <pre>\n * A list of blocks in which the transaction has been observed (on any chain). Also, a number used to disambiguate\n * ordering within a block.\n * </pre>\n */\n java.util.List<com.google.protobuf.ByteString> getBlockHashList();\n /**\n * <code>repeated bytes block_hash = 8;</code>\n *\n * <pre>\n * A list of blocks in which the transaction has been observed (on any chain). Also, a number used to disambiguate\n * ordering within a block.\n * </pre>\n */\n int getBlockHashCount();\n /**\n * <code>repeated bytes block_hash = 8;</code>\n *\n * <pre>\n * A list of blocks in which the transaction has been observed (on any chain). Also, a number used to disambiguate\n * ordering within a block.\n * </pre>\n */\n com.google.protobuf.ByteString getBlockHash(int index);\n\n // repeated int32 block_relativity_offsets = 11;\n /**\n * <code>repeated int32 block_relativity_offsets = 11;</code>\n */\n java.util.List<java.lang.Integer> getBlockRelativityOffsetsList();\n /**\n * <code>repeated int32 block_relativity_offsets = 11;</code>\n */\n int getBlockRelativityOffsetsCount();\n /**\n * <code>repeated int32 block_relativity_offsets = 11;</code>\n */\n int getBlockRelativityOffsets(int index);\n\n // optional .wallet.TransactionConfidence confidence = 9;\n /**\n * <code>optional .wallet.TransactionConfidence confidence = 9;</code>\n *\n * <pre>\n * Data describing where the transaction is in the chain.\n * </pre>\n */\n boolean hasConfidence();\n /**\n * <code>optional .wallet.TransactionConfidence confidence = 9;</code>\n *\n * <pre>\n * Data describing where the transaction is in the chain.\n * </pre>\n */\n org.bitcoinj.wallet.Protos.TransactionConfidence getConfidence();\n /**\n * <code>optional .wallet.TransactionConfidence confidence = 9;</code>\n *\n * <pre>\n * Data describing where the transaction is in the chain.\n * </pre>\n */\n org.bitcoinj.wallet.Protos.TransactionConfidenceOrBuilder getConfidenceOrBuilder();\n\n // optional .wallet.Transaction.Purpose purpose = 10 [default = UNKNOWN];\n /**\n * <code>optional .wallet.Transaction.Purpose purpose = 10 [default = UNKNOWN];</code>\n */\n boolean hasPurpose();\n /**\n * <code>optional .wallet.Transaction.Purpose purpose = 10 [default = UNKNOWN];</code>\n */\n org.bitcoinj.wallet.Protos.Transaction.Purpose getPurpose();\n }\n /**\n * Protobuf type {@code wallet.Transaction}\n */\n public static final class Transaction extends\n com.google.protobuf.GeneratedMessage\n implements TransactionOrBuilder {\n // Use Transaction.newBuilder() to construct.\n private Transaction(com.google.protobuf.GeneratedMessage.Builder<?> builder) {\n super(builder);\n this.unknownFields = builder.getUnknownFields();\n }\n private Transaction(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }\n\n private static final Transaction defaultInstance;\n public static Transaction getDefaultInstance() {\n return defaultInstance;\n }\n\n public Transaction getDefaultInstanceForType() {\n return defaultInstance;\n }\n\n private final com.google.protobuf.UnknownFieldSet unknownFields;\n @java.lang.Override\n public final com.google.protobuf.UnknownFieldSet\n getUnknownFields() {\n return this.unknownFields;\n }\n private Transaction(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n initFields();\n int mutable_bitField0_ = 0;\n com.google.protobuf.UnknownFieldSet.Builder unknownFields =\n com.google.protobuf.UnknownFieldSet.newBuilder();\n try {\n boolean done = false;\n while (!done) {\n int tag = input.readTag();\n switch (tag) {\n case 0:\n done = true;\n break;\n default: {\n if (!parseUnknownField(input, unknownFields,\n extensionRegistry, tag)) {\n done = true;\n }\n break;\n }\n case 8: {\n bitField0_ |= 0x00000001;\n version_ = input.readInt32();\n break;\n }\n case 18: {\n bitField0_ |= 0x00000002;\n hash_ = input.readBytes();\n break;\n }\n case 24: {\n int rawValue = input.readEnum();\n org.bitcoinj.wallet.Protos.Transaction.Pool value = org.bitcoinj.wallet.Protos.Transaction.Pool.valueOf(rawValue);\n if (value == null) {\n unknownFields.mergeVarintField(3, rawValue);\n } else {\n bitField0_ |= 0x00000004;\n pool_ = value;\n }\n break;\n }\n case 32: {\n bitField0_ |= 0x00000008;\n lockTime_ = input.readUInt32();\n break;\n }\n case 40: {\n bitField0_ |= 0x00000010;\n updatedAt_ = input.readInt64();\n break;\n }\n case 50: {\n if (!((mutable_bitField0_ & 0x00000020) == 0x00000020)) {\n transactionInput_ = new java.util.ArrayList<org.bitcoinj.wallet.Protos.TransactionInput>();\n mutable_bitField0_ |= 0x00000020;\n }\n transactionInput_.add(input.readMessage(org.bitcoinj.wallet.Protos.TransactionInput.PARSER, extensionRegistry));\n break;\n }\n case 58: {\n if (!((mutable_bitField0_ & 0x00000040) == 0x00000040)) {\n transactionOutput_ = new java.util.ArrayList<org.bitcoinj.wallet.Protos.TransactionOutput>();\n mutable_bitField0_ |= 0x00000040;\n }\n transactionOutput_.add(input.readMessage(org.bitcoinj.wallet.Protos.TransactionOutput.PARSER, extensionRegistry));\n break;\n }\n case 66: {\n if (!((mutable_bitField0_ & 0x00000080) == 0x00000080)) {\n blockHash_ = new java.util.ArrayList<com.google.protobuf.ByteString>();\n mutable_bitField0_ |= 0x00000080;\n }\n blockHash_.add(input.readBytes());\n break;\n }\n case 74: {\n org.bitcoinj.wallet.Protos.TransactionConfidence.Builder subBuilder = null;\n if (((bitField0_ & 0x00000020) == 0x00000020)) {\n subBuilder = confidence_.toBuilder();\n }\n confidence_ = input.readMessage(org.bitcoinj.wallet.Protos.TransactionConfidence.PARSER, extensionRegistry);\n if (subBuilder != null) {\n subBuilder.mergeFrom(confidence_);\n confidence_ = subBuilder.buildPartial();\n }\n bitField0_ |= 0x00000020;\n break;\n }\n case 80: {\n int rawValue = input.readEnum();\n org.bitcoinj.wallet.Protos.Transaction.Purpose value = org.bitcoinj.wallet.Protos.Transaction.Purpose.valueOf(rawValue);\n if (value == null) {\n unknownFields.mergeVarintField(10, rawValue);\n } else {\n bitField0_ |= 0x00000040;\n purpose_ = value;\n }\n break;\n }\n case 88: {\n if (!((mutable_bitField0_ & 0x00000100) == 0x00000100)) {\n blockRelativityOffsets_ = new java.util.ArrayList<java.lang.Integer>();\n mutable_bitField0_ |= 0x00000100;\n }\n blockRelativityOffsets_.add(input.readInt32());\n break;\n }\n case 90: {\n int length = input.readRawVarint32();\n int limit = input.pushLimit(length);\n if (!((mutable_bitField0_ & 0x00000100) == 0x00000100) && input.getBytesUntilLimit() > 0) {\n blockRelativityOffsets_ = new java.util.ArrayList<java.lang.Integer>();\n mutable_bitField0_ |= 0x00000100;\n }\n while (input.getBytesUntilLimit() > 0) {\n blockRelativityOffsets_.add(input.readInt32());\n }\n input.popLimit(limit);\n break;\n }\n }\n }\n } catch (com.google.protobuf.InvalidProtocolBufferException e) {\n throw e.setUnfinishedMessage(this);\n } catch (java.io.IOException e) {\n throw new com.google.protobuf.InvalidProtocolBufferException(\n e.getMessage()).setUnfinishedMessage(this);\n } finally {\n if (((mutable_bitField0_ & 0x00000020) == 0x00000020)) {\n transactionInput_ = java.util.Collections.unmodifiableList(transactionInput_);\n }\n if (((mutable_bitField0_ & 0x00000040) == 0x00000040)) {\n transactionOutput_ = java.util.Collections.unmodifiableList(transactionOutput_);\n }\n if (((mutable_bitField0_ & 0x00000080) == 0x00000080)) {\n blockHash_ = java.util.Collections.unmodifiableList(blockHash_);\n }\n if (((mutable_bitField0_ & 0x00000100) == 0x00000100)) {\n blockRelativityOffsets_ = java.util.Collections.unmodifiableList(blockRelativityOffsets_);\n }\n this.unknownFields = unknownFields.build();\n makeExtensionsImmutable();\n }\n }\n public static final com.google.protobuf.Descriptors.Descriptor\n getDescriptor() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_Transaction_descriptor;\n }\n\n protected com.google.protobuf.GeneratedMessage.FieldAccessorTable\n internalGetFieldAccessorTable() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_Transaction_fieldAccessorTable\n .ensureFieldAccessorsInitialized(\n org.bitcoinj.wallet.Protos.Transaction.class, org.bitcoinj.wallet.Protos.Transaction.Builder.class);\n }\n\n public static com.google.protobuf.Parser<Transaction> PARSER =\n new com.google.protobuf.AbstractParser<Transaction>() {\n public Transaction parsePartialFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return new Transaction(input, extensionRegistry);\n }\n };\n\n @java.lang.Override\n public com.google.protobuf.Parser<Transaction> getParserForType() {\n return PARSER;\n }\n\n /**\n * Protobuf enum {@code wallet.Transaction.Pool}\n *\n * <pre>\n **\n * This is a bitfield oriented enum, with the following bits:\n * \n * bit 0 - spent\n * bit 1 - appears in alt chain\n * bit 2 - appears in best chain\n * bit 3 - double-spent\n * bit 4 - pending (we would like the tx to go into the best chain)\n * \n * Not all combinations are interesting, just the ones actually used in the enum.\n * </pre>\n */\n public enum Pool\n implements com.google.protobuf.ProtocolMessageEnum {\n /**\n * <code>UNSPENT = 4;</code>\n *\n * <pre>\n * In best chain, not all outputs spent\n * </pre>\n */\n UNSPENT(0, 4),\n /**\n * <code>SPENT = 5;</code>\n *\n * <pre>\n * In best chain, all outputs spent\n * </pre>\n */\n SPENT(1, 5),\n /**\n * <code>INACTIVE = 2;</code>\n *\n * <pre>\n * In non-best chain, not our transaction\n * </pre>\n */\n INACTIVE(2, 2),\n /**\n * <code>DEAD = 10;</code>\n *\n * <pre>\n * Double-spent by a transaction in the best chain\n * </pre>\n */\n DEAD(3, 10),\n /**\n * <code>PENDING = 16;</code>\n *\n * <pre>\n * Our transaction, not in any chain\n * </pre>\n */\n PENDING(4, 16),\n /**\n * <code>PENDING_INACTIVE = 18;</code>\n *\n * <pre>\n * In non-best chain, our transaction\n * </pre>\n */\n PENDING_INACTIVE(5, 18),\n ;\n\n /**\n * <code>UNSPENT = 4;</code>\n *\n * <pre>\n * In best chain, not all outputs spent\n * </pre>\n */\n public static final int UNSPENT_VALUE = 4;\n /**\n * <code>SPENT = 5;</code>\n *\n * <pre>\n * In best chain, all outputs spent\n * </pre>\n */\n public static final int SPENT_VALUE = 5;\n /**\n * <code>INACTIVE = 2;</code>\n *\n * <pre>\n * In non-best chain, not our transaction\n * </pre>\n */\n public static final int INACTIVE_VALUE = 2;\n /**\n * <code>DEAD = 10;</code>\n *\n * <pre>\n * Double-spent by a transaction in the best chain\n * </pre>\n */\n public static final int DEAD_VALUE = 10;\n /**\n * <code>PENDING = 16;</code>\n *\n * <pre>\n * Our transaction, not in any chain\n * </pre>\n */\n public static final int PENDING_VALUE = 16;\n /**\n * <code>PENDING_INACTIVE = 18;</code>\n *\n * <pre>\n * In non-best chain, our transaction\n * </pre>\n */\n public static final int PENDING_INACTIVE_VALUE = 18;\n\n\n public final int getNumber() { return value; }\n\n public static Pool valueOf(int value) {\n switch (value) {\n case 4: return UNSPENT;\n case 5: return SPENT;\n case 2: return INACTIVE;\n case 10: return DEAD;\n case 16: return PENDING;\n case 18: return PENDING_INACTIVE;\n default: return null;\n }\n }\n\n public static com.google.protobuf.Internal.EnumLiteMap<Pool>\n internalGetValueMap() {\n return internalValueMap;\n }\n private static com.google.protobuf.Internal.EnumLiteMap<Pool>\n internalValueMap =\n new com.google.protobuf.Internal.EnumLiteMap<Pool>() {\n public Pool findValueByNumber(int number) {\n return Pool.valueOf(number);\n }\n };\n\n public final com.google.protobuf.Descriptors.EnumValueDescriptor\n getValueDescriptor() {\n return getDescriptor().getValues().get(index);\n }\n public final com.google.protobuf.Descriptors.EnumDescriptor\n getDescriptorForType() {\n return getDescriptor();\n }\n public static final com.google.protobuf.Descriptors.EnumDescriptor\n getDescriptor() {\n return org.bitcoinj.wallet.Protos.Transaction.getDescriptor().getEnumTypes().get(0);\n }\n\n private static final Pool[] VALUES = values();\n\n public static Pool valueOf(\n com.google.protobuf.Descriptors.EnumValueDescriptor desc) {\n if (desc.getType() != getDescriptor()) {\n throw new java.lang.IllegalArgumentException(\n \"EnumValueDescriptor is not for this type.\");\n }\n return VALUES[desc.getIndex()];\n }\n\n private final int index;\n private final int value;\n\n private Pool(int index, int value) {\n this.index = index;\n this.value = value;\n }\n\n // @@protoc_insertion_point(enum_scope:wallet.Transaction.Pool)\n }\n\n /**\n * Protobuf enum {@code wallet.Transaction.Purpose}\n *\n * <pre>\n * For what purpose the transaction was created.\n * </pre>\n */\n public enum Purpose\n implements com.google.protobuf.ProtocolMessageEnum {\n /**\n * <code>UNKNOWN = 0;</code>\n *\n * <pre>\n * Old wallets or the purpose genuinely is a mystery (e.g. imported from some external source).\n * </pre>\n */\n UNKNOWN(0, 0),\n /**\n * <code>USER_PAYMENT = 1;</code>\n *\n * <pre>\n * Created in response to a user request for payment. This is the normal case.\n * </pre>\n */\n USER_PAYMENT(1, 1),\n /**\n * <code>KEY_ROTATION = 2;</code>\n *\n * <pre>\n * Created automatically to move money from rotated keys.\n * </pre>\n */\n KEY_ROTATION(2, 2),\n ;\n\n /**\n * <code>UNKNOWN = 0;</code>\n *\n * <pre>\n * Old wallets or the purpose genuinely is a mystery (e.g. imported from some external source).\n * </pre>\n */\n public static final int UNKNOWN_VALUE = 0;\n /**\n * <code>USER_PAYMENT = 1;</code>\n *\n * <pre>\n * Created in response to a user request for payment. This is the normal case.\n * </pre>\n */\n public static final int USER_PAYMENT_VALUE = 1;\n /**\n * <code>KEY_ROTATION = 2;</code>\n *\n * <pre>\n * Created automatically to move money from rotated keys.\n * </pre>\n */\n public static final int KEY_ROTATION_VALUE = 2;\n\n\n public final int getNumber() { return value; }\n\n public static Purpose valueOf(int value) {\n switch (value) {\n case 0: return UNKNOWN;\n case 1: return USER_PAYMENT;\n case 2: return KEY_ROTATION;\n default: return null;\n }\n }\n\n public static com.google.protobuf.Internal.EnumLiteMap<Purpose>\n internalGetValueMap() {\n return internalValueMap;\n }\n private static com.google.protobuf.Internal.EnumLiteMap<Purpose>\n internalValueMap =\n new com.google.protobuf.Internal.EnumLiteMap<Purpose>() {\n public Purpose findValueByNumber(int number) {\n return Purpose.valueOf(number);\n }\n };\n\n public final com.google.protobuf.Descriptors.EnumValueDescriptor\n getValueDescriptor() {\n return getDescriptor().getValues().get(index);\n }\n public final com.google.protobuf.Descriptors.EnumDescriptor\n getDescriptorForType() {\n return getDescriptor();\n }\n public static final com.google.protobuf.Descriptors.EnumDescriptor\n getDescriptor() {\n return org.bitcoinj.wallet.Protos.Transaction.getDescriptor().getEnumTypes().get(1);\n }\n\n private static final Purpose[] VALUES = values();\n\n public static Purpose valueOf(\n com.google.protobuf.Descriptors.EnumValueDescriptor desc) {\n if (desc.getType() != getDescriptor()) {\n throw new java.lang.IllegalArgumentException(\n \"EnumValueDescriptor is not for this type.\");\n }\n return VALUES[desc.getIndex()];\n }\n\n private final int index;\n private final int value;\n\n private Purpose(int index, int value) {\n this.index = index;\n this.value = value;\n }\n\n // @@protoc_insertion_point(enum_scope:wallet.Transaction.Purpose)\n }\n\n private int bitField0_;\n // required int32 version = 1;\n public static final int VERSION_FIELD_NUMBER = 1;\n private int version_;\n /**\n * <code>required int32 version = 1;</code>\n *\n * <pre>\n * See Wallet.java for detailed description of pool semantics\n * </pre>\n */\n public boolean hasVersion() {\n return ((bitField0_ & 0x00000001) == 0x00000001);\n }\n /**\n * <code>required int32 version = 1;</code>\n *\n * <pre>\n * See Wallet.java for detailed description of pool semantics\n * </pre>\n */\n public int getVersion() {\n return version_;\n }\n\n // required bytes hash = 2;\n public static final int HASH_FIELD_NUMBER = 2;\n private com.google.protobuf.ByteString hash_;\n /**\n * <code>required bytes hash = 2;</code>\n */\n public boolean hasHash() {\n return ((bitField0_ & 0x00000002) == 0x00000002);\n }\n /**\n * <code>required bytes hash = 2;</code>\n */\n public com.google.protobuf.ByteString getHash() {\n return hash_;\n }\n\n // optional .wallet.Transaction.Pool pool = 3;\n public static final int POOL_FIELD_NUMBER = 3;\n private org.bitcoinj.wallet.Protos.Transaction.Pool pool_;\n /**\n * <code>optional .wallet.Transaction.Pool pool = 3;</code>\n *\n * <pre>\n * If pool is not present, that means either:\n * - This Transaction is either not in a wallet at all (the proto is re-used elsewhere)\n * - Or it is stored but for other purposes, for example, because it is the overriding transaction of a double spend.\n * - Or the Pool enum got a new value which your software is too old to parse.\n * </pre>\n */\n public boolean hasPool() {\n return ((bitField0_ & 0x00000004) == 0x00000004);\n }\n /**\n * <code>optional .wallet.Transaction.Pool pool = 3;</code>\n *\n * <pre>\n * If pool is not present, that means either:\n * - This Transaction is either not in a wallet at all (the proto is re-used elsewhere)\n * - Or it is stored but for other purposes, for example, because it is the overriding transaction of a double spend.\n * - Or the Pool enum got a new value which your software is too old to parse.\n * </pre>\n */\n public org.bitcoinj.wallet.Protos.Transaction.Pool getPool() {\n return pool_;\n }\n\n // optional uint32 lock_time = 4;\n public static final int LOCK_TIME_FIELD_NUMBER = 4;\n private int lockTime_;\n /**\n * <code>optional uint32 lock_time = 4;</code>\n *\n * <pre>\n * The nLockTime field is useful for contracts.\n * </pre>\n */\n public boolean hasLockTime() {\n return ((bitField0_ & 0x00000008) == 0x00000008);\n }\n /**\n * <code>optional uint32 lock_time = 4;</code>\n *\n * <pre>\n * The nLockTime field is useful for contracts.\n * </pre>\n */\n public int getLockTime() {\n return lockTime_;\n }\n\n // optional int64 updated_at = 5;\n public static final int UPDATED_AT_FIELD_NUMBER = 5;\n private long updatedAt_;\n /**\n * <code>optional int64 updated_at = 5;</code>\n *\n * <pre>\n * millis since epoch the transaction was last updated\n * </pre>\n */\n public boolean hasUpdatedAt() {\n return ((bitField0_ & 0x00000010) == 0x00000010);\n }\n /**\n * <code>optional int64 updated_at = 5;</code>\n *\n * <pre>\n * millis since epoch the transaction was last updated\n * </pre>\n */\n public long getUpdatedAt() {\n return updatedAt_;\n }\n\n // repeated .wallet.TransactionInput transaction_input = 6;\n public static final int TRANSACTION_INPUT_FIELD_NUMBER = 6;\n private java.util.List<org.bitcoinj.wallet.Protos.TransactionInput> transactionInput_;\n /**\n * <code>repeated .wallet.TransactionInput transaction_input = 6;</code>\n */\n public java.util.List<org.bitcoinj.wallet.Protos.TransactionInput> getTransactionInputList() {\n return transactionInput_;\n }\n /**\n * <code>repeated .wallet.TransactionInput transaction_input = 6;</code>\n */\n public java.util.List<? extends org.bitcoinj.wallet.Protos.TransactionInputOrBuilder> \n getTransactionInputOrBuilderList() {\n return transactionInput_;\n }\n /**\n * <code>repeated .wallet.TransactionInput transaction_input = 6;</code>\n */\n public int getTransactionInputCount() {\n return transactionInput_.size();\n }\n /**\n * <code>repeated .wallet.TransactionInput transaction_input = 6;</code>\n */\n public org.bitcoinj.wallet.Protos.TransactionInput getTransactionInput(int index) {\n return transactionInput_.get(index);\n }\n /**\n * <code>repeated .wallet.TransactionInput transaction_input = 6;</code>\n */\n public org.bitcoinj.wallet.Protos.TransactionInputOrBuilder getTransactionInputOrBuilder(\n int index) {\n return transactionInput_.get(index);\n }\n\n // repeated .wallet.TransactionOutput transaction_output = 7;\n public static final int TRANSACTION_OUTPUT_FIELD_NUMBER = 7;\n private java.util.List<org.bitcoinj.wallet.Protos.TransactionOutput> transactionOutput_;\n /**\n * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code>\n */\n public java.util.List<org.bitcoinj.wallet.Protos.TransactionOutput> getTransactionOutputList() {\n return transactionOutput_;\n }\n /**\n * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code>\n */\n public java.util.List<? extends org.bitcoinj.wallet.Protos.TransactionOutputOrBuilder> \n getTransactionOutputOrBuilderList() {\n return transactionOutput_;\n }\n /**\n * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code>\n */\n public int getTransactionOutputCount() {\n return transactionOutput_.size();\n }\n /**\n * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code>\n */\n public org.bitcoinj.wallet.Protos.TransactionOutput getTransactionOutput(int index) {\n return transactionOutput_.get(index);\n }\n /**\n * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code>\n */\n public org.bitcoinj.wallet.Protos.TransactionOutputOrBuilder getTransactionOutputOrBuilder(\n int index) {\n return transactionOutput_.get(index);\n }\n\n // repeated bytes block_hash = 8;\n public static final int BLOCK_HASH_FIELD_NUMBER = 8;\n private java.util.List<com.google.protobuf.ByteString> blockHash_;\n /**\n * <code>repeated bytes block_hash = 8;</code>\n *\n * <pre>\n * A list of blocks in which the transaction has been observed (on any chain). Also, a number used to disambiguate\n * ordering within a block.\n * </pre>\n */\n public java.util.List<com.google.protobuf.ByteString>\n getBlockHashList() {\n return blockHash_;\n }\n /**\n * <code>repeated bytes block_hash = 8;</code>\n *\n * <pre>\n * A list of blocks in which the transaction has been observed (on any chain). Also, a number used to disambiguate\n * ordering within a block.\n * </pre>\n */\n public int getBlockHashCount() {\n return blockHash_.size();\n }\n /**\n * <code>repeated bytes block_hash = 8;</code>\n *\n * <pre>\n * A list of blocks in which the transaction has been observed (on any chain). Also, a number used to disambiguate\n * ordering within a block.\n * </pre>\n */\n public com.google.protobuf.ByteString getBlockHash(int index) {\n return blockHash_.get(index);\n }\n\n // repeated int32 block_relativity_offsets = 11;\n public static final int BLOCK_RELATIVITY_OFFSETS_FIELD_NUMBER = 11;\n private java.util.List<java.lang.Integer> blockRelativityOffsets_;\n /**\n * <code>repeated int32 block_relativity_offsets = 11;</code>\n */\n public java.util.List<java.lang.Integer>\n getBlockRelativityOffsetsList() {\n return blockRelativityOffsets_;\n }\n /**\n * <code>repeated int32 block_relativity_offsets = 11;</code>\n */\n public int getBlockRelativityOffsetsCount() {\n return blockRelativityOffsets_.size();\n }\n /**\n * <code>repeated int32 block_relativity_offsets = 11;</code>\n */\n public int getBlockRelativityOffsets(int index) {\n return blockRelativityOffsets_.get(index);\n }\n\n // optional .wallet.TransactionConfidence confidence = 9;\n public static final int CONFIDENCE_FIELD_NUMBER = 9;\n private org.bitcoinj.wallet.Protos.TransactionConfidence confidence_;\n /**\n * <code>optional .wallet.TransactionConfidence confidence = 9;</code>\n *\n * <pre>\n * Data describing where the transaction is in the chain.\n * </pre>\n */\n public boolean hasConfidence() {\n return ((bitField0_ & 0x00000020) == 0x00000020);\n }\n /**\n * <code>optional .wallet.TransactionConfidence confidence = 9;</code>\n *\n * <pre>\n * Data describing where the transaction is in the chain.\n * </pre>\n */\n public org.bitcoinj.wallet.Protos.TransactionConfidence getConfidence() {\n return confidence_;\n }\n /**\n * <code>optional .wallet.TransactionConfidence confidence = 9;</code>\n *\n * <pre>\n * Data describing where the transaction is in the chain.\n * </pre>\n */\n public org.bitcoinj.wallet.Protos.TransactionConfidenceOrBuilder getConfidenceOrBuilder() {\n return confidence_;\n }\n\n // optional .wallet.Transaction.Purpose purpose = 10 [default = UNKNOWN];\n public static final int PURPOSE_FIELD_NUMBER = 10;\n private org.bitcoinj.wallet.Protos.Transaction.Purpose purpose_;\n /**\n * <code>optional .wallet.Transaction.Purpose purpose = 10 [default = UNKNOWN];</code>\n */\n public boolean hasPurpose() {\n return ((bitField0_ & 0x00000040) == 0x00000040);\n }\n /**\n * <code>optional .wallet.Transaction.Purpose purpose = 10 [default = UNKNOWN];</code>\n */\n public org.bitcoinj.wallet.Protos.Transaction.Purpose getPurpose() {\n return purpose_;\n }\n\n private void initFields() {\n version_ = 0;\n hash_ = com.google.protobuf.ByteString.EMPTY;\n pool_ = org.bitcoinj.wallet.Protos.Transaction.Pool.UNSPENT;\n lockTime_ = 0;\n updatedAt_ = 0L;\n transactionInput_ = java.util.Collections.emptyList();\n transactionOutput_ = java.util.Collections.emptyList();\n blockHash_ = java.util.Collections.emptyList();\n blockRelativityOffsets_ = java.util.Collections.emptyList();\n confidence_ = org.bitcoinj.wallet.Protos.TransactionConfidence.getDefaultInstance();\n purpose_ = org.bitcoinj.wallet.Protos.Transaction.Purpose.UNKNOWN;\n }\n private byte memoizedIsInitialized = -1;\n public final boolean isInitialized() {\n byte isInitialized = memoizedIsInitialized;\n if (isInitialized != -1) return isInitialized == 1;\n\n if (!hasVersion()) {\n memoizedIsInitialized = 0;\n return false;\n }\n if (!hasHash()) {\n memoizedIsInitialized = 0;\n return false;\n }\n for (int i = 0; i < getTransactionInputCount(); i++) {\n if (!getTransactionInput(i).isInitialized()) {\n memoizedIsInitialized = 0;\n return false;\n }\n }\n for (int i = 0; i < getTransactionOutputCount(); i++) {\n if (!getTransactionOutput(i).isInitialized()) {\n memoizedIsInitialized = 0;\n return false;\n }\n }\n if (hasConfidence()) {\n if (!getConfidence().isInitialized()) {\n memoizedIsInitialized = 0;\n return false;\n }\n }\n memoizedIsInitialized = 1;\n return true;\n }\n\n public void writeTo(com.google.protobuf.CodedOutputStream output)\n throws java.io.IOException {\n getSerializedSize();\n if (((bitField0_ & 0x00000001) == 0x00000001)) {\n output.writeInt32(1, version_);\n }\n if (((bitField0_ & 0x00000002) == 0x00000002)) {\n output.writeBytes(2, hash_);\n }\n if (((bitField0_ & 0x00000004) == 0x00000004)) {\n output.writeEnum(3, pool_.getNumber());\n }\n if (((bitField0_ & 0x00000008) == 0x00000008)) {\n output.writeUInt32(4, lockTime_);\n }\n if (((bitField0_ & 0x00000010) == 0x00000010)) {\n output.writeInt64(5, updatedAt_);\n }\n for (int i = 0; i < transactionInput_.size(); i++) {\n output.writeMessage(6, transactionInput_.get(i));\n }\n for (int i = 0; i < transactionOutput_.size(); i++) {\n output.writeMessage(7, transactionOutput_.get(i));\n }\n for (int i = 0; i < blockHash_.size(); i++) {\n output.writeBytes(8, blockHash_.get(i));\n }\n if (((bitField0_ & 0x00000020) == 0x00000020)) {\n output.writeMessage(9, confidence_);\n }\n if (((bitField0_ & 0x00000040) == 0x00000040)) {\n output.writeEnum(10, purpose_.getNumber());\n }\n for (int i = 0; i < blockRelativityOffsets_.size(); i++) {\n output.writeInt32(11, blockRelativityOffsets_.get(i));\n }\n getUnknownFields().writeTo(output);\n }\n\n private int memoizedSerializedSize = -1;\n public int getSerializedSize() {\n int size = memoizedSerializedSize;\n if (size != -1) return size;\n\n size = 0;\n if (((bitField0_ & 0x00000001) == 0x00000001)) {\n size += com.google.protobuf.CodedOutputStream\n .computeInt32Size(1, version_);\n }\n if (((bitField0_ & 0x00000002) == 0x00000002)) {\n size += com.google.protobuf.CodedOutputStream\n .computeBytesSize(2, hash_);\n }\n if (((bitField0_ & 0x00000004) == 0x00000004)) {\n size += com.google.protobuf.CodedOutputStream\n .computeEnumSize(3, pool_.getNumber());\n }\n if (((bitField0_ & 0x00000008) == 0x00000008)) {\n size += com.google.protobuf.CodedOutputStream\n .computeUInt32Size(4, lockTime_);\n }\n if (((bitField0_ & 0x00000010) == 0x00000010)) {\n size += com.google.protobuf.CodedOutputStream\n .computeInt64Size(5, updatedAt_);\n }\n for (int i = 0; i < transactionInput_.size(); i++) {\n size += com.google.protobuf.CodedOutputStream\n .computeMessageSize(6, transactionInput_.get(i));\n }\n for (int i = 0; i < transactionOutput_.size(); i++) {\n size += com.google.protobuf.CodedOutputStream\n .computeMessageSize(7, transactionOutput_.get(i));\n }\n {\n int dataSize = 0;\n for (int i = 0; i < blockHash_.size(); i++) {\n dataSize += com.google.protobuf.CodedOutputStream\n .computeBytesSizeNoTag(blockHash_.get(i));\n }\n size += dataSize;\n size += 1 * getBlockHashList().size();\n }\n if (((bitField0_ & 0x00000020) == 0x00000020)) {\n size += com.google.protobuf.CodedOutputStream\n .computeMessageSize(9, confidence_);\n }\n if (((bitField0_ & 0x00000040) == 0x00000040)) {\n size += com.google.protobuf.CodedOutputStream\n .computeEnumSize(10, purpose_.getNumber());\n }\n {\n int dataSize = 0;\n for (int i = 0; i < blockRelativityOffsets_.size(); i++) {\n dataSize += com.google.protobuf.CodedOutputStream\n .computeInt32SizeNoTag(blockRelativityOffsets_.get(i));\n }\n size += dataSize;\n size += 1 * getBlockRelativityOffsetsList().size();\n }\n size += getUnknownFields().getSerializedSize();\n memoizedSerializedSize = size;\n return size;\n }\n\n private static final long serialVersionUID = 0L;\n @java.lang.Override\n protected java.lang.Object writeReplace()\n throws java.io.ObjectStreamException {\n return super.writeReplace();\n }\n\n public static org.bitcoinj.wallet.Protos.Transaction parseFrom(\n com.google.protobuf.ByteString data)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n public static org.bitcoinj.wallet.Protos.Transaction parseFrom(\n com.google.protobuf.ByteString data,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n public static org.bitcoinj.wallet.Protos.Transaction parseFrom(byte[] data)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n public static org.bitcoinj.wallet.Protos.Transaction parseFrom(\n byte[] data,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n public static org.bitcoinj.wallet.Protos.Transaction parseFrom(java.io.InputStream input)\n throws java.io.IOException {\n return PARSER.parseFrom(input);\n }\n public static org.bitcoinj.wallet.Protos.Transaction parseFrom(\n java.io.InputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return PARSER.parseFrom(input, extensionRegistry);\n }\n public static org.bitcoinj.wallet.Protos.Transaction parseDelimitedFrom(java.io.InputStream input)\n throws java.io.IOException {\n return PARSER.parseDelimitedFrom(input);\n }\n public static org.bitcoinj.wallet.Protos.Transaction parseDelimitedFrom(\n java.io.InputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return PARSER.parseDelimitedFrom(input, extensionRegistry);\n }\n public static org.bitcoinj.wallet.Protos.Transaction parseFrom(\n com.google.protobuf.CodedInputStream input)\n throws java.io.IOException {\n return PARSER.parseFrom(input);\n }\n public static org.bitcoinj.wallet.Protos.Transaction parseFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return PARSER.parseFrom(input, extensionRegistry);\n }\n\n public static Builder newBuilder() { return Builder.create(); }\n public Builder newBuilderForType() { return newBuilder(); }\n public static Builder newBuilder(org.bitcoinj.wallet.Protos.Transaction prototype) {\n return newBuilder().mergeFrom(prototype);\n }\n public Builder toBuilder() { return newBuilder(this); }\n\n @java.lang.Override\n protected Builder newBuilderForType(\n com.google.protobuf.GeneratedMessage.BuilderParent parent) {\n Builder builder = new Builder(parent);\n return builder;\n }\n /**\n * Protobuf type {@code wallet.Transaction}\n */\n public static final class Builder extends\n com.google.protobuf.GeneratedMessage.Builder<Builder>\n implements org.bitcoinj.wallet.Protos.TransactionOrBuilder {\n public static final com.google.protobuf.Descriptors.Descriptor\n getDescriptor() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_Transaction_descriptor;\n }\n\n protected com.google.protobuf.GeneratedMessage.FieldAccessorTable\n internalGetFieldAccessorTable() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_Transaction_fieldAccessorTable\n .ensureFieldAccessorsInitialized(\n org.bitcoinj.wallet.Protos.Transaction.class, org.bitcoinj.wallet.Protos.Transaction.Builder.class);\n }\n\n // Construct using org.bitcoinj.wallet.Protos.Transaction.newBuilder()\n private Builder() {\n maybeForceBuilderInitialization();\n }\n\n private Builder(\n com.google.protobuf.GeneratedMessage.BuilderParent parent) {\n super(parent);\n maybeForceBuilderInitialization();\n }\n private void maybeForceBuilderInitialization() {\n if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {\n getTransactionInputFieldBuilder();\n getTransactionOutputFieldBuilder();\n getConfidenceFieldBuilder();\n }\n }\n private static Builder create() {\n return new Builder();\n }\n\n public Builder clear() {\n super.clear();\n version_ = 0;\n bitField0_ = (bitField0_ & ~0x00000001);\n hash_ = com.google.protobuf.ByteString.EMPTY;\n bitField0_ = (bitField0_ & ~0x00000002);\n pool_ = org.bitcoinj.wallet.Protos.Transaction.Pool.UNSPENT;\n bitField0_ = (bitField0_ & ~0x00000004);\n lockTime_ = 0;\n bitField0_ = (bitField0_ & ~0x00000008);\n updatedAt_ = 0L;\n bitField0_ = (bitField0_ & ~0x00000010);\n if (transactionInputBuilder_ == null) {\n transactionInput_ = java.util.Collections.emptyList();\n bitField0_ = (bitField0_ & ~0x00000020);\n } else {\n transactionInputBuilder_.clear();\n }\n if (transactionOutputBuilder_ == null) {\n transactionOutput_ = java.util.Collections.emptyList();\n bitField0_ = (bitField0_ & ~0x00000040);\n } else {\n transactionOutputBuilder_.clear();\n }\n blockHash_ = java.util.Collections.emptyList();\n bitField0_ = (bitField0_ & ~0x00000080);\n blockRelativityOffsets_ = java.util.Collections.emptyList();\n bitField0_ = (bitField0_ & ~0x00000100);\n if (confidenceBuilder_ == null) {\n confidence_ = org.bitcoinj.wallet.Protos.TransactionConfidence.getDefaultInstance();\n } else {\n confidenceBuilder_.clear();\n }\n bitField0_ = (bitField0_ & ~0x00000200);\n purpose_ = org.bitcoinj.wallet.Protos.Transaction.Purpose.UNKNOWN;\n bitField0_ = (bitField0_ & ~0x00000400);\n return this;\n }\n\n public Builder clone() {\n return create().mergeFrom(buildPartial());\n }\n\n public com.google.protobuf.Descriptors.Descriptor\n getDescriptorForType() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_Transaction_descriptor;\n }\n\n public org.bitcoinj.wallet.Protos.Transaction getDefaultInstanceForType() {\n return org.bitcoinj.wallet.Protos.Transaction.getDefaultInstance();\n }\n\n public org.bitcoinj.wallet.Protos.Transaction build() {\n org.bitcoinj.wallet.Protos.Transaction result = buildPartial();\n if (!result.isInitialized()) {\n throw newUninitializedMessageException(result);\n }\n return result;\n }\n\n public org.bitcoinj.wallet.Protos.Transaction buildPartial() {\n org.bitcoinj.wallet.Protos.Transaction result = new org.bitcoinj.wallet.Protos.Transaction(this);\n int from_bitField0_ = bitField0_;\n int to_bitField0_ = 0;\n if (((from_bitField0_ & 0x00000001) == 0x00000001)) {\n to_bitField0_ |= 0x00000001;\n }\n result.version_ = version_;\n if (((from_bitField0_ & 0x00000002) == 0x00000002)) {\n to_bitField0_ |= 0x00000002;\n }\n result.hash_ = hash_;\n if (((from_bitField0_ & 0x00000004) == 0x00000004)) {\n to_bitField0_ |= 0x00000004;\n }\n result.pool_ = pool_;\n if (((from_bitField0_ & 0x00000008) == 0x00000008)) {\n to_bitField0_ |= 0x00000008;\n }\n result.lockTime_ = lockTime_;\n if (((from_bitField0_ & 0x00000010) == 0x00000010)) {\n to_bitField0_ |= 0x00000010;\n }\n result.updatedAt_ = updatedAt_;\n if (transactionInputBuilder_ == null) {\n if (((bitField0_ & 0x00000020) == 0x00000020)) {\n transactionInput_ = java.util.Collections.unmodifiableList(transactionInput_);\n bitField0_ = (bitField0_ & ~0x00000020);\n }\n result.transactionInput_ = transactionInput_;\n } else {\n result.transactionInput_ = transactionInputBuilder_.build();\n }\n if (transactionOutputBuilder_ == null) {\n if (((bitField0_ & 0x00000040) == 0x00000040)) {\n transactionOutput_ = java.util.Collections.unmodifiableList(transactionOutput_);\n bitField0_ = (bitField0_ & ~0x00000040);\n }\n result.transactionOutput_ = transactionOutput_;\n } else {\n result.transactionOutput_ = transactionOutputBuilder_.build();\n }\n if (((bitField0_ & 0x00000080) == 0x00000080)) {\n blockHash_ = java.util.Collections.unmodifiableList(blockHash_);\n bitField0_ = (bitField0_ & ~0x00000080);\n }\n result.blockHash_ = blockHash_;\n if (((bitField0_ & 0x00000100) == 0x00000100)) {\n blockRelativityOffsets_ = java.util.Collections.unmodifiableList(blockRelativityOffsets_);\n bitField0_ = (bitField0_ & ~0x00000100);\n }\n result.blockRelativityOffsets_ = blockRelativityOffsets_;\n if (((from_bitField0_ & 0x00000200) == 0x00000200)) {\n to_bitField0_ |= 0x00000020;\n }\n if (confidenceBuilder_ == null) {\n result.confidence_ = confidence_;\n } else {\n result.confidence_ = confidenceBuilder_.build();\n }\n if (((from_bitField0_ & 0x00000400) == 0x00000400)) {\n to_bitField0_ |= 0x00000040;\n }\n result.purpose_ = purpose_;\n result.bitField0_ = to_bitField0_;\n onBuilt();\n return result;\n }\n\n public Builder mergeFrom(com.google.protobuf.Message other) {\n if (other instanceof org.bitcoinj.wallet.Protos.Transaction) {\n return mergeFrom((org.bitcoinj.wallet.Protos.Transaction)other);\n } else {\n super.mergeFrom(other);\n return this;\n }\n }\n\n public Builder mergeFrom(org.bitcoinj.wallet.Protos.Transaction other) {\n if (other == org.bitcoinj.wallet.Protos.Transaction.getDefaultInstance()) return this;\n if (other.hasVersion()) {\n setVersion(other.getVersion());\n }\n if (other.hasHash()) {\n setHash(other.getHash());\n }\n if (other.hasPool()) {\n setPool(other.getPool());\n }\n if (other.hasLockTime()) {\n setLockTime(other.getLockTime());\n }\n if (other.hasUpdatedAt()) {\n setUpdatedAt(other.getUpdatedAt());\n }\n if (transactionInputBuilder_ == null) {\n if (!other.transactionInput_.isEmpty()) {\n if (transactionInput_.isEmpty()) {\n transactionInput_ = other.transactionInput_;\n bitField0_ = (bitField0_ & ~0x00000020);\n } else {\n ensureTransactionInputIsMutable();\n transactionInput_.addAll(other.transactionInput_);\n }\n onChanged();\n }\n } else {\n if (!other.transactionInput_.isEmpty()) {\n if (transactionInputBuilder_.isEmpty()) {\n transactionInputBuilder_.dispose();\n transactionInputBuilder_ = null;\n transactionInput_ = other.transactionInput_;\n bitField0_ = (bitField0_ & ~0x00000020);\n transactionInputBuilder_ = \n com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ?\n getTransactionInputFieldBuilder() : null;\n } else {\n transactionInputBuilder_.addAllMessages(other.transactionInput_);\n }\n }\n }\n if (transactionOutputBuilder_ == null) {\n if (!other.transactionOutput_.isEmpty()) {\n if (transactionOutput_.isEmpty()) {\n transactionOutput_ = other.transactionOutput_;\n bitField0_ = (bitField0_ & ~0x00000040);\n } else {\n ensureTransactionOutputIsMutable();\n transactionOutput_.addAll(other.transactionOutput_);\n }\n onChanged();\n }\n } else {\n if (!other.transactionOutput_.isEmpty()) {\n if (transactionOutputBuilder_.isEmpty()) {\n transactionOutputBuilder_.dispose();\n transactionOutputBuilder_ = null;\n transactionOutput_ = other.transactionOutput_;\n bitField0_ = (bitField0_ & ~0x00000040);\n transactionOutputBuilder_ = \n com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ?\n getTransactionOutputFieldBuilder() : null;\n } else {\n transactionOutputBuilder_.addAllMessages(other.transactionOutput_);\n }\n }\n }\n if (!other.blockHash_.isEmpty()) {\n if (blockHash_.isEmpty()) {\n blockHash_ = other.blockHash_;\n bitField0_ = (bitField0_ & ~0x00000080);\n } else {\n ensureBlockHashIsMutable();\n blockHash_.addAll(other.blockHash_);\n }\n onChanged();\n }\n if (!other.blockRelativityOffsets_.isEmpty()) {\n if (blockRelativityOffsets_.isEmpty()) {\n blockRelativityOffsets_ = other.blockRelativityOffsets_;\n bitField0_ = (bitField0_ & ~0x00000100);\n } else {\n ensureBlockRelativityOffsetsIsMutable();\n blockRelativityOffsets_.addAll(other.blockRelativityOffsets_);\n }\n onChanged();\n }\n if (other.hasConfidence()) {\n mergeConfidence(other.getConfidence());\n }\n if (other.hasPurpose()) {\n setPurpose(other.getPurpose());\n }\n this.mergeUnknownFields(other.getUnknownFields());\n return this;\n }\n\n public final boolean isInitialized() {\n if (!hasVersion()) {\n \n return false;\n }\n if (!hasHash()) {\n \n return false;\n }\n for (int i = 0; i < getTransactionInputCount(); i++) {\n if (!getTransactionInput(i).isInitialized()) {\n \n return false;\n }\n }\n for (int i = 0; i < getTransactionOutputCount(); i++) {\n if (!getTransactionOutput(i).isInitialized()) {\n \n return false;\n }\n }\n if (hasConfidence()) {\n if (!getConfidence().isInitialized()) {\n \n return false;\n }\n }\n return true;\n }\n\n public Builder mergeFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n org.bitcoinj.wallet.Protos.Transaction parsedMessage = null;\n try {\n parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);\n } catch (com.google.protobuf.InvalidProtocolBufferException e) {\n parsedMessage = (org.bitcoinj.wallet.Protos.Transaction) e.getUnfinishedMessage();\n throw e;\n } finally {\n if (parsedMessage != null) {\n mergeFrom(parsedMessage);\n }\n }\n return this;\n }\n private int bitField0_;\n\n // required int32 version = 1;\n private int version_ ;\n /**\n * <code>required int32 version = 1;</code>\n *\n * <pre>\n * See Wallet.java for detailed description of pool semantics\n * </pre>\n */\n public boolean hasVersion() {\n return ((bitField0_ & 0x00000001) == 0x00000001);\n }\n /**\n * <code>required int32 version = 1;</code>\n *\n * <pre>\n * See Wallet.java for detailed description of pool semantics\n * </pre>\n */\n public int getVersion() {\n return version_;\n }\n /**\n * <code>required int32 version = 1;</code>\n *\n * <pre>\n * See Wallet.java for detailed description of pool semantics\n * </pre>\n */\n public Builder setVersion(int value) {\n bitField0_ |= 0x00000001;\n version_ = value;\n onChanged();\n return this;\n }\n /**\n * <code>required int32 version = 1;</code>\n *\n * <pre>\n * See Wallet.java for detailed description of pool semantics\n * </pre>\n */\n public Builder clearVersion() {\n bitField0_ = (bitField0_ & ~0x00000001);\n version_ = 0;\n onChanged();\n return this;\n }\n\n // required bytes hash = 2;\n private com.google.protobuf.ByteString hash_ = com.google.protobuf.ByteString.EMPTY;\n /**\n * <code>required bytes hash = 2;</code>\n */\n public boolean hasHash() {\n return ((bitField0_ & 0x00000002) == 0x00000002);\n }\n /**\n * <code>required bytes hash = 2;</code>\n */\n public com.google.protobuf.ByteString getHash() {\n return hash_;\n }\n /**\n * <code>required bytes hash = 2;</code>\n */\n public Builder setHash(com.google.protobuf.ByteString value) {\n if (value == null) {\n throw new NullPointerException();\n }\n bitField0_ |= 0x00000002;\n hash_ = value;\n onChanged();\n return this;\n }\n /**\n * <code>required bytes hash = 2;</code>\n */\n public Builder clearHash() {\n bitField0_ = (bitField0_ & ~0x00000002);\n hash_ = getDefaultInstance().getHash();\n onChanged();\n return this;\n }\n\n // optional .wallet.Transaction.Pool pool = 3;\n private org.bitcoinj.wallet.Protos.Transaction.Pool pool_ = org.bitcoinj.wallet.Protos.Transaction.Pool.UNSPENT;\n /**\n * <code>optional .wallet.Transaction.Pool pool = 3;</code>\n *\n * <pre>\n * If pool is not present, that means either:\n * - This Transaction is either not in a wallet at all (the proto is re-used elsewhere)\n * - Or it is stored but for other purposes, for example, because it is the overriding transaction of a double spend.\n * - Or the Pool enum got a new value which your software is too old to parse.\n * </pre>\n */\n public boolean hasPool() {\n return ((bitField0_ & 0x00000004) == 0x00000004);\n }\n /**\n * <code>optional .wallet.Transaction.Pool pool = 3;</code>\n *\n * <pre>\n * If pool is not present, that means either:\n * - This Transaction is either not in a wallet at all (the proto is re-used elsewhere)\n * - Or it is stored but for other purposes, for example, because it is the overriding transaction of a double spend.\n * - Or the Pool enum got a new value which your software is too old to parse.\n * </pre>\n */\n public org.bitcoinj.wallet.Protos.Transaction.Pool getPool() {\n return pool_;\n }\n /**\n * <code>optional .wallet.Transaction.Pool pool = 3;</code>\n *\n * <pre>\n * If pool is not present, that means either:\n * - This Transaction is either not in a wallet at all (the proto is re-used elsewhere)\n * - Or it is stored but for other purposes, for example, because it is the overriding transaction of a double spend.\n * - Or the Pool enum got a new value which your software is too old to parse.\n * </pre>\n */\n public Builder setPool(org.bitcoinj.wallet.Protos.Transaction.Pool value) {\n if (value == null) {\n throw new NullPointerException();\n }\n bitField0_ |= 0x00000004;\n pool_ = value;\n onChanged();\n return this;\n }\n /**\n * <code>optional .wallet.Transaction.Pool pool = 3;</code>\n *\n * <pre>\n * If pool is not present, that means either:\n * - This Transaction is either not in a wallet at all (the proto is re-used elsewhere)\n * - Or it is stored but for other purposes, for example, because it is the overriding transaction of a double spend.\n * - Or the Pool enum got a new value which your software is too old to parse.\n * </pre>\n */\n public Builder clearPool() {\n bitField0_ = (bitField0_ & ~0x00000004);\n pool_ = org.bitcoinj.wallet.Protos.Transaction.Pool.UNSPENT;\n onChanged();\n return this;\n }\n\n // optional uint32 lock_time = 4;\n private int lockTime_ ;\n /**\n * <code>optional uint32 lock_time = 4;</code>\n *\n * <pre>\n * The nLockTime field is useful for contracts.\n * </pre>\n */\n public boolean hasLockTime() {\n return ((bitField0_ & 0x00000008) == 0x00000008);\n }\n /**\n * <code>optional uint32 lock_time = 4;</code>\n *\n * <pre>\n * The nLockTime field is useful for contracts.\n * </pre>\n */\n public int getLockTime() {\n return lockTime_;\n }\n /**\n * <code>optional uint32 lock_time = 4;</code>\n *\n * <pre>\n * The nLockTime field is useful for contracts.\n * </pre>\n */\n public Builder setLockTime(int value) {\n bitField0_ |= 0x00000008;\n lockTime_ = value;\n onChanged();\n return this;\n }\n /**\n * <code>optional uint32 lock_time = 4;</code>\n *\n * <pre>\n * The nLockTime field is useful for contracts.\n * </pre>\n */\n public Builder clearLockTime() {\n bitField0_ = (bitField0_ & ~0x00000008);\n lockTime_ = 0;\n onChanged();\n return this;\n }\n\n // optional int64 updated_at = 5;\n private long updatedAt_ ;\n /**\n * <code>optional int64 updated_at = 5;</code>\n *\n * <pre>\n * millis since epoch the transaction was last updated\n * </pre>\n */\n public boolean hasUpdatedAt() {\n return ((bitField0_ & 0x00000010) == 0x00000010);\n }\n /**\n * <code>optional int64 updated_at = 5;</code>\n *\n * <pre>\n * millis since epoch the transaction was last updated\n * </pre>\n */\n public long getUpdatedAt() {\n return updatedAt_;\n }\n /**\n * <code>optional int64 updated_at = 5;</code>\n *\n * <pre>\n * millis since epoch the transaction was last updated\n * </pre>\n */\n public Builder setUpdatedAt(long value) {\n bitField0_ |= 0x00000010;\n updatedAt_ = value;\n onChanged();\n return this;\n }\n /**\n * <code>optional int64 updated_at = 5;</code>\n *\n * <pre>\n * millis since epoch the transaction was last updated\n * </pre>\n */\n public Builder clearUpdatedAt() {\n bitField0_ = (bitField0_ & ~0x00000010);\n updatedAt_ = 0L;\n onChanged();\n return this;\n }\n\n // repeated .wallet.TransactionInput transaction_input = 6;\n private java.util.List<org.bitcoinj.wallet.Protos.TransactionInput> transactionInput_ =\n java.util.Collections.emptyList();\n private void ensureTransactionInputIsMutable() {\n if (!((bitField0_ & 0x00000020) == 0x00000020)) {\n transactionInput_ = new java.util.ArrayList<org.bitcoinj.wallet.Protos.TransactionInput>(transactionInput_);\n bitField0_ |= 0x00000020;\n }\n }\n\n private com.google.protobuf.RepeatedFieldBuilder<\n org.bitcoinj.wallet.Protos.TransactionInput, org.bitcoinj.wallet.Protos.TransactionInput.Builder, org.bitcoinj.wallet.Protos.TransactionInputOrBuilder> transactionInputBuilder_;\n\n /**\n * <code>repeated .wallet.TransactionInput transaction_input = 6;</code>\n */\n public java.util.List<org.bitcoinj.wallet.Protos.TransactionInput> getTransactionInputList() {\n if (transactionInputBuilder_ == null) {\n return java.util.Collections.unmodifiableList(transactionInput_);\n } else {\n return transactionInputBuilder_.getMessageList();\n }\n }\n /**\n * <code>repeated .wallet.TransactionInput transaction_input = 6;</code>\n */\n public int getTransactionInputCount() {\n if (transactionInputBuilder_ == null) {\n return transactionInput_.size();\n } else {\n return transactionInputBuilder_.getCount();\n }\n }\n /**\n * <code>repeated .wallet.TransactionInput transaction_input = 6;</code>\n */\n public org.bitcoinj.wallet.Protos.TransactionInput getTransactionInput(int index) {\n if (transactionInputBuilder_ == null) {\n return transactionInput_.get(index);\n } else {\n return transactionInputBuilder_.getMessage(index);\n }\n }\n /**\n * <code>repeated .wallet.TransactionInput transaction_input = 6;</code>\n */\n public Builder setTransactionInput(\n int index, org.bitcoinj.wallet.Protos.TransactionInput value) {\n if (transactionInputBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureTransactionInputIsMutable();\n transactionInput_.set(index, value);\n onChanged();\n } else {\n transactionInputBuilder_.setMessage(index, value);\n }\n return this;\n }\n /**\n * <code>repeated .wallet.TransactionInput transaction_input = 6;</code>\n */\n public Builder setTransactionInput(\n int index, org.bitcoinj.wallet.Protos.TransactionInput.Builder builderForValue) {\n if (transactionInputBuilder_ == null) {\n ensureTransactionInputIsMutable();\n transactionInput_.set(index, builderForValue.build());\n onChanged();\n } else {\n transactionInputBuilder_.setMessage(index, builderForValue.build());\n }\n return this;\n }\n /**\n * <code>repeated .wallet.TransactionInput transaction_input = 6;</code>\n */\n public Builder addTransactionInput(org.bitcoinj.wallet.Protos.TransactionInput value) {\n if (transactionInputBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureTransactionInputIsMutable();\n transactionInput_.add(value);\n onChanged();\n } else {\n transactionInputBuilder_.addMessage(value);\n }\n return this;\n }\n /**\n * <code>repeated .wallet.TransactionInput transaction_input = 6;</code>\n */\n public Builder addTransactionInput(\n int index, org.bitcoinj.wallet.Protos.TransactionInput value) {\n if (transactionInputBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureTransactionInputIsMutable();\n transactionInput_.add(index, value);\n onChanged();\n } else {\n transactionInputBuilder_.addMessage(index, value);\n }\n return this;\n }\n /**\n * <code>repeated .wallet.TransactionInput transaction_input = 6;</code>\n */\n public Builder addTransactionInput(\n org.bitcoinj.wallet.Protos.TransactionInput.Builder builderForValue) {\n if (transactionInputBuilder_ == null) {\n ensureTransactionInputIsMutable();\n transactionInput_.add(builderForValue.build());\n onChanged();\n } else {\n transactionInputBuilder_.addMessage(builderForValue.build());\n }\n return this;\n }\n /**\n * <code>repeated .wallet.TransactionInput transaction_input = 6;</code>\n */\n public Builder addTransactionInput(\n int index, org.bitcoinj.wallet.Protos.TransactionInput.Builder builderForValue) {\n if (transactionInputBuilder_ == null) {\n ensureTransactionInputIsMutable();\n transactionInput_.add(index, builderForValue.build());\n onChanged();\n } else {\n transactionInputBuilder_.addMessage(index, builderForValue.build());\n }\n return this;\n }\n /**\n * <code>repeated .wallet.TransactionInput transaction_input = 6;</code>\n */\n public Builder addAllTransactionInput(\n java.lang.Iterable<? extends org.bitcoinj.wallet.Protos.TransactionInput> values) {\n if (transactionInputBuilder_ == null) {\n ensureTransactionInputIsMutable();\n super.addAll(values, transactionInput_);\n onChanged();\n } else {\n transactionInputBuilder_.addAllMessages(values);\n }\n return this;\n }\n /**\n * <code>repeated .wallet.TransactionInput transaction_input = 6;</code>\n */\n public Builder clearTransactionInput() {\n if (transactionInputBuilder_ == null) {\n transactionInput_ = java.util.Collections.emptyList();\n bitField0_ = (bitField0_ & ~0x00000020);\n onChanged();\n } else {\n transactionInputBuilder_.clear();\n }\n return this;\n }\n /**\n * <code>repeated .wallet.TransactionInput transaction_input = 6;</code>\n */\n public Builder removeTransactionInput(int index) {\n if (transactionInputBuilder_ == null) {\n ensureTransactionInputIsMutable();\n transactionInput_.remove(index);\n onChanged();\n } else {\n transactionInputBuilder_.remove(index);\n }\n return this;\n }\n /**\n * <code>repeated .wallet.TransactionInput transaction_input = 6;</code>\n */\n public org.bitcoinj.wallet.Protos.TransactionInput.Builder getTransactionInputBuilder(\n int index) {\n return getTransactionInputFieldBuilder().getBuilder(index);\n }\n /**\n * <code>repeated .wallet.TransactionInput transaction_input = 6;</code>\n */\n public org.bitcoinj.wallet.Protos.TransactionInputOrBuilder getTransactionInputOrBuilder(\n int index) {\n if (transactionInputBuilder_ == null) {\n return transactionInput_.get(index); } else {\n return transactionInputBuilder_.getMessageOrBuilder(index);\n }\n }\n /**\n * <code>repeated .wallet.TransactionInput transaction_input = 6;</code>\n */\n public java.util.List<? extends org.bitcoinj.wallet.Protos.TransactionInputOrBuilder> \n getTransactionInputOrBuilderList() {\n if (transactionInputBuilder_ != null) {\n return transactionInputBuilder_.getMessageOrBuilderList();\n } else {\n return java.util.Collections.unmodifiableList(transactionInput_);\n }\n }\n /**\n * <code>repeated .wallet.TransactionInput transaction_input = 6;</code>\n */\n public org.bitcoinj.wallet.Protos.TransactionInput.Builder addTransactionInputBuilder() {\n return getTransactionInputFieldBuilder().addBuilder(\n org.bitcoinj.wallet.Protos.TransactionInput.getDefaultInstance());\n }\n /**\n * <code>repeated .wallet.TransactionInput transaction_input = 6;</code>\n */\n public org.bitcoinj.wallet.Protos.TransactionInput.Builder addTransactionInputBuilder(\n int index) {\n return getTransactionInputFieldBuilder().addBuilder(\n index, org.bitcoinj.wallet.Protos.TransactionInput.getDefaultInstance());\n }\n /**\n * <code>repeated .wallet.TransactionInput transaction_input = 6;</code>\n */\n public java.util.List<org.bitcoinj.wallet.Protos.TransactionInput.Builder> \n getTransactionInputBuilderList() {\n return getTransactionInputFieldBuilder().getBuilderList();\n }\n private com.google.protobuf.RepeatedFieldBuilder<\n org.bitcoinj.wallet.Protos.TransactionInput, org.bitcoinj.wallet.Protos.TransactionInput.Builder, org.bitcoinj.wallet.Protos.TransactionInputOrBuilder> \n getTransactionInputFieldBuilder() {\n if (transactionInputBuilder_ == null) {\n transactionInputBuilder_ = new com.google.protobuf.RepeatedFieldBuilder<\n org.bitcoinj.wallet.Protos.TransactionInput, org.bitcoinj.wallet.Protos.TransactionInput.Builder, org.bitcoinj.wallet.Protos.TransactionInputOrBuilder>(\n transactionInput_,\n ((bitField0_ & 0x00000020) == 0x00000020),\n getParentForChildren(),\n isClean());\n transactionInput_ = null;\n }\n return transactionInputBuilder_;\n }\n\n // repeated .wallet.TransactionOutput transaction_output = 7;\n private java.util.List<org.bitcoinj.wallet.Protos.TransactionOutput> transactionOutput_ =\n java.util.Collections.emptyList();\n private void ensureTransactionOutputIsMutable() {\n if (!((bitField0_ & 0x00000040) == 0x00000040)) {\n transactionOutput_ = new java.util.ArrayList<org.bitcoinj.wallet.Protos.TransactionOutput>(transactionOutput_);\n bitField0_ |= 0x00000040;\n }\n }\n\n private com.google.protobuf.RepeatedFieldBuilder<\n org.bitcoinj.wallet.Protos.TransactionOutput, org.bitcoinj.wallet.Protos.TransactionOutput.Builder, org.bitcoinj.wallet.Protos.TransactionOutputOrBuilder> transactionOutputBuilder_;\n\n /**\n * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code>\n */\n public java.util.List<org.bitcoinj.wallet.Protos.TransactionOutput> getTransactionOutputList() {\n if (transactionOutputBuilder_ == null) {\n return java.util.Collections.unmodifiableList(transactionOutput_);\n } else {\n return transactionOutputBuilder_.getMessageList();\n }\n }\n /**\n * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code>\n */\n public int getTransactionOutputCount() {\n if (transactionOutputBuilder_ == null) {\n return transactionOutput_.size();\n } else {\n return transactionOutputBuilder_.getCount();\n }\n }\n /**\n * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code>\n */\n public org.bitcoinj.wallet.Protos.TransactionOutput getTransactionOutput(int index) {\n if (transactionOutputBuilder_ == null) {\n return transactionOutput_.get(index);\n } else {\n return transactionOutputBuilder_.getMessage(index);\n }\n }\n /**\n * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code>\n */\n public Builder setTransactionOutput(\n int index, org.bitcoinj.wallet.Protos.TransactionOutput value) {\n if (transactionOutputBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureTransactionOutputIsMutable();\n transactionOutput_.set(index, value);\n onChanged();\n } else {\n transactionOutputBuilder_.setMessage(index, value);\n }\n return this;\n }\n /**\n * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code>\n */\n public Builder setTransactionOutput(\n int index, org.bitcoinj.wallet.Protos.TransactionOutput.Builder builderForValue) {\n if (transactionOutputBuilder_ == null) {\n ensureTransactionOutputIsMutable();\n transactionOutput_.set(index, builderForValue.build());\n onChanged();\n } else {\n transactionOutputBuilder_.setMessage(index, builderForValue.build());\n }\n return this;\n }\n /**\n * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code>\n */\n public Builder addTransactionOutput(org.bitcoinj.wallet.Protos.TransactionOutput value) {\n if (transactionOutputBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureTransactionOutputIsMutable();\n transactionOutput_.add(value);\n onChanged();\n } else {\n transactionOutputBuilder_.addMessage(value);\n }\n return this;\n }\n /**\n * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code>\n */\n public Builder addTransactionOutput(\n int index, org.bitcoinj.wallet.Protos.TransactionOutput value) {\n if (transactionOutputBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureTransactionOutputIsMutable();\n transactionOutput_.add(index, value);\n onChanged();\n } else {\n transactionOutputBuilder_.addMessage(index, value);\n }\n return this;\n }\n /**\n * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code>\n */\n public Builder addTransactionOutput(\n org.bitcoinj.wallet.Protos.TransactionOutput.Builder builderForValue) {\n if (transactionOutputBuilder_ == null) {\n ensureTransactionOutputIsMutable();\n transactionOutput_.add(builderForValue.build());\n onChanged();\n } else {\n transactionOutputBuilder_.addMessage(builderForValue.build());\n }\n return this;\n }\n /**\n * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code>\n */\n public Builder addTransactionOutput(\n int index, org.bitcoinj.wallet.Protos.TransactionOutput.Builder builderForValue) {\n if (transactionOutputBuilder_ == null) {\n ensureTransactionOutputIsMutable();\n transactionOutput_.add(index, builderForValue.build());\n onChanged();\n } else {\n transactionOutputBuilder_.addMessage(index, builderForValue.build());\n }\n return this;\n }\n /**\n * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code>\n */\n public Builder addAllTransactionOutput(\n java.lang.Iterable<? extends org.bitcoinj.wallet.Protos.TransactionOutput> values) {\n if (transactionOutputBuilder_ == null) {\n ensureTransactionOutputIsMutable();\n super.addAll(values, transactionOutput_);\n onChanged();\n } else {\n transactionOutputBuilder_.addAllMessages(values);\n }\n return this;\n }\n /**\n * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code>\n */\n public Builder clearTransactionOutput() {\n if (transactionOutputBuilder_ == null) {\n transactionOutput_ = java.util.Collections.emptyList();\n bitField0_ = (bitField0_ & ~0x00000040);\n onChanged();\n } else {\n transactionOutputBuilder_.clear();\n }\n return this;\n }\n /**\n * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code>\n */\n public Builder removeTransactionOutput(int index) {\n if (transactionOutputBuilder_ == null) {\n ensureTransactionOutputIsMutable();\n transactionOutput_.remove(index);\n onChanged();\n } else {\n transactionOutputBuilder_.remove(index);\n }\n return this;\n }\n /**\n * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code>\n */\n public org.bitcoinj.wallet.Protos.TransactionOutput.Builder getTransactionOutputBuilder(\n int index) {\n return getTransactionOutputFieldBuilder().getBuilder(index);\n }\n /**\n * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code>\n */\n public org.bitcoinj.wallet.Protos.TransactionOutputOrBuilder getTransactionOutputOrBuilder(\n int index) {\n if (transactionOutputBuilder_ == null) {\n return transactionOutput_.get(index); } else {\n return transactionOutputBuilder_.getMessageOrBuilder(index);\n }\n }\n /**\n * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code>\n */\n public java.util.List<? extends org.bitcoinj.wallet.Protos.TransactionOutputOrBuilder> \n getTransactionOutputOrBuilderList() {\n if (transactionOutputBuilder_ != null) {\n return transactionOutputBuilder_.getMessageOrBuilderList();\n } else {\n return java.util.Collections.unmodifiableList(transactionOutput_);\n }\n }\n /**\n * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code>\n */\n public org.bitcoinj.wallet.Protos.TransactionOutput.Builder addTransactionOutputBuilder() {\n return getTransactionOutputFieldBuilder().addBuilder(\n org.bitcoinj.wallet.Protos.TransactionOutput.getDefaultInstance());\n }\n /**\n * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code>\n */\n public org.bitcoinj.wallet.Protos.TransactionOutput.Builder addTransactionOutputBuilder(\n int index) {\n return getTransactionOutputFieldBuilder().addBuilder(\n index, org.bitcoinj.wallet.Protos.TransactionOutput.getDefaultInstance());\n }\n /**\n * <code>repeated .wallet.TransactionOutput transaction_output = 7;</code>\n */\n public java.util.List<org.bitcoinj.wallet.Protos.TransactionOutput.Builder> \n getTransactionOutputBuilderList() {\n return getTransactionOutputFieldBuilder().getBuilderList();\n }\n private com.google.protobuf.RepeatedFieldBuilder<\n org.bitcoinj.wallet.Protos.TransactionOutput, org.bitcoinj.wallet.Protos.TransactionOutput.Builder, org.bitcoinj.wallet.Protos.TransactionOutputOrBuilder> \n getTransactionOutputFieldBuilder() {\n if (transactionOutputBuilder_ == null) {\n transactionOutputBuilder_ = new com.google.protobuf.RepeatedFieldBuilder<\n org.bitcoinj.wallet.Protos.TransactionOutput, org.bitcoinj.wallet.Protos.TransactionOutput.Builder, org.bitcoinj.wallet.Protos.TransactionOutputOrBuilder>(\n transactionOutput_,\n ((bitField0_ & 0x00000040) == 0x00000040),\n getParentForChildren(),\n isClean());\n transactionOutput_ = null;\n }\n return transactionOutputBuilder_;\n }\n\n // repeated bytes block_hash = 8;\n private java.util.List<com.google.protobuf.ByteString> blockHash_ = java.util.Collections.emptyList();\n private void ensureBlockHashIsMutable() {\n if (!((bitField0_ & 0x00000080) == 0x00000080)) {\n blockHash_ = new java.util.ArrayList<com.google.protobuf.ByteString>(blockHash_);\n bitField0_ |= 0x00000080;\n }\n }\n /**\n * <code>repeated bytes block_hash = 8;</code>\n *\n * <pre>\n * A list of blocks in which the transaction has been observed (on any chain). Also, a number used to disambiguate\n * ordering within a block.\n * </pre>\n */\n public java.util.List<com.google.protobuf.ByteString>\n getBlockHashList() {\n return java.util.Collections.unmodifiableList(blockHash_);\n }\n /**\n * <code>repeated bytes block_hash = 8;</code>\n *\n * <pre>\n * A list of blocks in which the transaction has been observed (on any chain). Also, a number used to disambiguate\n * ordering within a block.\n * </pre>\n */\n public int getBlockHashCount() {\n return blockHash_.size();\n }\n /**\n * <code>repeated bytes block_hash = 8;</code>\n *\n * <pre>\n * A list of blocks in which the transaction has been observed (on any chain). Also, a number used to disambiguate\n * ordering within a block.\n * </pre>\n */\n public com.google.protobuf.ByteString getBlockHash(int index) {\n return blockHash_.get(index);\n }\n /**\n * <code>repeated bytes block_hash = 8;</code>\n *\n * <pre>\n * A list of blocks in which the transaction has been observed (on any chain). Also, a number used to disambiguate\n * ordering within a block.\n * </pre>\n */\n public Builder setBlockHash(\n int index, com.google.protobuf.ByteString value) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureBlockHashIsMutable();\n blockHash_.set(index, value);\n onChanged();\n return this;\n }\n /**\n * <code>repeated bytes block_hash = 8;</code>\n *\n * <pre>\n * A list of blocks in which the transaction has been observed (on any chain). Also, a number used to disambiguate\n * ordering within a block.\n * </pre>\n */\n public Builder addBlockHash(com.google.protobuf.ByteString value) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureBlockHashIsMutable();\n blockHash_.add(value);\n onChanged();\n return this;\n }\n /**\n * <code>repeated bytes block_hash = 8;</code>\n *\n * <pre>\n * A list of blocks in which the transaction has been observed (on any chain). Also, a number used to disambiguate\n * ordering within a block.\n * </pre>\n */\n public Builder addAllBlockHash(\n java.lang.Iterable<? extends com.google.protobuf.ByteString> values) {\n ensureBlockHashIsMutable();\n super.addAll(values, blockHash_);\n onChanged();\n return this;\n }\n /**\n * <code>repeated bytes block_hash = 8;</code>\n *\n * <pre>\n * A list of blocks in which the transaction has been observed (on any chain). Also, a number used to disambiguate\n * ordering within a block.\n * </pre>\n */\n public Builder clearBlockHash() {\n blockHash_ = java.util.Collections.emptyList();\n bitField0_ = (bitField0_ & ~0x00000080);\n onChanged();\n return this;\n }\n\n // repeated int32 block_relativity_offsets = 11;\n private java.util.List<java.lang.Integer> blockRelativityOffsets_ = java.util.Collections.emptyList();\n private void ensureBlockRelativityOffsetsIsMutable() {\n if (!((bitField0_ & 0x00000100) == 0x00000100)) {\n blockRelativityOffsets_ = new java.util.ArrayList<java.lang.Integer>(blockRelativityOffsets_);\n bitField0_ |= 0x00000100;\n }\n }\n /**\n * <code>repeated int32 block_relativity_offsets = 11;</code>\n */\n public java.util.List<java.lang.Integer>\n getBlockRelativityOffsetsList() {\n return java.util.Collections.unmodifiableList(blockRelativityOffsets_);\n }\n /**\n * <code>repeated int32 block_relativity_offsets = 11;</code>\n */\n public int getBlockRelativityOffsetsCount() {\n return blockRelativityOffsets_.size();\n }\n /**\n * <code>repeated int32 block_relativity_offsets = 11;</code>\n */\n public int getBlockRelativityOffsets(int index) {\n return blockRelativityOffsets_.get(index);\n }\n /**\n * <code>repeated int32 block_relativity_offsets = 11;</code>\n */\n public Builder setBlockRelativityOffsets(\n int index, int value) {\n ensureBlockRelativityOffsetsIsMutable();\n blockRelativityOffsets_.set(index, value);\n onChanged();\n return this;\n }\n /**\n * <code>repeated int32 block_relativity_offsets = 11;</code>\n */\n public Builder addBlockRelativityOffsets(int value) {\n ensureBlockRelativityOffsetsIsMutable();\n blockRelativityOffsets_.add(value);\n onChanged();\n return this;\n }\n /**\n * <code>repeated int32 block_relativity_offsets = 11;</code>\n */\n public Builder addAllBlockRelativityOffsets(\n java.lang.Iterable<? extends java.lang.Integer> values) {\n ensureBlockRelativityOffsetsIsMutable();\n super.addAll(values, blockRelativityOffsets_);\n onChanged();\n return this;\n }\n /**\n * <code>repeated int32 block_relativity_offsets = 11;</code>\n */\n public Builder clearBlockRelativityOffsets() {\n blockRelativityOffsets_ = java.util.Collections.emptyList();\n bitField0_ = (bitField0_ & ~0x00000100);\n onChanged();\n return this;\n }\n\n // optional .wallet.TransactionConfidence confidence = 9;\n private org.bitcoinj.wallet.Protos.TransactionConfidence confidence_ = org.bitcoinj.wallet.Protos.TransactionConfidence.getDefaultInstance();\n private com.google.protobuf.SingleFieldBuilder<\n org.bitcoinj.wallet.Protos.TransactionConfidence, org.bitcoinj.wallet.Protos.TransactionConfidence.Builder, org.bitcoinj.wallet.Protos.TransactionConfidenceOrBuilder> confidenceBuilder_;\n /**\n * <code>optional .wallet.TransactionConfidence confidence = 9;</code>\n *\n * <pre>\n * Data describing where the transaction is in the chain.\n * </pre>\n */\n public boolean hasConfidence() {\n return ((bitField0_ & 0x00000200) == 0x00000200);\n }\n /**\n * <code>optional .wallet.TransactionConfidence confidence = 9;</code>\n *\n * <pre>\n * Data describing where the transaction is in the chain.\n * </pre>\n */\n public org.bitcoinj.wallet.Protos.TransactionConfidence getConfidence() {\n if (confidenceBuilder_ == null) {\n return confidence_;\n } else {\n return confidenceBuilder_.getMessage();\n }\n }\n /**\n * <code>optional .wallet.TransactionConfidence confidence = 9;</code>\n *\n * <pre>\n * Data describing where the transaction is in the chain.\n * </pre>\n */\n public Builder setConfidence(org.bitcoinj.wallet.Protos.TransactionConfidence value) {\n if (confidenceBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n confidence_ = value;\n onChanged();\n } else {\n confidenceBuilder_.setMessage(value);\n }\n bitField0_ |= 0x00000200;\n return this;\n }\n /**\n * <code>optional .wallet.TransactionConfidence confidence = 9;</code>\n *\n * <pre>\n * Data describing where the transaction is in the chain.\n * </pre>\n */\n public Builder setConfidence(\n org.bitcoinj.wallet.Protos.TransactionConfidence.Builder builderForValue) {\n if (confidenceBuilder_ == null) {\n confidence_ = builderForValue.build();\n onChanged();\n } else {\n confidenceBuilder_.setMessage(builderForValue.build());\n }\n bitField0_ |= 0x00000200;\n return this;\n }\n /**\n * <code>optional .wallet.TransactionConfidence confidence = 9;</code>\n *\n * <pre>\n * Data describing where the transaction is in the chain.\n * </pre>\n */\n public Builder mergeConfidence(org.bitcoinj.wallet.Protos.TransactionConfidence value) {\n if (confidenceBuilder_ == null) {\n if (((bitField0_ & 0x00000200) == 0x00000200) &&\n confidence_ != org.bitcoinj.wallet.Protos.TransactionConfidence.getDefaultInstance()) {\n confidence_ =\n org.bitcoinj.wallet.Protos.TransactionConfidence.newBuilder(confidence_).mergeFrom(value).buildPartial();\n } else {\n confidence_ = value;\n }\n onChanged();\n } else {\n confidenceBuilder_.mergeFrom(value);\n }\n bitField0_ |= 0x00000200;\n return this;\n }\n /**\n * <code>optional .wallet.TransactionConfidence confidence = 9;</code>\n *\n * <pre>\n * Data describing where the transaction is in the chain.\n * </pre>\n */\n public Builder clearConfidence() {\n if (confidenceBuilder_ == null) {\n confidence_ = org.bitcoinj.wallet.Protos.TransactionConfidence.getDefaultInstance();\n onChanged();\n } else {\n confidenceBuilder_.clear();\n }\n bitField0_ = (bitField0_ & ~0x00000200);\n return this;\n }\n /**\n * <code>optional .wallet.TransactionConfidence confidence = 9;</code>\n *\n * <pre>\n * Data describing where the transaction is in the chain.\n * </pre>\n */\n public org.bitcoinj.wallet.Protos.TransactionConfidence.Builder getConfidenceBuilder() {\n bitField0_ |= 0x00000200;\n onChanged();\n return getConfidenceFieldBuilder().getBuilder();\n }\n /**\n * <code>optional .wallet.TransactionConfidence confidence = 9;</code>\n *\n * <pre>\n * Data describing where the transaction is in the chain.\n * </pre>\n */\n public org.bitcoinj.wallet.Protos.TransactionConfidenceOrBuilder getConfidenceOrBuilder() {\n if (confidenceBuilder_ != null) {\n return confidenceBuilder_.getMessageOrBuilder();\n } else {\n return confidence_;\n }\n }\n /**\n * <code>optional .wallet.TransactionConfidence confidence = 9;</code>\n *\n * <pre>\n * Data describing where the transaction is in the chain.\n * </pre>\n */\n private com.google.protobuf.SingleFieldBuilder<\n org.bitcoinj.wallet.Protos.TransactionConfidence, org.bitcoinj.wallet.Protos.TransactionConfidence.Builder, org.bitcoinj.wallet.Protos.TransactionConfidenceOrBuilder> \n getConfidenceFieldBuilder() {\n if (confidenceBuilder_ == null) {\n confidenceBuilder_ = new com.google.protobuf.SingleFieldBuilder<\n org.bitcoinj.wallet.Protos.TransactionConfidence, org.bitcoinj.wallet.Protos.TransactionConfidence.Builder, org.bitcoinj.wallet.Protos.TransactionConfidenceOrBuilder>(\n confidence_,\n getParentForChildren(),\n isClean());\n confidence_ = null;\n }\n return confidenceBuilder_;\n }\n\n // optional .wallet.Transaction.Purpose purpose = 10 [default = UNKNOWN];\n private org.bitcoinj.wallet.Protos.Transaction.Purpose purpose_ = org.bitcoinj.wallet.Protos.Transaction.Purpose.UNKNOWN;\n /**\n * <code>optional .wallet.Transaction.Purpose purpose = 10 [default = UNKNOWN];</code>\n */\n public boolean hasPurpose() {\n return ((bitField0_ & 0x00000400) == 0x00000400);\n }\n /**\n * <code>optional .wallet.Transaction.Purpose purpose = 10 [default = UNKNOWN];</code>\n */\n public org.bitcoinj.wallet.Protos.Transaction.Purpose getPurpose() {\n return purpose_;\n }\n /**\n * <code>optional .wallet.Transaction.Purpose purpose = 10 [default = UNKNOWN];</code>\n */\n public Builder setPurpose(org.bitcoinj.wallet.Protos.Transaction.Purpose value) {\n if (value == null) {\n throw new NullPointerException();\n }\n bitField0_ |= 0x00000400;\n purpose_ = value;\n onChanged();\n return this;\n }\n /**\n * <code>optional .wallet.Transaction.Purpose purpose = 10 [default = UNKNOWN];</code>\n */\n public Builder clearPurpose() {\n bitField0_ = (bitField0_ & ~0x00000400);\n purpose_ = org.bitcoinj.wallet.Protos.Transaction.Purpose.UNKNOWN;\n onChanged();\n return this;\n }\n\n // @@protoc_insertion_point(builder_scope:wallet.Transaction)\n }\n\n static {\n defaultInstance = new Transaction(true);\n defaultInstance.initFields();\n }\n\n // @@protoc_insertion_point(class_scope:wallet.Transaction)\n }\n\n public interface ScryptParametersOrBuilder\n extends com.google.protobuf.MessageOrBuilder {\n\n // required bytes salt = 1;\n /**\n * <code>required bytes salt = 1;</code>\n *\n * <pre>\n * Salt to use in generation of the wallet password (8 bytes)\n * </pre>\n */\n boolean hasSalt();\n /**\n * <code>required bytes salt = 1;</code>\n *\n * <pre>\n * Salt to use in generation of the wallet password (8 bytes)\n * </pre>\n */\n com.google.protobuf.ByteString getSalt();\n\n // optional int64 n = 2 [default = 16384];\n /**\n * <code>optional int64 n = 2 [default = 16384];</code>\n *\n * <pre>\n * CPU/ memory cost parameter\n * </pre>\n */\n boolean hasN();\n /**\n * <code>optional int64 n = 2 [default = 16384];</code>\n *\n * <pre>\n * CPU/ memory cost parameter\n * </pre>\n */\n long getN();\n\n // optional int32 r = 3 [default = 8];\n /**\n * <code>optional int32 r = 3 [default = 8];</code>\n *\n * <pre>\n * Block size parameter\n * </pre>\n */\n boolean hasR();\n /**\n * <code>optional int32 r = 3 [default = 8];</code>\n *\n * <pre>\n * Block size parameter\n * </pre>\n */\n int getR();\n\n // optional int32 p = 4 [default = 1];\n /**\n * <code>optional int32 p = 4 [default = 1];</code>\n *\n * <pre>\n * Parallelisation parameter\n * </pre>\n */\n boolean hasP();\n /**\n * <code>optional int32 p = 4 [default = 1];</code>\n *\n * <pre>\n * Parallelisation parameter\n * </pre>\n */\n int getP();\n }\n /**\n * Protobuf type {@code wallet.ScryptParameters}\n *\n * <pre>\n ** The parameters used in the scrypt key derivation function.\n * The default values are taken from http://www.tarsnap.com/scrypt/scrypt-slides.pdf.\n * They can be increased - n is the number of iterations performed and\n * r and p can be used to tweak the algorithm - see:\n * http://stackoverflow.com/questions/11126315/what-are-optimal-scrypt-work-factors\n * </pre>\n */\n public static final class ScryptParameters extends\n com.google.protobuf.GeneratedMessage\n implements ScryptParametersOrBuilder {\n // Use ScryptParameters.newBuilder() to construct.\n private ScryptParameters(com.google.protobuf.GeneratedMessage.Builder<?> builder) {\n super(builder);\n this.unknownFields = builder.getUnknownFields();\n }\n private ScryptParameters(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }\n\n private static final ScryptParameters defaultInstance;\n public static ScryptParameters getDefaultInstance() {\n return defaultInstance;\n }\n\n public ScryptParameters getDefaultInstanceForType() {\n return defaultInstance;\n }\n\n private final com.google.protobuf.UnknownFieldSet unknownFields;\n @java.lang.Override\n public final com.google.protobuf.UnknownFieldSet\n getUnknownFields() {\n return this.unknownFields;\n }\n private ScryptParameters(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n initFields();\n int mutable_bitField0_ = 0;\n com.google.protobuf.UnknownFieldSet.Builder unknownFields =\n com.google.protobuf.UnknownFieldSet.newBuilder();\n try {\n boolean done = false;\n while (!done) {\n int tag = input.readTag();\n switch (tag) {\n case 0:\n done = true;\n break;\n default: {\n if (!parseUnknownField(input, unknownFields,\n extensionRegistry, tag)) {\n done = true;\n }\n break;\n }\n case 10: {\n bitField0_ |= 0x00000001;\n salt_ = input.readBytes();\n break;\n }\n case 16: {\n bitField0_ |= 0x00000002;\n n_ = input.readInt64();\n break;\n }\n case 24: {\n bitField0_ |= 0x00000004;\n r_ = input.readInt32();\n break;\n }\n case 32: {\n bitField0_ |= 0x00000008;\n p_ = input.readInt32();\n break;\n }\n }\n }\n } catch (com.google.protobuf.InvalidProtocolBufferException e) {\n throw e.setUnfinishedMessage(this);\n } catch (java.io.IOException e) {\n throw new com.google.protobuf.InvalidProtocolBufferException(\n e.getMessage()).setUnfinishedMessage(this);\n } finally {\n this.unknownFields = unknownFields.build();\n makeExtensionsImmutable();\n }\n }\n public static final com.google.protobuf.Descriptors.Descriptor\n getDescriptor() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_ScryptParameters_descriptor;\n }\n\n protected com.google.protobuf.GeneratedMessage.FieldAccessorTable\n internalGetFieldAccessorTable() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_ScryptParameters_fieldAccessorTable\n .ensureFieldAccessorsInitialized(\n org.bitcoinj.wallet.Protos.ScryptParameters.class, org.bitcoinj.wallet.Protos.ScryptParameters.Builder.class);\n }\n\n public static com.google.protobuf.Parser<ScryptParameters> PARSER =\n new com.google.protobuf.AbstractParser<ScryptParameters>() {\n public ScryptParameters parsePartialFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return new ScryptParameters(input, extensionRegistry);\n }\n };\n\n @java.lang.Override\n public com.google.protobuf.Parser<ScryptParameters> getParserForType() {\n return PARSER;\n }\n\n private int bitField0_;\n // required bytes salt = 1;\n public static final int SALT_FIELD_NUMBER = 1;\n private com.google.protobuf.ByteString salt_;\n /**\n * <code>required bytes salt = 1;</code>\n *\n * <pre>\n * Salt to use in generation of the wallet password (8 bytes)\n * </pre>\n */\n public boolean hasSalt() {\n return ((bitField0_ & 0x00000001) == 0x00000001);\n }\n /**\n * <code>required bytes salt = 1;</code>\n *\n * <pre>\n * Salt to use in generation of the wallet password (8 bytes)\n * </pre>\n */\n public com.google.protobuf.ByteString getSalt() {\n return salt_;\n }\n\n // optional int64 n = 2 [default = 16384];\n public static final int N_FIELD_NUMBER = 2;\n private long n_;\n /**\n * <code>optional int64 n = 2 [default = 16384];</code>\n *\n * <pre>\n * CPU/ memory cost parameter\n * </pre>\n */\n public boolean hasN() {\n return ((bitField0_ & 0x00000002) == 0x00000002);\n }\n /**\n * <code>optional int64 n = 2 [default = 16384];</code>\n *\n * <pre>\n * CPU/ memory cost parameter\n * </pre>\n */\n public long getN() {\n return n_;\n }\n\n // optional int32 r = 3 [default = 8];\n public static final int R_FIELD_NUMBER = 3;\n private int r_;\n /**\n * <code>optional int32 r = 3 [default = 8];</code>\n *\n * <pre>\n * Block size parameter\n * </pre>\n */\n public boolean hasR() {\n return ((bitField0_ & 0x00000004) == 0x00000004);\n }\n /**\n * <code>optional int32 r = 3 [default = 8];</code>\n *\n * <pre>\n * Block size parameter\n * </pre>\n */\n public int getR() {\n return r_;\n }\n\n // optional int32 p = 4 [default = 1];\n public static final int P_FIELD_NUMBER = 4;\n private int p_;\n /**\n * <code>optional int32 p = 4 [default = 1];</code>\n *\n * <pre>\n * Parallelisation parameter\n * </pre>\n */\n public boolean hasP() {\n return ((bitField0_ & 0x00000008) == 0x00000008);\n }\n /**\n * <code>optional int32 p = 4 [default = 1];</code>\n *\n * <pre>\n * Parallelisation parameter\n * </pre>\n */\n public int getP() {\n return p_;\n }\n\n private void initFields() {\n salt_ = com.google.protobuf.ByteString.EMPTY;\n n_ = 16384L;\n r_ = 8;\n p_ = 1;\n }\n private byte memoizedIsInitialized = -1;\n public final boolean isInitialized() {\n byte isInitialized = memoizedIsInitialized;\n if (isInitialized != -1) return isInitialized == 1;\n\n if (!hasSalt()) {\n memoizedIsInitialized = 0;\n return false;\n }\n memoizedIsInitialized = 1;\n return true;\n }\n\n public void writeTo(com.google.protobuf.CodedOutputStream output)\n throws java.io.IOException {\n getSerializedSize();\n if (((bitField0_ & 0x00000001) == 0x00000001)) {\n output.writeBytes(1, salt_);\n }\n if (((bitField0_ & 0x00000002) == 0x00000002)) {\n output.writeInt64(2, n_);\n }\n if (((bitField0_ & 0x00000004) == 0x00000004)) {\n output.writeInt32(3, r_);\n }\n if (((bitField0_ & 0x00000008) == 0x00000008)) {\n output.writeInt32(4, p_);\n }\n getUnknownFields().writeTo(output);\n }\n\n private int memoizedSerializedSize = -1;\n public int getSerializedSize() {\n int size = memoizedSerializedSize;\n if (size != -1) return size;\n\n size = 0;\n if (((bitField0_ & 0x00000001) == 0x00000001)) {\n size += com.google.protobuf.CodedOutputStream\n .computeBytesSize(1, salt_);\n }\n if (((bitField0_ & 0x00000002) == 0x00000002)) {\n size += com.google.protobuf.CodedOutputStream\n .computeInt64Size(2, n_);\n }\n if (((bitField0_ & 0x00000004) == 0x00000004)) {\n size += com.google.protobuf.CodedOutputStream\n .computeInt32Size(3, r_);\n }\n if (((bitField0_ & 0x00000008) == 0x00000008)) {\n size += com.google.protobuf.CodedOutputStream\n .computeInt32Size(4, p_);\n }\n size += getUnknownFields().getSerializedSize();\n memoizedSerializedSize = size;\n return size;\n }\n\n private static final long serialVersionUID = 0L;\n @java.lang.Override\n protected java.lang.Object writeReplace()\n throws java.io.ObjectStreamException {\n return super.writeReplace();\n }\n\n public static org.bitcoinj.wallet.Protos.ScryptParameters parseFrom(\n com.google.protobuf.ByteString data)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n public static org.bitcoinj.wallet.Protos.ScryptParameters parseFrom(\n com.google.protobuf.ByteString data,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n public static org.bitcoinj.wallet.Protos.ScryptParameters parseFrom(byte[] data)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n public static org.bitcoinj.wallet.Protos.ScryptParameters parseFrom(\n byte[] data,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n public static org.bitcoinj.wallet.Protos.ScryptParameters parseFrom(java.io.InputStream input)\n throws java.io.IOException {\n return PARSER.parseFrom(input);\n }\n public static org.bitcoinj.wallet.Protos.ScryptParameters parseFrom(\n java.io.InputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return PARSER.parseFrom(input, extensionRegistry);\n }\n public static org.bitcoinj.wallet.Protos.ScryptParameters parseDelimitedFrom(java.io.InputStream input)\n throws java.io.IOException {\n return PARSER.parseDelimitedFrom(input);\n }\n public static org.bitcoinj.wallet.Protos.ScryptParameters parseDelimitedFrom(\n java.io.InputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return PARSER.parseDelimitedFrom(input, extensionRegistry);\n }\n public static org.bitcoinj.wallet.Protos.ScryptParameters parseFrom(\n com.google.protobuf.CodedInputStream input)\n throws java.io.IOException {\n return PARSER.parseFrom(input);\n }\n public static org.bitcoinj.wallet.Protos.ScryptParameters parseFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return PARSER.parseFrom(input, extensionRegistry);\n }\n\n public static Builder newBuilder() { return Builder.create(); }\n public Builder newBuilderForType() { return newBuilder(); }\n public static Builder newBuilder(org.bitcoinj.wallet.Protos.ScryptParameters prototype) {\n return newBuilder().mergeFrom(prototype);\n }\n public Builder toBuilder() { return newBuilder(this); }\n\n @java.lang.Override\n protected Builder newBuilderForType(\n com.google.protobuf.GeneratedMessage.BuilderParent parent) {\n Builder builder = new Builder(parent);\n return builder;\n }\n /**\n * Protobuf type {@code wallet.ScryptParameters}\n *\n * <pre>\n ** The parameters used in the scrypt key derivation function.\n * The default values are taken from http://www.tarsnap.com/scrypt/scrypt-slides.pdf.\n * They can be increased - n is the number of iterations performed and\n * r and p can be used to tweak the algorithm - see:\n * http://stackoverflow.com/questions/11126315/what-are-optimal-scrypt-work-factors\n * </pre>\n */\n public static final class Builder extends\n com.google.protobuf.GeneratedMessage.Builder<Builder>\n implements org.bitcoinj.wallet.Protos.ScryptParametersOrBuilder {\n public static final com.google.protobuf.Descriptors.Descriptor\n getDescriptor() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_ScryptParameters_descriptor;\n }\n\n protected com.google.protobuf.GeneratedMessage.FieldAccessorTable\n internalGetFieldAccessorTable() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_ScryptParameters_fieldAccessorTable\n .ensureFieldAccessorsInitialized(\n org.bitcoinj.wallet.Protos.ScryptParameters.class, org.bitcoinj.wallet.Protos.ScryptParameters.Builder.class);\n }\n\n // Construct using org.bitcoinj.wallet.Protos.ScryptParameters.newBuilder()\n private Builder() {\n maybeForceBuilderInitialization();\n }\n\n private Builder(\n com.google.protobuf.GeneratedMessage.BuilderParent parent) {\n super(parent);\n maybeForceBuilderInitialization();\n }\n private void maybeForceBuilderInitialization() {\n if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {\n }\n }\n private static Builder create() {\n return new Builder();\n }\n\n public Builder clear() {\n super.clear();\n salt_ = com.google.protobuf.ByteString.EMPTY;\n bitField0_ = (bitField0_ & ~0x00000001);\n n_ = 16384L;\n bitField0_ = (bitField0_ & ~0x00000002);\n r_ = 8;\n bitField0_ = (bitField0_ & ~0x00000004);\n p_ = 1;\n bitField0_ = (bitField0_ & ~0x00000008);\n return this;\n }\n\n public Builder clone() {\n return create().mergeFrom(buildPartial());\n }\n\n public com.google.protobuf.Descriptors.Descriptor\n getDescriptorForType() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_ScryptParameters_descriptor;\n }\n\n public org.bitcoinj.wallet.Protos.ScryptParameters getDefaultInstanceForType() {\n return org.bitcoinj.wallet.Protos.ScryptParameters.getDefaultInstance();\n }\n\n public org.bitcoinj.wallet.Protos.ScryptParameters build() {\n org.bitcoinj.wallet.Protos.ScryptParameters result = buildPartial();\n if (!result.isInitialized()) {\n throw newUninitializedMessageException(result);\n }\n return result;\n }\n\n public org.bitcoinj.wallet.Protos.ScryptParameters buildPartial() {\n org.bitcoinj.wallet.Protos.ScryptParameters result = new org.bitcoinj.wallet.Protos.ScryptParameters(this);\n int from_bitField0_ = bitField0_;\n int to_bitField0_ = 0;\n if (((from_bitField0_ & 0x00000001) == 0x00000001)) {\n to_bitField0_ |= 0x00000001;\n }\n result.salt_ = salt_;\n if (((from_bitField0_ & 0x00000002) == 0x00000002)) {\n to_bitField0_ |= 0x00000002;\n }\n result.n_ = n_;\n if (((from_bitField0_ & 0x00000004) == 0x00000004)) {\n to_bitField0_ |= 0x00000004;\n }\n result.r_ = r_;\n if (((from_bitField0_ & 0x00000008) == 0x00000008)) {\n to_bitField0_ |= 0x00000008;\n }\n result.p_ = p_;\n result.bitField0_ = to_bitField0_;\n onBuilt();\n return result;\n }\n\n public Builder mergeFrom(com.google.protobuf.Message other) {\n if (other instanceof org.bitcoinj.wallet.Protos.ScryptParameters) {\n return mergeFrom((org.bitcoinj.wallet.Protos.ScryptParameters)other);\n } else {\n super.mergeFrom(other);\n return this;\n }\n }\n\n public Builder mergeFrom(org.bitcoinj.wallet.Protos.ScryptParameters other) {\n if (other == org.bitcoinj.wallet.Protos.ScryptParameters.getDefaultInstance()) return this;\n if (other.hasSalt()) {\n setSalt(other.getSalt());\n }\n if (other.hasN()) {\n setN(other.getN());\n }\n if (other.hasR()) {\n setR(other.getR());\n }\n if (other.hasP()) {\n setP(other.getP());\n }\n this.mergeUnknownFields(other.getUnknownFields());\n return this;\n }\n\n public final boolean isInitialized() {\n if (!hasSalt()) {\n \n return false;\n }\n return true;\n }\n\n public Builder mergeFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n org.bitcoinj.wallet.Protos.ScryptParameters parsedMessage = null;\n try {\n parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);\n } catch (com.google.protobuf.InvalidProtocolBufferException e) {\n parsedMessage = (org.bitcoinj.wallet.Protos.ScryptParameters) e.getUnfinishedMessage();\n throw e;\n } finally {\n if (parsedMessage != null) {\n mergeFrom(parsedMessage);\n }\n }\n return this;\n }\n private int bitField0_;\n\n // required bytes salt = 1;\n private com.google.protobuf.ByteString salt_ = com.google.protobuf.ByteString.EMPTY;\n /**\n * <code>required bytes salt = 1;</code>\n *\n * <pre>\n * Salt to use in generation of the wallet password (8 bytes)\n * </pre>\n */\n public boolean hasSalt() {\n return ((bitField0_ & 0x00000001) == 0x00000001);\n }\n /**\n * <code>required bytes salt = 1;</code>\n *\n * <pre>\n * Salt to use in generation of the wallet password (8 bytes)\n * </pre>\n */\n public com.google.protobuf.ByteString getSalt() {\n return salt_;\n }\n /**\n * <code>required bytes salt = 1;</code>\n *\n * <pre>\n * Salt to use in generation of the wallet password (8 bytes)\n * </pre>\n */\n public Builder setSalt(com.google.protobuf.ByteString value) {\n if (value == null) {\n throw new NullPointerException();\n }\n bitField0_ |= 0x00000001;\n salt_ = value;\n onChanged();\n return this;\n }\n /**\n * <code>required bytes salt = 1;</code>\n *\n * <pre>\n * Salt to use in generation of the wallet password (8 bytes)\n * </pre>\n */\n public Builder clearSalt() {\n bitField0_ = (bitField0_ & ~0x00000001);\n salt_ = getDefaultInstance().getSalt();\n onChanged();\n return this;\n }\n\n // optional int64 n = 2 [default = 16384];\n private long n_ = 16384L;\n /**\n * <code>optional int64 n = 2 [default = 16384];</code>\n *\n * <pre>\n * CPU/ memory cost parameter\n * </pre>\n */\n public boolean hasN() {\n return ((bitField0_ & 0x00000002) == 0x00000002);\n }\n /**\n * <code>optional int64 n = 2 [default = 16384];</code>\n *\n * <pre>\n * CPU/ memory cost parameter\n * </pre>\n */\n public long getN() {\n return n_;\n }\n /**\n * <code>optional int64 n = 2 [default = 16384];</code>\n *\n * <pre>\n * CPU/ memory cost parameter\n * </pre>\n */\n public Builder setN(long value) {\n bitField0_ |= 0x00000002;\n n_ = value;\n onChanged();\n return this;\n }\n /**\n * <code>optional int64 n = 2 [default = 16384];</code>\n *\n * <pre>\n * CPU/ memory cost parameter\n * </pre>\n */\n public Builder clearN() {\n bitField0_ = (bitField0_ & ~0x00000002);\n n_ = 16384L;\n onChanged();\n return this;\n }\n\n // optional int32 r = 3 [default = 8];\n private int r_ = 8;\n /**\n * <code>optional int32 r = 3 [default = 8];</code>\n *\n * <pre>\n * Block size parameter\n * </pre>\n */\n public boolean hasR() {\n return ((bitField0_ & 0x00000004) == 0x00000004);\n }\n /**\n * <code>optional int32 r = 3 [default = 8];</code>\n *\n * <pre>\n * Block size parameter\n * </pre>\n */\n public int getR() {\n return r_;\n }\n /**\n * <code>optional int32 r = 3 [default = 8];</code>\n *\n * <pre>\n * Block size parameter\n * </pre>\n */\n public Builder setR(int value) {\n bitField0_ |= 0x00000004;\n r_ = value;\n onChanged();\n return this;\n }\n /**\n * <code>optional int32 r = 3 [default = 8];</code>\n *\n * <pre>\n * Block size parameter\n * </pre>\n */\n public Builder clearR() {\n bitField0_ = (bitField0_ & ~0x00000004);\n r_ = 8;\n onChanged();\n return this;\n }\n\n // optional int32 p = 4 [default = 1];\n private int p_ = 1;\n /**\n * <code>optional int32 p = 4 [default = 1];</code>\n *\n * <pre>\n * Parallelisation parameter\n * </pre>\n */\n public boolean hasP() {\n return ((bitField0_ & 0x00000008) == 0x00000008);\n }\n /**\n * <code>optional int32 p = 4 [default = 1];</code>\n *\n * <pre>\n * Parallelisation parameter\n * </pre>\n */\n public int getP() {\n return p_;\n }\n /**\n * <code>optional int32 p = 4 [default = 1];</code>\n *\n * <pre>\n * Parallelisation parameter\n * </pre>\n */\n public Builder setP(int value) {\n bitField0_ |= 0x00000008;\n p_ = value;\n onChanged();\n return this;\n }\n /**\n * <code>optional int32 p = 4 [default = 1];</code>\n *\n * <pre>\n * Parallelisation parameter\n * </pre>\n */\n public Builder clearP() {\n bitField0_ = (bitField0_ & ~0x00000008);\n p_ = 1;\n onChanged();\n return this;\n }\n\n // @@protoc_insertion_point(builder_scope:wallet.ScryptParameters)\n }\n\n static {\n defaultInstance = new ScryptParameters(true);\n defaultInstance.initFields();\n }\n\n // @@protoc_insertion_point(class_scope:wallet.ScryptParameters)\n }\n\n public interface ExtensionOrBuilder\n extends com.google.protobuf.MessageOrBuilder {\n\n // required string id = 1;\n /**\n * <code>required string id = 1;</code>\n *\n * <pre>\n * like org.whatever.foo.bar\n * </pre>\n */\n boolean hasId();\n /**\n * <code>required string id = 1;</code>\n *\n * <pre>\n * like org.whatever.foo.bar\n * </pre>\n */\n java.lang.String getId();\n /**\n * <code>required string id = 1;</code>\n *\n * <pre>\n * like org.whatever.foo.bar\n * </pre>\n */\n com.google.protobuf.ByteString\n getIdBytes();\n\n // required bytes data = 2;\n /**\n * <code>required bytes data = 2;</code>\n */\n boolean hasData();\n /**\n * <code>required bytes data = 2;</code>\n */\n com.google.protobuf.ByteString getData();\n\n // required bool mandatory = 3;\n /**\n * <code>required bool mandatory = 3;</code>\n *\n * <pre>\n * If we do not understand a mandatory extension, abort to prevent data loss.\n * For example, this could be applied to a new type of holding, such as a contract, where\n * dropping of an extension in a read/write cycle could cause loss of value.\n * </pre>\n */\n boolean hasMandatory();\n /**\n * <code>required bool mandatory = 3;</code>\n *\n * <pre>\n * If we do not understand a mandatory extension, abort to prevent data loss.\n * For example, this could be applied to a new type of holding, such as a contract, where\n * dropping of an extension in a read/write cycle could cause loss of value.\n * </pre>\n */\n boolean getMandatory();\n }\n /**\n * Protobuf type {@code wallet.Extension}\n *\n * <pre>\n ** An extension to the wallet \n * </pre>\n */\n public static final class Extension extends\n com.google.protobuf.GeneratedMessage\n implements ExtensionOrBuilder {\n // Use Extension.newBuilder() to construct.\n private Extension(com.google.protobuf.GeneratedMessage.Builder<?> builder) {\n super(builder);\n this.unknownFields = builder.getUnknownFields();\n }\n private Extension(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }\n\n private static final Extension defaultInstance;\n public static Extension getDefaultInstance() {\n return defaultInstance;\n }\n\n public Extension getDefaultInstanceForType() {\n return defaultInstance;\n }\n\n private final com.google.protobuf.UnknownFieldSet unknownFields;\n @java.lang.Override\n public final com.google.protobuf.UnknownFieldSet\n getUnknownFields() {\n return this.unknownFields;\n }\n private Extension(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n initFields();\n int mutable_bitField0_ = 0;\n com.google.protobuf.UnknownFieldSet.Builder unknownFields =\n com.google.protobuf.UnknownFieldSet.newBuilder();\n try {\n boolean done = false;\n while (!done) {\n int tag = input.readTag();\n switch (tag) {\n case 0:\n done = true;\n break;\n default: {\n if (!parseUnknownField(input, unknownFields,\n extensionRegistry, tag)) {\n done = true;\n }\n break;\n }\n case 10: {\n bitField0_ |= 0x00000001;\n id_ = input.readBytes();\n break;\n }\n case 18: {\n bitField0_ |= 0x00000002;\n data_ = input.readBytes();\n break;\n }\n case 24: {\n bitField0_ |= 0x00000004;\n mandatory_ = input.readBool();\n break;\n }\n }\n }\n } catch (com.google.protobuf.InvalidProtocolBufferException e) {\n throw e.setUnfinishedMessage(this);\n } catch (java.io.IOException e) {\n throw new com.google.protobuf.InvalidProtocolBufferException(\n e.getMessage()).setUnfinishedMessage(this);\n } finally {\n this.unknownFields = unknownFields.build();\n makeExtensionsImmutable();\n }\n }\n public static final com.google.protobuf.Descriptors.Descriptor\n getDescriptor() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_Extension_descriptor;\n }\n\n protected com.google.protobuf.GeneratedMessage.FieldAccessorTable\n internalGetFieldAccessorTable() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_Extension_fieldAccessorTable\n .ensureFieldAccessorsInitialized(\n org.bitcoinj.wallet.Protos.Extension.class, org.bitcoinj.wallet.Protos.Extension.Builder.class);\n }\n\n public static com.google.protobuf.Parser<Extension> PARSER =\n new com.google.protobuf.AbstractParser<Extension>() {\n public Extension parsePartialFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return new Extension(input, extensionRegistry);\n }\n };\n\n @java.lang.Override\n public com.google.protobuf.Parser<Extension> getParserForType() {\n return PARSER;\n }\n\n private int bitField0_;\n // required string id = 1;\n public static final int ID_FIELD_NUMBER = 1;\n private java.lang.Object id_;\n /**\n * <code>required string id = 1;</code>\n *\n * <pre>\n * like org.whatever.foo.bar\n * </pre>\n */\n public boolean hasId() {\n return ((bitField0_ & 0x00000001) == 0x00000001);\n }\n /**\n * <code>required string id = 1;</code>\n *\n * <pre>\n * like org.whatever.foo.bar\n * </pre>\n */\n public java.lang.String getId() {\n java.lang.Object ref = id_;\n if (ref instanceof java.lang.String) {\n return (java.lang.String) ref;\n } else {\n com.google.protobuf.ByteString bs = \n (com.google.protobuf.ByteString) ref;\n java.lang.String s = bs.toStringUtf8();\n if (bs.isValidUtf8()) {\n id_ = s;\n }\n return s;\n }\n }\n /**\n * <code>required string id = 1;</code>\n *\n * <pre>\n * like org.whatever.foo.bar\n * </pre>\n */\n public com.google.protobuf.ByteString\n getIdBytes() {\n java.lang.Object ref = id_;\n if (ref instanceof java.lang.String) {\n com.google.protobuf.ByteString b = \n com.google.protobuf.ByteString.copyFromUtf8(\n (java.lang.String) ref);\n id_ = b;\n return b;\n } else {\n return (com.google.protobuf.ByteString) ref;\n }\n }\n\n // required bytes data = 2;\n public static final int DATA_FIELD_NUMBER = 2;\n private com.google.protobuf.ByteString data_;\n /**\n * <code>required bytes data = 2;</code>\n */\n public boolean hasData() {\n return ((bitField0_ & 0x00000002) == 0x00000002);\n }\n /**\n * <code>required bytes data = 2;</code>\n */\n public com.google.protobuf.ByteString getData() {\n return data_;\n }\n\n // required bool mandatory = 3;\n public static final int MANDATORY_FIELD_NUMBER = 3;\n private boolean mandatory_;\n /**\n * <code>required bool mandatory = 3;</code>\n *\n * <pre>\n * If we do not understand a mandatory extension, abort to prevent data loss.\n * For example, this could be applied to a new type of holding, such as a contract, where\n * dropping of an extension in a read/write cycle could cause loss of value.\n * </pre>\n */\n public boolean hasMandatory() {\n return ((bitField0_ & 0x00000004) == 0x00000004);\n }\n /**\n * <code>required bool mandatory = 3;</code>\n *\n * <pre>\n * If we do not understand a mandatory extension, abort to prevent data loss.\n * For example, this could be applied to a new type of holding, such as a contract, where\n * dropping of an extension in a read/write cycle could cause loss of value.\n * </pre>\n */\n public boolean getMandatory() {\n return mandatory_;\n }\n\n private void initFields() {\n id_ = \"\";\n data_ = com.google.protobuf.ByteString.EMPTY;\n mandatory_ = false;\n }\n private byte memoizedIsInitialized = -1;\n public final boolean isInitialized() {\n byte isInitialized = memoizedIsInitialized;\n if (isInitialized != -1) return isInitialized == 1;\n\n if (!hasId()) {\n memoizedIsInitialized = 0;\n return false;\n }\n if (!hasData()) {\n memoizedIsInitialized = 0;\n return false;\n }\n if (!hasMandatory()) {\n memoizedIsInitialized = 0;\n return false;\n }\n memoizedIsInitialized = 1;\n return true;\n }\n\n public void writeTo(com.google.protobuf.CodedOutputStream output)\n throws java.io.IOException {\n getSerializedSize();\n if (((bitField0_ & 0x00000001) == 0x00000001)) {\n output.writeBytes(1, getIdBytes());\n }\n if (((bitField0_ & 0x00000002) == 0x00000002)) {\n output.writeBytes(2, data_);\n }\n if (((bitField0_ & 0x00000004) == 0x00000004)) {\n output.writeBool(3, mandatory_);\n }\n getUnknownFields().writeTo(output);\n }\n\n private int memoizedSerializedSize = -1;\n public int getSerializedSize() {\n int size = memoizedSerializedSize;\n if (size != -1) return size;\n\n size = 0;\n if (((bitField0_ & 0x00000001) == 0x00000001)) {\n size += com.google.protobuf.CodedOutputStream\n .computeBytesSize(1, getIdBytes());\n }\n if (((bitField0_ & 0x00000002) == 0x00000002)) {\n size += com.google.protobuf.CodedOutputStream\n .computeBytesSize(2, data_);\n }\n if (((bitField0_ & 0x00000004) == 0x00000004)) {\n size += com.google.protobuf.CodedOutputStream\n .computeBoolSize(3, mandatory_);\n }\n size += getUnknownFields().getSerializedSize();\n memoizedSerializedSize = size;\n return size;\n }\n\n private static final long serialVersionUID = 0L;\n @java.lang.Override\n protected java.lang.Object writeReplace()\n throws java.io.ObjectStreamException {\n return super.writeReplace();\n }\n\n public static org.bitcoinj.wallet.Protos.Extension parseFrom(\n com.google.protobuf.ByteString data)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n public static org.bitcoinj.wallet.Protos.Extension parseFrom(\n com.google.protobuf.ByteString data,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n public static org.bitcoinj.wallet.Protos.Extension parseFrom(byte[] data)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n public static org.bitcoinj.wallet.Protos.Extension parseFrom(\n byte[] data,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n public static org.bitcoinj.wallet.Protos.Extension parseFrom(java.io.InputStream input)\n throws java.io.IOException {\n return PARSER.parseFrom(input);\n }\n public static org.bitcoinj.wallet.Protos.Extension parseFrom(\n java.io.InputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return PARSER.parseFrom(input, extensionRegistry);\n }\n public static org.bitcoinj.wallet.Protos.Extension parseDelimitedFrom(java.io.InputStream input)\n throws java.io.IOException {\n return PARSER.parseDelimitedFrom(input);\n }\n public static org.bitcoinj.wallet.Protos.Extension parseDelimitedFrom(\n java.io.InputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return PARSER.parseDelimitedFrom(input, extensionRegistry);\n }\n public static org.bitcoinj.wallet.Protos.Extension parseFrom(\n com.google.protobuf.CodedInputStream input)\n throws java.io.IOException {\n return PARSER.parseFrom(input);\n }\n public static org.bitcoinj.wallet.Protos.Extension parseFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return PARSER.parseFrom(input, extensionRegistry);\n }\n\n public static Builder newBuilder() { return Builder.create(); }\n public Builder newBuilderForType() { return newBuilder(); }\n public static Builder newBuilder(org.bitcoinj.wallet.Protos.Extension prototype) {\n return newBuilder().mergeFrom(prototype);\n }\n public Builder toBuilder() { return newBuilder(this); }\n\n @java.lang.Override\n protected Builder newBuilderForType(\n com.google.protobuf.GeneratedMessage.BuilderParent parent) {\n Builder builder = new Builder(parent);\n return builder;\n }\n /**\n * Protobuf type {@code wallet.Extension}\n *\n * <pre>\n ** An extension to the wallet \n * </pre>\n */\n public static final class Builder extends\n com.google.protobuf.GeneratedMessage.Builder<Builder>\n implements org.bitcoinj.wallet.Protos.ExtensionOrBuilder {\n public static final com.google.protobuf.Descriptors.Descriptor\n getDescriptor() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_Extension_descriptor;\n }\n\n protected com.google.protobuf.GeneratedMessage.FieldAccessorTable\n internalGetFieldAccessorTable() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_Extension_fieldAccessorTable\n .ensureFieldAccessorsInitialized(\n org.bitcoinj.wallet.Protos.Extension.class, org.bitcoinj.wallet.Protos.Extension.Builder.class);\n }\n\n // Construct using org.bitcoinj.wallet.Protos.Extension.newBuilder()\n private Builder() {\n maybeForceBuilderInitialization();\n }\n\n private Builder(\n com.google.protobuf.GeneratedMessage.BuilderParent parent) {\n super(parent);\n maybeForceBuilderInitialization();\n }\n private void maybeForceBuilderInitialization() {\n if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {\n }\n }\n private static Builder create() {\n return new Builder();\n }\n\n public Builder clear() {\n super.clear();\n id_ = \"\";\n bitField0_ = (bitField0_ & ~0x00000001);\n data_ = com.google.protobuf.ByteString.EMPTY;\n bitField0_ = (bitField0_ & ~0x00000002);\n mandatory_ = false;\n bitField0_ = (bitField0_ & ~0x00000004);\n return this;\n }\n\n public Builder clone() {\n return create().mergeFrom(buildPartial());\n }\n\n public com.google.protobuf.Descriptors.Descriptor\n getDescriptorForType() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_Extension_descriptor;\n }\n\n public org.bitcoinj.wallet.Protos.Extension getDefaultInstanceForType() {\n return org.bitcoinj.wallet.Protos.Extension.getDefaultInstance();\n }\n\n public org.bitcoinj.wallet.Protos.Extension build() {\n org.bitcoinj.wallet.Protos.Extension result = buildPartial();\n if (!result.isInitialized()) {\n throw newUninitializedMessageException(result);\n }\n return result;\n }\n\n public org.bitcoinj.wallet.Protos.Extension buildPartial() {\n org.bitcoinj.wallet.Protos.Extension result = new org.bitcoinj.wallet.Protos.Extension(this);\n int from_bitField0_ = bitField0_;\n int to_bitField0_ = 0;\n if (((from_bitField0_ & 0x00000001) == 0x00000001)) {\n to_bitField0_ |= 0x00000001;\n }\n result.id_ = id_;\n if (((from_bitField0_ & 0x00000002) == 0x00000002)) {\n to_bitField0_ |= 0x00000002;\n }\n result.data_ = data_;\n if (((from_bitField0_ & 0x00000004) == 0x00000004)) {\n to_bitField0_ |= 0x00000004;\n }\n result.mandatory_ = mandatory_;\n result.bitField0_ = to_bitField0_;\n onBuilt();\n return result;\n }\n\n public Builder mergeFrom(com.google.protobuf.Message other) {\n if (other instanceof org.bitcoinj.wallet.Protos.Extension) {\n return mergeFrom((org.bitcoinj.wallet.Protos.Extension)other);\n } else {\n super.mergeFrom(other);\n return this;\n }\n }\n\n public Builder mergeFrom(org.bitcoinj.wallet.Protos.Extension other) {\n if (other == org.bitcoinj.wallet.Protos.Extension.getDefaultInstance()) return this;\n if (other.hasId()) {\n bitField0_ |= 0x00000001;\n id_ = other.id_;\n onChanged();\n }\n if (other.hasData()) {\n setData(other.getData());\n }\n if (other.hasMandatory()) {\n setMandatory(other.getMandatory());\n }\n this.mergeUnknownFields(other.getUnknownFields());\n return this;\n }\n\n public final boolean isInitialized() {\n if (!hasId()) {\n \n return false;\n }\n if (!hasData()) {\n \n return false;\n }\n if (!hasMandatory()) {\n \n return false;\n }\n return true;\n }\n\n public Builder mergeFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n org.bitcoinj.wallet.Protos.Extension parsedMessage = null;\n try {\n parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);\n } catch (com.google.protobuf.InvalidProtocolBufferException e) {\n parsedMessage = (org.bitcoinj.wallet.Protos.Extension) e.getUnfinishedMessage();\n throw e;\n } finally {\n if (parsedMessage != null) {\n mergeFrom(parsedMessage);\n }\n }\n return this;\n }\n private int bitField0_;\n\n // required string id = 1;\n private java.lang.Object id_ = \"\";\n /**\n * <code>required string id = 1;</code>\n *\n * <pre>\n * like org.whatever.foo.bar\n * </pre>\n */\n public boolean hasId() {\n return ((bitField0_ & 0x00000001) == 0x00000001);\n }\n /**\n * <code>required string id = 1;</code>\n *\n * <pre>\n * like org.whatever.foo.bar\n * </pre>\n */\n public java.lang.String getId() {\n java.lang.Object ref = id_;\n if (!(ref instanceof java.lang.String)) {\n java.lang.String s = ((com.google.protobuf.ByteString) ref)\n .toStringUtf8();\n id_ = s;\n return s;\n } else {\n return (java.lang.String) ref;\n }\n }\n /**\n * <code>required string id = 1;</code>\n *\n * <pre>\n * like org.whatever.foo.bar\n * </pre>\n */\n public com.google.protobuf.ByteString\n getIdBytes() {\n java.lang.Object ref = id_;\n if (ref instanceof String) {\n com.google.protobuf.ByteString b = \n com.google.protobuf.ByteString.copyFromUtf8(\n (java.lang.String) ref);\n id_ = b;\n return b;\n } else {\n return (com.google.protobuf.ByteString) ref;\n }\n }\n /**\n * <code>required string id = 1;</code>\n *\n * <pre>\n * like org.whatever.foo.bar\n * </pre>\n */\n public Builder setId(\n java.lang.String value) {\n if (value == null) {\n throw new NullPointerException();\n }\n bitField0_ |= 0x00000001;\n id_ = value;\n onChanged();\n return this;\n }\n /**\n * <code>required string id = 1;</code>\n *\n * <pre>\n * like org.whatever.foo.bar\n * </pre>\n */\n public Builder clearId() {\n bitField0_ = (bitField0_ & ~0x00000001);\n id_ = getDefaultInstance().getId();\n onChanged();\n return this;\n }\n /**\n * <code>required string id = 1;</code>\n *\n * <pre>\n * like org.whatever.foo.bar\n * </pre>\n */\n public Builder setIdBytes(\n com.google.protobuf.ByteString value) {\n if (value == null) {\n throw new NullPointerException();\n }\n bitField0_ |= 0x00000001;\n id_ = value;\n onChanged();\n return this;\n }\n\n // required bytes data = 2;\n private com.google.protobuf.ByteString data_ = com.google.protobuf.ByteString.EMPTY;\n /**\n * <code>required bytes data = 2;</code>\n */\n public boolean hasData() {\n return ((bitField0_ & 0x00000002) == 0x00000002);\n }\n /**\n * <code>required bytes data = 2;</code>\n */\n public com.google.protobuf.ByteString getData() {\n return data_;\n }\n /**\n * <code>required bytes data = 2;</code>\n */\n public Builder setData(com.google.protobuf.ByteString value) {\n if (value == null) {\n throw new NullPointerException();\n }\n bitField0_ |= 0x00000002;\n data_ = value;\n onChanged();\n return this;\n }\n /**\n * <code>required bytes data = 2;</code>\n */\n public Builder clearData() {\n bitField0_ = (bitField0_ & ~0x00000002);\n data_ = getDefaultInstance().getData();\n onChanged();\n return this;\n }\n\n // required bool mandatory = 3;\n private boolean mandatory_ ;\n /**\n * <code>required bool mandatory = 3;</code>\n *\n * <pre>\n * If we do not understand a mandatory extension, abort to prevent data loss.\n * For example, this could be applied to a new type of holding, such as a contract, where\n * dropping of an extension in a read/write cycle could cause loss of value.\n * </pre>\n */\n public boolean hasMandatory() {\n return ((bitField0_ & 0x00000004) == 0x00000004);\n }\n /**\n * <code>required bool mandatory = 3;</code>\n *\n * <pre>\n * If we do not understand a mandatory extension, abort to prevent data loss.\n * For example, this could be applied to a new type of holding, such as a contract, where\n * dropping of an extension in a read/write cycle could cause loss of value.\n * </pre>\n */\n public boolean getMandatory() {\n return mandatory_;\n }\n /**\n * <code>required bool mandatory = 3;</code>\n *\n * <pre>\n * If we do not understand a mandatory extension, abort to prevent data loss.\n * For example, this could be applied to a new type of holding, such as a contract, where\n * dropping of an extension in a read/write cycle could cause loss of value.\n * </pre>\n */\n public Builder setMandatory(boolean value) {\n bitField0_ |= 0x00000004;\n mandatory_ = value;\n onChanged();\n return this;\n }\n /**\n * <code>required bool mandatory = 3;</code>\n *\n * <pre>\n * If we do not understand a mandatory extension, abort to prevent data loss.\n * For example, this could be applied to a new type of holding, such as a contract, where\n * dropping of an extension in a read/write cycle could cause loss of value.\n * </pre>\n */\n public Builder clearMandatory() {\n bitField0_ = (bitField0_ & ~0x00000004);\n mandatory_ = false;\n onChanged();\n return this;\n }\n\n // @@protoc_insertion_point(builder_scope:wallet.Extension)\n }\n\n static {\n defaultInstance = new Extension(true);\n defaultInstance.initFields();\n }\n\n // @@protoc_insertion_point(class_scope:wallet.Extension)\n }\n\n public interface WalletOrBuilder\n extends com.google.protobuf.MessageOrBuilder {\n\n // required string network_identifier = 1;\n /**\n * <code>required string network_identifier = 1;</code>\n *\n * <pre>\n * the network used by this wallet\n * </pre>\n */\n boolean hasNetworkIdentifier();\n /**\n * <code>required string network_identifier = 1;</code>\n *\n * <pre>\n * the network used by this wallet\n * </pre>\n */\n java.lang.String getNetworkIdentifier();\n /**\n * <code>required string network_identifier = 1;</code>\n *\n * <pre>\n * the network used by this wallet\n * </pre>\n */\n com.google.protobuf.ByteString\n getNetworkIdentifierBytes();\n\n // optional bytes last_seen_block_hash = 2;\n /**\n * <code>optional bytes last_seen_block_hash = 2;</code>\n *\n * <pre>\n * The SHA256 hash of the head of the best chain seen by this wallet.\n * </pre>\n */\n boolean hasLastSeenBlockHash();\n /**\n * <code>optional bytes last_seen_block_hash = 2;</code>\n *\n * <pre>\n * The SHA256 hash of the head of the best chain seen by this wallet.\n * </pre>\n */\n com.google.protobuf.ByteString getLastSeenBlockHash();\n\n // optional uint32 last_seen_block_height = 12;\n /**\n * <code>optional uint32 last_seen_block_height = 12;</code>\n *\n * <pre>\n * The height in the chain of the last seen block.\n * </pre>\n */\n boolean hasLastSeenBlockHeight();\n /**\n * <code>optional uint32 last_seen_block_height = 12;</code>\n *\n * <pre>\n * The height in the chain of the last seen block.\n * </pre>\n */\n int getLastSeenBlockHeight();\n\n // optional int64 last_seen_block_time_secs = 14;\n /**\n * <code>optional int64 last_seen_block_time_secs = 14;</code>\n */\n boolean hasLastSeenBlockTimeSecs();\n /**\n * <code>optional int64 last_seen_block_time_secs = 14;</code>\n */\n long getLastSeenBlockTimeSecs();\n\n // repeated .wallet.Key key = 3;\n /**\n * <code>repeated .wallet.Key key = 3;</code>\n */\n java.util.List<org.bitcoinj.wallet.Protos.Key> \n getKeyList();\n /**\n * <code>repeated .wallet.Key key = 3;</code>\n */\n org.bitcoinj.wallet.Protos.Key getKey(int index);\n /**\n * <code>repeated .wallet.Key key = 3;</code>\n */\n int getKeyCount();\n /**\n * <code>repeated .wallet.Key key = 3;</code>\n */\n java.util.List<? extends org.bitcoinj.wallet.Protos.KeyOrBuilder> \n getKeyOrBuilderList();\n /**\n * <code>repeated .wallet.Key key = 3;</code>\n */\n org.bitcoinj.wallet.Protos.KeyOrBuilder getKeyOrBuilder(\n int index);\n\n // repeated .wallet.Transaction transaction = 4;\n /**\n * <code>repeated .wallet.Transaction transaction = 4;</code>\n */\n java.util.List<org.bitcoinj.wallet.Protos.Transaction> \n getTransactionList();\n /**\n * <code>repeated .wallet.Transaction transaction = 4;</code>\n */\n org.bitcoinj.wallet.Protos.Transaction getTransaction(int index);\n /**\n * <code>repeated .wallet.Transaction transaction = 4;</code>\n */\n int getTransactionCount();\n /**\n * <code>repeated .wallet.Transaction transaction = 4;</code>\n */\n java.util.List<? extends org.bitcoinj.wallet.Protos.TransactionOrBuilder> \n getTransactionOrBuilderList();\n /**\n * <code>repeated .wallet.Transaction transaction = 4;</code>\n */\n org.bitcoinj.wallet.Protos.TransactionOrBuilder getTransactionOrBuilder(\n int index);\n\n // repeated .wallet.Script watched_script = 15;\n /**\n * <code>repeated .wallet.Script watched_script = 15;</code>\n */\n java.util.List<org.bitcoinj.wallet.Protos.Script> \n getWatchedScriptList();\n /**\n * <code>repeated .wallet.Script watched_script = 15;</code>\n */\n org.bitcoinj.wallet.Protos.Script getWatchedScript(int index);\n /**\n * <code>repeated .wallet.Script watched_script = 15;</code>\n */\n int getWatchedScriptCount();\n /**\n * <code>repeated .wallet.Script watched_script = 15;</code>\n */\n java.util.List<? extends org.bitcoinj.wallet.Protos.ScriptOrBuilder> \n getWatchedScriptOrBuilderList();\n /**\n * <code>repeated .wallet.Script watched_script = 15;</code>\n */\n org.bitcoinj.wallet.Protos.ScriptOrBuilder getWatchedScriptOrBuilder(\n int index);\n\n // optional .wallet.Wallet.EncryptionType encryption_type = 5 [default = UNENCRYPTED];\n /**\n * <code>optional .wallet.Wallet.EncryptionType encryption_type = 5 [default = UNENCRYPTED];</code>\n */\n boolean hasEncryptionType();\n /**\n * <code>optional .wallet.Wallet.EncryptionType encryption_type = 5 [default = UNENCRYPTED];</code>\n */\n org.bitcoinj.wallet.Protos.Wallet.EncryptionType getEncryptionType();\n\n // optional .wallet.ScryptParameters encryption_parameters = 6;\n /**\n * <code>optional .wallet.ScryptParameters encryption_parameters = 6;</code>\n */\n boolean hasEncryptionParameters();\n /**\n * <code>optional .wallet.ScryptParameters encryption_parameters = 6;</code>\n */\n org.bitcoinj.wallet.Protos.ScryptParameters getEncryptionParameters();\n /**\n * <code>optional .wallet.ScryptParameters encryption_parameters = 6;</code>\n */\n org.bitcoinj.wallet.Protos.ScryptParametersOrBuilder getEncryptionParametersOrBuilder();\n\n // optional int32 version = 7;\n /**\n * <code>optional int32 version = 7;</code>\n *\n * <pre>\n * The version number of the wallet - used to detect wallets that were produced in the future\n * (i.e the wallet may contain some future format this protobuf/ code does not know about)\n * </pre>\n */\n boolean hasVersion();\n /**\n * <code>optional int32 version = 7;</code>\n *\n * <pre>\n * The version number of the wallet - used to detect wallets that were produced in the future\n * (i.e the wallet may contain some future format this protobuf/ code does not know about)\n * </pre>\n */\n int getVersion();\n\n // repeated .wallet.Extension extension = 10;\n /**\n * <code>repeated .wallet.Extension extension = 10;</code>\n */\n java.util.List<org.bitcoinj.wallet.Protos.Extension> \n getExtensionList();\n /**\n * <code>repeated .wallet.Extension extension = 10;</code>\n */\n org.bitcoinj.wallet.Protos.Extension getExtension(int index);\n /**\n * <code>repeated .wallet.Extension extension = 10;</code>\n */\n int getExtensionCount();\n /**\n * <code>repeated .wallet.Extension extension = 10;</code>\n */\n java.util.List<? extends org.bitcoinj.wallet.Protos.ExtensionOrBuilder> \n getExtensionOrBuilderList();\n /**\n * <code>repeated .wallet.Extension extension = 10;</code>\n */\n org.bitcoinj.wallet.Protos.ExtensionOrBuilder getExtensionOrBuilder(\n int index);\n\n // optional string description = 11;\n /**\n * <code>optional string description = 11;</code>\n *\n * <pre>\n * A UTF8 encoded text description of the wallet that is intended for end user provided text.\n * </pre>\n */\n boolean hasDescription();\n /**\n * <code>optional string description = 11;</code>\n *\n * <pre>\n * A UTF8 encoded text description of the wallet that is intended for end user provided text.\n * </pre>\n */\n java.lang.String getDescription();\n /**\n * <code>optional string description = 11;</code>\n *\n * <pre>\n * A UTF8 encoded text description of the wallet that is intended for end user provided text.\n * </pre>\n */\n com.google.protobuf.ByteString\n getDescriptionBytes();\n\n // optional uint64 key_rotation_time = 13;\n /**\n * <code>optional uint64 key_rotation_time = 13;</code>\n *\n * <pre>\n * UNIX time in seconds since the epoch. If set, then any keys created before this date are assumed to be no longer\n * wanted. Money sent to them will be re-spent automatically to the first key that was created after this time. It\n * can be used to recover a compromised wallet, or just as part of preventative defence-in-depth measures.\n * </pre>\n */\n boolean hasKeyRotationTime();\n /**\n * <code>optional uint64 key_rotation_time = 13;</code>\n *\n * <pre>\n * UNIX time in seconds since the epoch. If set, then any keys created before this date are assumed to be no longer\n * wanted. Money sent to them will be re-spent automatically to the first key that was created after this time. It\n * can be used to recover a compromised wallet, or just as part of preventative defence-in-depth measures.\n * </pre>\n */\n long getKeyRotationTime();\n }\n /**\n * Protobuf type {@code wallet.Wallet}\n *\n * <pre>\n ** A bitcoin wallet \n * </pre>\n */\n public static final class Wallet extends\n com.google.protobuf.GeneratedMessage\n implements WalletOrBuilder {\n // Use Wallet.newBuilder() to construct.\n private Wallet(com.google.protobuf.GeneratedMessage.Builder<?> builder) {\n super(builder);\n this.unknownFields = builder.getUnknownFields();\n }\n private Wallet(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }\n\n private static final Wallet defaultInstance;\n public static Wallet getDefaultInstance() {\n return defaultInstance;\n }\n\n public Wallet getDefaultInstanceForType() {\n return defaultInstance;\n }\n\n private final com.google.protobuf.UnknownFieldSet unknownFields;\n @java.lang.Override\n public final com.google.protobuf.UnknownFieldSet\n getUnknownFields() {\n return this.unknownFields;\n }\n private Wallet(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n initFields();\n int mutable_bitField0_ = 0;\n com.google.protobuf.UnknownFieldSet.Builder unknownFields =\n com.google.protobuf.UnknownFieldSet.newBuilder();\n try {\n boolean done = false;\n while (!done) {\n int tag = input.readTag();\n switch (tag) {\n case 0:\n done = true;\n break;\n default: {\n if (!parseUnknownField(input, unknownFields,\n extensionRegistry, tag)) {\n done = true;\n }\n break;\n }\n case 10: {\n bitField0_ |= 0x00000001;\n networkIdentifier_ = input.readBytes();\n break;\n }\n case 18: {\n bitField0_ |= 0x00000002;\n lastSeenBlockHash_ = input.readBytes();\n break;\n }\n case 26: {\n if (!((mutable_bitField0_ & 0x00000010) == 0x00000010)) {\n key_ = new java.util.ArrayList<org.bitcoinj.wallet.Protos.Key>();\n mutable_bitField0_ |= 0x00000010;\n }\n key_.add(input.readMessage(org.bitcoinj.wallet.Protos.Key.PARSER, extensionRegistry));\n break;\n }\n case 34: {\n if (!((mutable_bitField0_ & 0x00000020) == 0x00000020)) {\n transaction_ = new java.util.ArrayList<org.bitcoinj.wallet.Protos.Transaction>();\n mutable_bitField0_ |= 0x00000020;\n }\n transaction_.add(input.readMessage(org.bitcoinj.wallet.Protos.Transaction.PARSER, extensionRegistry));\n break;\n }\n case 40: {\n int rawValue = input.readEnum();\n org.bitcoinj.wallet.Protos.Wallet.EncryptionType value = org.bitcoinj.wallet.Protos.Wallet.EncryptionType.valueOf(rawValue);\n if (value == null) {\n unknownFields.mergeVarintField(5, rawValue);\n } else {\n bitField0_ |= 0x00000010;\n encryptionType_ = value;\n }\n break;\n }\n case 50: {\n org.bitcoinj.wallet.Protos.ScryptParameters.Builder subBuilder = null;\n if (((bitField0_ & 0x00000020) == 0x00000020)) {\n subBuilder = encryptionParameters_.toBuilder();\n }\n encryptionParameters_ = input.readMessage(org.bitcoinj.wallet.Protos.ScryptParameters.PARSER, extensionRegistry);\n if (subBuilder != null) {\n subBuilder.mergeFrom(encryptionParameters_);\n encryptionParameters_ = subBuilder.buildPartial();\n }\n bitField0_ |= 0x00000020;\n break;\n }\n case 56: {\n bitField0_ |= 0x00000040;\n version_ = input.readInt32();\n break;\n }\n case 82: {\n if (!((mutable_bitField0_ & 0x00000400) == 0x00000400)) {\n extension_ = new java.util.ArrayList<org.bitcoinj.wallet.Protos.Extension>();\n mutable_bitField0_ |= 0x00000400;\n }\n extension_.add(input.readMessage(org.bitcoinj.wallet.Protos.Extension.PARSER, extensionRegistry));\n break;\n }\n case 90: {\n bitField0_ |= 0x00000080;\n description_ = input.readBytes();\n break;\n }\n case 96: {\n bitField0_ |= 0x00000004;\n lastSeenBlockHeight_ = input.readUInt32();\n break;\n }\n case 104: {\n bitField0_ |= 0x00000100;\n keyRotationTime_ = input.readUInt64();\n break;\n }\n case 112: {\n bitField0_ |= 0x00000008;\n lastSeenBlockTimeSecs_ = input.readInt64();\n break;\n }\n case 122: {\n if (!((mutable_bitField0_ & 0x00000040) == 0x00000040)) {\n watchedScript_ = new java.util.ArrayList<org.bitcoinj.wallet.Protos.Script>();\n mutable_bitField0_ |= 0x00000040;\n }\n watchedScript_.add(input.readMessage(org.bitcoinj.wallet.Protos.Script.PARSER, extensionRegistry));\n break;\n }\n }\n }\n } catch (com.google.protobuf.InvalidProtocolBufferException e) {\n throw e.setUnfinishedMessage(this);\n } catch (java.io.IOException e) {\n throw new com.google.protobuf.InvalidProtocolBufferException(\n e.getMessage()).setUnfinishedMessage(this);\n } finally {\n if (((mutable_bitField0_ & 0x00000010) == 0x00000010)) {\n key_ = java.util.Collections.unmodifiableList(key_);\n }\n if (((mutable_bitField0_ & 0x00000020) == 0x00000020)) {\n transaction_ = java.util.Collections.unmodifiableList(transaction_);\n }\n if (((mutable_bitField0_ & 0x00000400) == 0x00000400)) {\n extension_ = java.util.Collections.unmodifiableList(extension_);\n }\n if (((mutable_bitField0_ & 0x00000040) == 0x00000040)) {\n watchedScript_ = java.util.Collections.unmodifiableList(watchedScript_);\n }\n this.unknownFields = unknownFields.build();\n makeExtensionsImmutable();\n }\n }\n public static final com.google.protobuf.Descriptors.Descriptor\n getDescriptor() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_Wallet_descriptor;\n }\n\n protected com.google.protobuf.GeneratedMessage.FieldAccessorTable\n internalGetFieldAccessorTable() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_Wallet_fieldAccessorTable\n .ensureFieldAccessorsInitialized(\n org.bitcoinj.wallet.Protos.Wallet.class, org.bitcoinj.wallet.Protos.Wallet.Builder.class);\n }\n\n public static com.google.protobuf.Parser<Wallet> PARSER =\n new com.google.protobuf.AbstractParser<Wallet>() {\n public Wallet parsePartialFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return new Wallet(input, extensionRegistry);\n }\n };\n\n @java.lang.Override\n public com.google.protobuf.Parser<Wallet> getParserForType() {\n return PARSER;\n }\n\n /**\n * Protobuf enum {@code wallet.Wallet.EncryptionType}\n *\n * <pre>\n **\n * The encryption type of the wallet.\n *\n * The encryption type is UNENCRYPTED for wallets where the wallet does not support encryption - wallets prior to\n * encryption support are grandfathered in as this wallet type.\n * When a wallet is ENCRYPTED_SCRYPT_AES the keys are either encrypted with the wallet password or are unencrypted.\n * </pre>\n */\n public enum EncryptionType\n implements com.google.protobuf.ProtocolMessageEnum {\n /**\n * <code>UNENCRYPTED = 1;</code>\n *\n * <pre>\n * All keys in the wallet are unencrypted\n * </pre>\n */\n UNENCRYPTED(0, 1),\n /**\n * <code>ENCRYPTED_SCRYPT_AES = 2;</code>\n *\n * <pre>\n * All keys are encrypted with a passphrase based KDF of scrypt and AES encryption\n * </pre>\n */\n ENCRYPTED_SCRYPT_AES(1, 2),\n ;\n\n /**\n * <code>UNENCRYPTED = 1;</code>\n *\n * <pre>\n * All keys in the wallet are unencrypted\n * </pre>\n */\n public static final int UNENCRYPTED_VALUE = 1;\n /**\n * <code>ENCRYPTED_SCRYPT_AES = 2;</code>\n *\n * <pre>\n * All keys are encrypted with a passphrase based KDF of scrypt and AES encryption\n * </pre>\n */\n public static final int ENCRYPTED_SCRYPT_AES_VALUE = 2;\n\n\n public final int getNumber() { return value; }\n\n public static EncryptionType valueOf(int value) {\n switch (value) {\n case 1: return UNENCRYPTED;\n case 2: return ENCRYPTED_SCRYPT_AES;\n default: return null;\n }\n }\n\n public static com.google.protobuf.Internal.EnumLiteMap<EncryptionType>\n internalGetValueMap() {\n return internalValueMap;\n }\n private static com.google.protobuf.Internal.EnumLiteMap<EncryptionType>\n internalValueMap =\n new com.google.protobuf.Internal.EnumLiteMap<EncryptionType>() {\n public EncryptionType findValueByNumber(int number) {\n return EncryptionType.valueOf(number);\n }\n };\n\n public final com.google.protobuf.Descriptors.EnumValueDescriptor\n getValueDescriptor() {\n return getDescriptor().getValues().get(index);\n }\n public final com.google.protobuf.Descriptors.EnumDescriptor\n getDescriptorForType() {\n return getDescriptor();\n }\n public static final com.google.protobuf.Descriptors.EnumDescriptor\n getDescriptor() {\n return org.bitcoinj.wallet.Protos.Wallet.getDescriptor().getEnumTypes().get(0);\n }\n\n private static final EncryptionType[] VALUES = values();\n\n public static EncryptionType valueOf(\n com.google.protobuf.Descriptors.EnumValueDescriptor desc) {\n if (desc.getType() != getDescriptor()) {\n throw new java.lang.IllegalArgumentException(\n \"EnumValueDescriptor is not for this type.\");\n }\n return VALUES[desc.getIndex()];\n }\n\n private final int index;\n private final int value;\n\n private EncryptionType(int index, int value) {\n this.index = index;\n this.value = value;\n }\n\n // @@protoc_insertion_point(enum_scope:wallet.Wallet.EncryptionType)\n }\n\n private int bitField0_;\n // required string network_identifier = 1;\n public static final int NETWORK_IDENTIFIER_FIELD_NUMBER = 1;\n private java.lang.Object networkIdentifier_;\n /**\n * <code>required string network_identifier = 1;</code>\n *\n * <pre>\n * the network used by this wallet\n * </pre>\n */\n public boolean hasNetworkIdentifier() {\n return ((bitField0_ & 0x00000001) == 0x00000001);\n }\n /**\n * <code>required string network_identifier = 1;</code>\n *\n * <pre>\n * the network used by this wallet\n * </pre>\n */\n public java.lang.String getNetworkIdentifier() {\n java.lang.Object ref = networkIdentifier_;\n if (ref instanceof java.lang.String) {\n return (java.lang.String) ref;\n } else {\n com.google.protobuf.ByteString bs = \n (com.google.protobuf.ByteString) ref;\n java.lang.String s = bs.toStringUtf8();\n if (bs.isValidUtf8()) {\n networkIdentifier_ = s;\n }\n return s;\n }\n }\n /**\n * <code>required string network_identifier = 1;</code>\n *\n * <pre>\n * the network used by this wallet\n * </pre>\n */\n public com.google.protobuf.ByteString\n getNetworkIdentifierBytes() {\n java.lang.Object ref = networkIdentifier_;\n if (ref instanceof java.lang.String) {\n com.google.protobuf.ByteString b = \n com.google.protobuf.ByteString.copyFromUtf8(\n (java.lang.String) ref);\n networkIdentifier_ = b;\n return b;\n } else {\n return (com.google.protobuf.ByteString) ref;\n }\n }\n\n // optional bytes last_seen_block_hash = 2;\n public static final int LAST_SEEN_BLOCK_HASH_FIELD_NUMBER = 2;\n private com.google.protobuf.ByteString lastSeenBlockHash_;\n /**\n * <code>optional bytes last_seen_block_hash = 2;</code>\n *\n * <pre>\n * The SHA256 hash of the head of the best chain seen by this wallet.\n * </pre>\n */\n public boolean hasLastSeenBlockHash() {\n return ((bitField0_ & 0x00000002) == 0x00000002);\n }\n /**\n * <code>optional bytes last_seen_block_hash = 2;</code>\n *\n * <pre>\n * The SHA256 hash of the head of the best chain seen by this wallet.\n * </pre>\n */\n public com.google.protobuf.ByteString getLastSeenBlockHash() {\n return lastSeenBlockHash_;\n }\n\n // optional uint32 last_seen_block_height = 12;\n public static final int LAST_SEEN_BLOCK_HEIGHT_FIELD_NUMBER = 12;\n private int lastSeenBlockHeight_;\n /**\n * <code>optional uint32 last_seen_block_height = 12;</code>\n *\n * <pre>\n * The height in the chain of the last seen block.\n * </pre>\n */\n public boolean hasLastSeenBlockHeight() {\n return ((bitField0_ & 0x00000004) == 0x00000004);\n }\n /**\n * <code>optional uint32 last_seen_block_height = 12;</code>\n *\n * <pre>\n * The height in the chain of the last seen block.\n * </pre>\n */\n public int getLastSeenBlockHeight() {\n return lastSeenBlockHeight_;\n }\n\n // optional int64 last_seen_block_time_secs = 14;\n public static final int LAST_SEEN_BLOCK_TIME_SECS_FIELD_NUMBER = 14;\n private long lastSeenBlockTimeSecs_;\n /**\n * <code>optional int64 last_seen_block_time_secs = 14;</code>\n */\n public boolean hasLastSeenBlockTimeSecs() {\n return ((bitField0_ & 0x00000008) == 0x00000008);\n }\n /**\n * <code>optional int64 last_seen_block_time_secs = 14;</code>\n */\n public long getLastSeenBlockTimeSecs() {\n return lastSeenBlockTimeSecs_;\n }\n\n // repeated .wallet.Key key = 3;\n public static final int KEY_FIELD_NUMBER = 3;\n private java.util.List<org.bitcoinj.wallet.Protos.Key> key_;\n /**\n * <code>repeated .wallet.Key key = 3;</code>\n */\n public java.util.List<org.bitcoinj.wallet.Protos.Key> getKeyList() {\n return key_;\n }\n /**\n * <code>repeated .wallet.Key key = 3;</code>\n */\n public java.util.List<? extends org.bitcoinj.wallet.Protos.KeyOrBuilder> \n getKeyOrBuilderList() {\n return key_;\n }\n /**\n * <code>repeated .wallet.Key key = 3;</code>\n */\n public int getKeyCount() {\n return key_.size();\n }\n /**\n * <code>repeated .wallet.Key key = 3;</code>\n */\n public org.bitcoinj.wallet.Protos.Key getKey(int index) {\n return key_.get(index);\n }\n /**\n * <code>repeated .wallet.Key key = 3;</code>\n */\n public org.bitcoinj.wallet.Protos.KeyOrBuilder getKeyOrBuilder(\n int index) {\n return key_.get(index);\n }\n\n // repeated .wallet.Transaction transaction = 4;\n public static final int TRANSACTION_FIELD_NUMBER = 4;\n private java.util.List<org.bitcoinj.wallet.Protos.Transaction> transaction_;\n /**\n * <code>repeated .wallet.Transaction transaction = 4;</code>\n */\n public java.util.List<org.bitcoinj.wallet.Protos.Transaction> getTransactionList() {\n return transaction_;\n }\n /**\n * <code>repeated .wallet.Transaction transaction = 4;</code>\n */\n public java.util.List<? extends org.bitcoinj.wallet.Protos.TransactionOrBuilder> \n getTransactionOrBuilderList() {\n return transaction_;\n }\n /**\n * <code>repeated .wallet.Transaction transaction = 4;</code>\n */\n public int getTransactionCount() {\n return transaction_.size();\n }\n /**\n * <code>repeated .wallet.Transaction transaction = 4;</code>\n */\n public org.bitcoinj.wallet.Protos.Transaction getTransaction(int index) {\n return transaction_.get(index);\n }\n /**\n * <code>repeated .wallet.Transaction transaction = 4;</code>\n */\n public org.bitcoinj.wallet.Protos.TransactionOrBuilder getTransactionOrBuilder(\n int index) {\n return transaction_.get(index);\n }\n\n // repeated .wallet.Script watched_script = 15;\n public static final int WATCHED_SCRIPT_FIELD_NUMBER = 15;\n private java.util.List<org.bitcoinj.wallet.Protos.Script> watchedScript_;\n /**\n * <code>repeated .wallet.Script watched_script = 15;</code>\n */\n public java.util.List<org.bitcoinj.wallet.Protos.Script> getWatchedScriptList() {\n return watchedScript_;\n }\n /**\n * <code>repeated .wallet.Script watched_script = 15;</code>\n */\n public java.util.List<? extends org.bitcoinj.wallet.Protos.ScriptOrBuilder> \n getWatchedScriptOrBuilderList() {\n return watchedScript_;\n }\n /**\n * <code>repeated .wallet.Script watched_script = 15;</code>\n */\n public int getWatchedScriptCount() {\n return watchedScript_.size();\n }\n /**\n * <code>repeated .wallet.Script watched_script = 15;</code>\n */\n public org.bitcoinj.wallet.Protos.Script getWatchedScript(int index) {\n return watchedScript_.get(index);\n }\n /**\n * <code>repeated .wallet.Script watched_script = 15;</code>\n */\n public org.bitcoinj.wallet.Protos.ScriptOrBuilder getWatchedScriptOrBuilder(\n int index) {\n return watchedScript_.get(index);\n }\n\n // optional .wallet.Wallet.EncryptionType encryption_type = 5 [default = UNENCRYPTED];\n public static final int ENCRYPTION_TYPE_FIELD_NUMBER = 5;\n private org.bitcoinj.wallet.Protos.Wallet.EncryptionType encryptionType_;\n /**\n * <code>optional .wallet.Wallet.EncryptionType encryption_type = 5 [default = UNENCRYPTED];</code>\n */\n public boolean hasEncryptionType() {\n return ((bitField0_ & 0x00000010) == 0x00000010);\n }\n /**\n * <code>optional .wallet.Wallet.EncryptionType encryption_type = 5 [default = UNENCRYPTED];</code>\n */\n public org.bitcoinj.wallet.Protos.Wallet.EncryptionType getEncryptionType() {\n return encryptionType_;\n }\n\n // optional .wallet.ScryptParameters encryption_parameters = 6;\n public static final int ENCRYPTION_PARAMETERS_FIELD_NUMBER = 6;\n private org.bitcoinj.wallet.Protos.ScryptParameters encryptionParameters_;\n /**\n * <code>optional .wallet.ScryptParameters encryption_parameters = 6;</code>\n */\n public boolean hasEncryptionParameters() {\n return ((bitField0_ & 0x00000020) == 0x00000020);\n }\n /**\n * <code>optional .wallet.ScryptParameters encryption_parameters = 6;</code>\n */\n public org.bitcoinj.wallet.Protos.ScryptParameters getEncryptionParameters() {\n return encryptionParameters_;\n }\n /**\n * <code>optional .wallet.ScryptParameters encryption_parameters = 6;</code>\n */\n public org.bitcoinj.wallet.Protos.ScryptParametersOrBuilder getEncryptionParametersOrBuilder() {\n return encryptionParameters_;\n }\n\n // optional int32 version = 7;\n public static final int VERSION_FIELD_NUMBER = 7;\n private int version_;\n /**\n * <code>optional int32 version = 7;</code>\n *\n * <pre>\n * The version number of the wallet - used to detect wallets that were produced in the future\n * (i.e the wallet may contain some future format this protobuf/ code does not know about)\n * </pre>\n */\n public boolean hasVersion() {\n return ((bitField0_ & 0x00000040) == 0x00000040);\n }\n /**\n * <code>optional int32 version = 7;</code>\n *\n * <pre>\n * The version number of the wallet - used to detect wallets that were produced in the future\n * (i.e the wallet may contain some future format this protobuf/ code does not know about)\n * </pre>\n */\n public int getVersion() {\n return version_;\n }\n\n // repeated .wallet.Extension extension = 10;\n public static final int EXTENSION_FIELD_NUMBER = 10;\n private java.util.List<org.bitcoinj.wallet.Protos.Extension> extension_;\n /**\n * <code>repeated .wallet.Extension extension = 10;</code>\n */\n public java.util.List<org.bitcoinj.wallet.Protos.Extension> getExtensionList() {\n return extension_;\n }\n /**\n * <code>repeated .wallet.Extension extension = 10;</code>\n */\n public java.util.List<? extends org.bitcoinj.wallet.Protos.ExtensionOrBuilder> \n getExtensionOrBuilderList() {\n return extension_;\n }\n /**\n * <code>repeated .wallet.Extension extension = 10;</code>\n */\n public int getExtensionCount() {\n return extension_.size();\n }\n /**\n * <code>repeated .wallet.Extension extension = 10;</code>\n */\n public org.bitcoinj.wallet.Protos.Extension getExtension(int index) {\n return extension_.get(index);\n }\n /**\n * <code>repeated .wallet.Extension extension = 10;</code>\n */\n public org.bitcoinj.wallet.Protos.ExtensionOrBuilder getExtensionOrBuilder(\n int index) {\n return extension_.get(index);\n }\n\n // optional string description = 11;\n public static final int DESCRIPTION_FIELD_NUMBER = 11;\n private java.lang.Object description_;\n /**\n * <code>optional string description = 11;</code>\n *\n * <pre>\n * A UTF8 encoded text description of the wallet that is intended for end user provided text.\n * </pre>\n */\n public boolean hasDescription() {\n return ((bitField0_ & 0x00000080) == 0x00000080);\n }\n /**\n * <code>optional string description = 11;</code>\n *\n * <pre>\n * A UTF8 encoded text description of the wallet that is intended for end user provided text.\n * </pre>\n */\n public java.lang.String getDescription() {\n java.lang.Object ref = description_;\n if (ref instanceof java.lang.String) {\n return (java.lang.String) ref;\n } else {\n com.google.protobuf.ByteString bs = \n (com.google.protobuf.ByteString) ref;\n java.lang.String s = bs.toStringUtf8();\n if (bs.isValidUtf8()) {\n description_ = s;\n }\n return s;\n }\n }\n /**\n * <code>optional string description = 11;</code>\n *\n * <pre>\n * A UTF8 encoded text description of the wallet that is intended for end user provided text.\n * </pre>\n */\n public com.google.protobuf.ByteString\n getDescriptionBytes() {\n java.lang.Object ref = description_;\n if (ref instanceof java.lang.String) {\n com.google.protobuf.ByteString b = \n com.google.protobuf.ByteString.copyFromUtf8(\n (java.lang.String) ref);\n description_ = b;\n return b;\n } else {\n return (com.google.protobuf.ByteString) ref;\n }\n }\n\n // optional uint64 key_rotation_time = 13;\n public static final int KEY_ROTATION_TIME_FIELD_NUMBER = 13;\n private long keyRotationTime_;\n /**\n * <code>optional uint64 key_rotation_time = 13;</code>\n *\n * <pre>\n * UNIX time in seconds since the epoch. If set, then any keys created before this date are assumed to be no longer\n * wanted. Money sent to them will be re-spent automatically to the first key that was created after this time. It\n * can be used to recover a compromised wallet, or just as part of preventative defence-in-depth measures.\n * </pre>\n */\n public boolean hasKeyRotationTime() {\n return ((bitField0_ & 0x00000100) == 0x00000100);\n }\n /**\n * <code>optional uint64 key_rotation_time = 13;</code>\n *\n * <pre>\n * UNIX time in seconds since the epoch. If set, then any keys created before this date are assumed to be no longer\n * wanted. Money sent to them will be re-spent automatically to the first key that was created after this time. It\n * can be used to recover a compromised wallet, or just as part of preventative defence-in-depth measures.\n * </pre>\n */\n public long getKeyRotationTime() {\n return keyRotationTime_;\n }\n\n private void initFields() {\n networkIdentifier_ = \"\";\n lastSeenBlockHash_ = com.google.protobuf.ByteString.EMPTY;\n lastSeenBlockHeight_ = 0;\n lastSeenBlockTimeSecs_ = 0L;\n key_ = java.util.Collections.emptyList();\n transaction_ = java.util.Collections.emptyList();\n watchedScript_ = java.util.Collections.emptyList();\n encryptionType_ = org.bitcoinj.wallet.Protos.Wallet.EncryptionType.UNENCRYPTED;\n encryptionParameters_ = org.bitcoinj.wallet.Protos.ScryptParameters.getDefaultInstance();\n version_ = 0;\n extension_ = java.util.Collections.emptyList();\n description_ = \"\";\n keyRotationTime_ = 0L;\n }\n private byte memoizedIsInitialized = -1;\n public final boolean isInitialized() {\n byte isInitialized = memoizedIsInitialized;\n if (isInitialized != -1) return isInitialized == 1;\n\n if (!hasNetworkIdentifier()) {\n memoizedIsInitialized = 0;\n return false;\n }\n for (int i = 0; i < getKeyCount(); i++) {\n if (!getKey(i).isInitialized()) {\n memoizedIsInitialized = 0;\n return false;\n }\n }\n for (int i = 0; i < getTransactionCount(); i++) {\n if (!getTransaction(i).isInitialized()) {\n memoizedIsInitialized = 0;\n return false;\n }\n }\n for (int i = 0; i < getWatchedScriptCount(); i++) {\n if (!getWatchedScript(i).isInitialized()) {\n memoizedIsInitialized = 0;\n return false;\n }\n }\n if (hasEncryptionParameters()) {\n if (!getEncryptionParameters().isInitialized()) {\n memoizedIsInitialized = 0;\n return false;\n }\n }\n for (int i = 0; i < getExtensionCount(); i++) {\n if (!getExtension(i).isInitialized()) {\n memoizedIsInitialized = 0;\n return false;\n }\n }\n memoizedIsInitialized = 1;\n return true;\n }\n\n public void writeTo(com.google.protobuf.CodedOutputStream output)\n throws java.io.IOException {\n getSerializedSize();\n if (((bitField0_ & 0x00000001) == 0x00000001)) {\n output.writeBytes(1, getNetworkIdentifierBytes());\n }\n if (((bitField0_ & 0x00000002) == 0x00000002)) {\n output.writeBytes(2, lastSeenBlockHash_);\n }\n for (int i = 0; i < key_.size(); i++) {\n output.writeMessage(3, key_.get(i));\n }\n for (int i = 0; i < transaction_.size(); i++) {\n output.writeMessage(4, transaction_.get(i));\n }\n if (((bitField0_ & 0x00000010) == 0x00000010)) {\n output.writeEnum(5, encryptionType_.getNumber());\n }\n if (((bitField0_ & 0x00000020) == 0x00000020)) {\n output.writeMessage(6, encryptionParameters_);\n }\n if (((bitField0_ & 0x00000040) == 0x00000040)) {\n output.writeInt32(7, version_);\n }\n for (int i = 0; i < extension_.size(); i++) {\n output.writeMessage(10, extension_.get(i));\n }\n if (((bitField0_ & 0x00000080) == 0x00000080)) {\n output.writeBytes(11, getDescriptionBytes());\n }\n if (((bitField0_ & 0x00000004) == 0x00000004)) {\n output.writeUInt32(12, lastSeenBlockHeight_);\n }\n if (((bitField0_ & 0x00000100) == 0x00000100)) {\n output.writeUInt64(13, keyRotationTime_);\n }\n if (((bitField0_ & 0x00000008) == 0x00000008)) {\n output.writeInt64(14, lastSeenBlockTimeSecs_);\n }\n for (int i = 0; i < watchedScript_.size(); i++) {\n output.writeMessage(15, watchedScript_.get(i));\n }\n getUnknownFields().writeTo(output);\n }\n\n private int memoizedSerializedSize = -1;\n public int getSerializedSize() {\n int size = memoizedSerializedSize;\n if (size != -1) return size;\n\n size = 0;\n if (((bitField0_ & 0x00000001) == 0x00000001)) {\n size += com.google.protobuf.CodedOutputStream\n .computeBytesSize(1, getNetworkIdentifierBytes());\n }\n if (((bitField0_ & 0x00000002) == 0x00000002)) {\n size += com.google.protobuf.CodedOutputStream\n .computeBytesSize(2, lastSeenBlockHash_);\n }\n for (int i = 0; i < key_.size(); i++) {\n size += com.google.protobuf.CodedOutputStream\n .computeMessageSize(3, key_.get(i));\n }\n for (int i = 0; i < transaction_.size(); i++) {\n size += com.google.protobuf.CodedOutputStream\n .computeMessageSize(4, transaction_.get(i));\n }\n if (((bitField0_ & 0x00000010) == 0x00000010)) {\n size += com.google.protobuf.CodedOutputStream\n .computeEnumSize(5, encryptionType_.getNumber());\n }\n if (((bitField0_ & 0x00000020) == 0x00000020)) {\n size += com.google.protobuf.CodedOutputStream\n .computeMessageSize(6, encryptionParameters_);\n }\n if (((bitField0_ & 0x00000040) == 0x00000040)) {\n size += com.google.protobuf.CodedOutputStream\n .computeInt32Size(7, version_);\n }\n for (int i = 0; i < extension_.size(); i++) {\n size += com.google.protobuf.CodedOutputStream\n .computeMessageSize(10, extension_.get(i));\n }\n if (((bitField0_ & 0x00000080) == 0x00000080)) {\n size += com.google.protobuf.CodedOutputStream\n .computeBytesSize(11, getDescriptionBytes());\n }\n if (((bitField0_ & 0x00000004) == 0x00000004)) {\n size += com.google.protobuf.CodedOutputStream\n .computeUInt32Size(12, lastSeenBlockHeight_);\n }\n if (((bitField0_ & 0x00000100) == 0x00000100)) {\n size += com.google.protobuf.CodedOutputStream\n .computeUInt64Size(13, keyRotationTime_);\n }\n if (((bitField0_ & 0x00000008) == 0x00000008)) {\n size += com.google.protobuf.CodedOutputStream\n .computeInt64Size(14, lastSeenBlockTimeSecs_);\n }\n for (int i = 0; i < watchedScript_.size(); i++) {\n size += com.google.protobuf.CodedOutputStream\n .computeMessageSize(15, watchedScript_.get(i));\n }\n size += getUnknownFields().getSerializedSize();\n memoizedSerializedSize = size;\n return size;\n }\n\n private static final long serialVersionUID = 0L;\n @java.lang.Override\n protected java.lang.Object writeReplace()\n throws java.io.ObjectStreamException {\n return super.writeReplace();\n }\n\n public static org.bitcoinj.wallet.Protos.Wallet parseFrom(\n com.google.protobuf.ByteString data)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n public static org.bitcoinj.wallet.Protos.Wallet parseFrom(\n com.google.protobuf.ByteString data,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n public static org.bitcoinj.wallet.Protos.Wallet parseFrom(byte[] data)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data);\n }\n public static org.bitcoinj.wallet.Protos.Wallet parseFrom(\n byte[] data,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws com.google.protobuf.InvalidProtocolBufferException {\n return PARSER.parseFrom(data, extensionRegistry);\n }\n public static org.bitcoinj.wallet.Protos.Wallet parseFrom(java.io.InputStream input)\n throws java.io.IOException {\n return PARSER.parseFrom(input);\n }\n public static org.bitcoinj.wallet.Protos.Wallet parseFrom(\n java.io.InputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return PARSER.parseFrom(input, extensionRegistry);\n }\n public static org.bitcoinj.wallet.Protos.Wallet parseDelimitedFrom(java.io.InputStream input)\n throws java.io.IOException {\n return PARSER.parseDelimitedFrom(input);\n }\n public static org.bitcoinj.wallet.Protos.Wallet parseDelimitedFrom(\n java.io.InputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return PARSER.parseDelimitedFrom(input, extensionRegistry);\n }\n public static org.bitcoinj.wallet.Protos.Wallet parseFrom(\n com.google.protobuf.CodedInputStream input)\n throws java.io.IOException {\n return PARSER.parseFrom(input);\n }\n public static org.bitcoinj.wallet.Protos.Wallet parseFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n return PARSER.parseFrom(input, extensionRegistry);\n }\n\n public static Builder newBuilder() { return Builder.create(); }\n public Builder newBuilderForType() { return newBuilder(); }\n public static Builder newBuilder(org.bitcoinj.wallet.Protos.Wallet prototype) {\n return newBuilder().mergeFrom(prototype);\n }\n public Builder toBuilder() { return newBuilder(this); }\n\n @java.lang.Override\n protected Builder newBuilderForType(\n com.google.protobuf.GeneratedMessage.BuilderParent parent) {\n Builder builder = new Builder(parent);\n return builder;\n }\n /**\n * Protobuf type {@code wallet.Wallet}\n *\n * <pre>\n ** A bitcoin wallet \n * </pre>\n */\n public static final class Builder extends\n com.google.protobuf.GeneratedMessage.Builder<Builder>\n implements org.bitcoinj.wallet.Protos.WalletOrBuilder {\n public static final com.google.protobuf.Descriptors.Descriptor\n getDescriptor() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_Wallet_descriptor;\n }\n\n protected com.google.protobuf.GeneratedMessage.FieldAccessorTable\n internalGetFieldAccessorTable() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_Wallet_fieldAccessorTable\n .ensureFieldAccessorsInitialized(\n org.bitcoinj.wallet.Protos.Wallet.class, org.bitcoinj.wallet.Protos.Wallet.Builder.class);\n }\n\n // Construct using org.bitcoinj.wallet.Protos.Wallet.newBuilder()\n private Builder() {\n maybeForceBuilderInitialization();\n }\n\n private Builder(\n com.google.protobuf.GeneratedMessage.BuilderParent parent) {\n super(parent);\n maybeForceBuilderInitialization();\n }\n private void maybeForceBuilderInitialization() {\n if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {\n getKeyFieldBuilder();\n getTransactionFieldBuilder();\n getWatchedScriptFieldBuilder();\n getEncryptionParametersFieldBuilder();\n getExtensionFieldBuilder();\n }\n }\n private static Builder create() {\n return new Builder();\n }\n\n public Builder clear() {\n super.clear();\n networkIdentifier_ = \"\";\n bitField0_ = (bitField0_ & ~0x00000001);\n lastSeenBlockHash_ = com.google.protobuf.ByteString.EMPTY;\n bitField0_ = (bitField0_ & ~0x00000002);\n lastSeenBlockHeight_ = 0;\n bitField0_ = (bitField0_ & ~0x00000004);\n lastSeenBlockTimeSecs_ = 0L;\n bitField0_ = (bitField0_ & ~0x00000008);\n if (keyBuilder_ == null) {\n key_ = java.util.Collections.emptyList();\n bitField0_ = (bitField0_ & ~0x00000010);\n } else {\n keyBuilder_.clear();\n }\n if (transactionBuilder_ == null) {\n transaction_ = java.util.Collections.emptyList();\n bitField0_ = (bitField0_ & ~0x00000020);\n } else {\n transactionBuilder_.clear();\n }\n if (watchedScriptBuilder_ == null) {\n watchedScript_ = java.util.Collections.emptyList();\n bitField0_ = (bitField0_ & ~0x00000040);\n } else {\n watchedScriptBuilder_.clear();\n }\n encryptionType_ = org.bitcoinj.wallet.Protos.Wallet.EncryptionType.UNENCRYPTED;\n bitField0_ = (bitField0_ & ~0x00000080);\n if (encryptionParametersBuilder_ == null) {\n encryptionParameters_ = org.bitcoinj.wallet.Protos.ScryptParameters.getDefaultInstance();\n } else {\n encryptionParametersBuilder_.clear();\n }\n bitField0_ = (bitField0_ & ~0x00000100);\n version_ = 0;\n bitField0_ = (bitField0_ & ~0x00000200);\n if (extensionBuilder_ == null) {\n extension_ = java.util.Collections.emptyList();\n bitField0_ = (bitField0_ & ~0x00000400);\n } else {\n extensionBuilder_.clear();\n }\n description_ = \"\";\n bitField0_ = (bitField0_ & ~0x00000800);\n keyRotationTime_ = 0L;\n bitField0_ = (bitField0_ & ~0x00001000);\n return this;\n }\n\n public Builder clone() {\n return create().mergeFrom(buildPartial());\n }\n\n public com.google.protobuf.Descriptors.Descriptor\n getDescriptorForType() {\n return org.bitcoinj.wallet.Protos.internal_static_wallet_Wallet_descriptor;\n }\n\n public org.bitcoinj.wallet.Protos.Wallet getDefaultInstanceForType() {\n return org.bitcoinj.wallet.Protos.Wallet.getDefaultInstance();\n }\n\n public org.bitcoinj.wallet.Protos.Wallet build() {\n org.bitcoinj.wallet.Protos.Wallet result = buildPartial();\n if (!result.isInitialized()) {\n throw newUninitializedMessageException(result);\n }\n return result;\n }\n\n public org.bitcoinj.wallet.Protos.Wallet buildPartial() {\n org.bitcoinj.wallet.Protos.Wallet result = new org.bitcoinj.wallet.Protos.Wallet(this);\n int from_bitField0_ = bitField0_;\n int to_bitField0_ = 0;\n if (((from_bitField0_ & 0x00000001) == 0x00000001)) {\n to_bitField0_ |= 0x00000001;\n }\n result.networkIdentifier_ = networkIdentifier_;\n if (((from_bitField0_ & 0x00000002) == 0x00000002)) {\n to_bitField0_ |= 0x00000002;\n }\n result.lastSeenBlockHash_ = lastSeenBlockHash_;\n if (((from_bitField0_ & 0x00000004) == 0x00000004)) {\n to_bitField0_ |= 0x00000004;\n }\n result.lastSeenBlockHeight_ = lastSeenBlockHeight_;\n if (((from_bitField0_ & 0x00000008) == 0x00000008)) {\n to_bitField0_ |= 0x00000008;\n }\n result.lastSeenBlockTimeSecs_ = lastSeenBlockTimeSecs_;\n if (keyBuilder_ == null) {\n if (((bitField0_ & 0x00000010) == 0x00000010)) {\n key_ = java.util.Collections.unmodifiableList(key_);\n bitField0_ = (bitField0_ & ~0x00000010);\n }\n result.key_ = key_;\n } else {\n result.key_ = keyBuilder_.build();\n }\n if (transactionBuilder_ == null) {\n if (((bitField0_ & 0x00000020) == 0x00000020)) {\n transaction_ = java.util.Collections.unmodifiableList(transaction_);\n bitField0_ = (bitField0_ & ~0x00000020);\n }\n result.transaction_ = transaction_;\n } else {\n result.transaction_ = transactionBuilder_.build();\n }\n if (watchedScriptBuilder_ == null) {\n if (((bitField0_ & 0x00000040) == 0x00000040)) {\n watchedScript_ = java.util.Collections.unmodifiableList(watchedScript_);\n bitField0_ = (bitField0_ & ~0x00000040);\n }\n result.watchedScript_ = watchedScript_;\n } else {\n result.watchedScript_ = watchedScriptBuilder_.build();\n }\n if (((from_bitField0_ & 0x00000080) == 0x00000080)) {\n to_bitField0_ |= 0x00000010;\n }\n result.encryptionType_ = encryptionType_;\n if (((from_bitField0_ & 0x00000100) == 0x00000100)) {\n to_bitField0_ |= 0x00000020;\n }\n if (encryptionParametersBuilder_ == null) {\n result.encryptionParameters_ = encryptionParameters_;\n } else {\n result.encryptionParameters_ = encryptionParametersBuilder_.build();\n }\n if (((from_bitField0_ & 0x00000200) == 0x00000200)) {\n to_bitField0_ |= 0x00000040;\n }\n result.version_ = version_;\n if (extensionBuilder_ == null) {\n if (((bitField0_ & 0x00000400) == 0x00000400)) {\n extension_ = java.util.Collections.unmodifiableList(extension_);\n bitField0_ = (bitField0_ & ~0x00000400);\n }\n result.extension_ = extension_;\n } else {\n result.extension_ = extensionBuilder_.build();\n }\n if (((from_bitField0_ & 0x00000800) == 0x00000800)) {\n to_bitField0_ |= 0x00000080;\n }\n result.description_ = description_;\n if (((from_bitField0_ & 0x00001000) == 0x00001000)) {\n to_bitField0_ |= 0x00000100;\n }\n result.keyRotationTime_ = keyRotationTime_;\n result.bitField0_ = to_bitField0_;\n onBuilt();\n return result;\n }\n\n public Builder mergeFrom(com.google.protobuf.Message other) {\n if (other instanceof org.bitcoinj.wallet.Protos.Wallet) {\n return mergeFrom((org.bitcoinj.wallet.Protos.Wallet)other);\n } else {\n super.mergeFrom(other);\n return this;\n }\n }\n\n public Builder mergeFrom(org.bitcoinj.wallet.Protos.Wallet other) {\n if (other == org.bitcoinj.wallet.Protos.Wallet.getDefaultInstance()) return this;\n if (other.hasNetworkIdentifier()) {\n bitField0_ |= 0x00000001;\n networkIdentifier_ = other.networkIdentifier_;\n onChanged();\n }\n if (other.hasLastSeenBlockHash()) {\n setLastSeenBlockHash(other.getLastSeenBlockHash());\n }\n if (other.hasLastSeenBlockHeight()) {\n setLastSeenBlockHeight(other.getLastSeenBlockHeight());\n }\n if (other.hasLastSeenBlockTimeSecs()) {\n setLastSeenBlockTimeSecs(other.getLastSeenBlockTimeSecs());\n }\n if (keyBuilder_ == null) {\n if (!other.key_.isEmpty()) {\n if (key_.isEmpty()) {\n key_ = other.key_;\n bitField0_ = (bitField0_ & ~0x00000010);\n } else {\n ensureKeyIsMutable();\n key_.addAll(other.key_);\n }\n onChanged();\n }\n } else {\n if (!other.key_.isEmpty()) {\n if (keyBuilder_.isEmpty()) {\n keyBuilder_.dispose();\n keyBuilder_ = null;\n key_ = other.key_;\n bitField0_ = (bitField0_ & ~0x00000010);\n keyBuilder_ = \n com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ?\n getKeyFieldBuilder() : null;\n } else {\n keyBuilder_.addAllMessages(other.key_);\n }\n }\n }\n if (transactionBuilder_ == null) {\n if (!other.transaction_.isEmpty()) {\n if (transaction_.isEmpty()) {\n transaction_ = other.transaction_;\n bitField0_ = (bitField0_ & ~0x00000020);\n } else {\n ensureTransactionIsMutable();\n transaction_.addAll(other.transaction_);\n }\n onChanged();\n }\n } else {\n if (!other.transaction_.isEmpty()) {\n if (transactionBuilder_.isEmpty()) {\n transactionBuilder_.dispose();\n transactionBuilder_ = null;\n transaction_ = other.transaction_;\n bitField0_ = (bitField0_ & ~0x00000020);\n transactionBuilder_ = \n com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ?\n getTransactionFieldBuilder() : null;\n } else {\n transactionBuilder_.addAllMessages(other.transaction_);\n }\n }\n }\n if (watchedScriptBuilder_ == null) {\n if (!other.watchedScript_.isEmpty()) {\n if (watchedScript_.isEmpty()) {\n watchedScript_ = other.watchedScript_;\n bitField0_ = (bitField0_ & ~0x00000040);\n } else {\n ensureWatchedScriptIsMutable();\n watchedScript_.addAll(other.watchedScript_);\n }\n onChanged();\n }\n } else {\n if (!other.watchedScript_.isEmpty()) {\n if (watchedScriptBuilder_.isEmpty()) {\n watchedScriptBuilder_.dispose();\n watchedScriptBuilder_ = null;\n watchedScript_ = other.watchedScript_;\n bitField0_ = (bitField0_ & ~0x00000040);\n watchedScriptBuilder_ = \n com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ?\n getWatchedScriptFieldBuilder() : null;\n } else {\n watchedScriptBuilder_.addAllMessages(other.watchedScript_);\n }\n }\n }\n if (other.hasEncryptionType()) {\n setEncryptionType(other.getEncryptionType());\n }\n if (other.hasEncryptionParameters()) {\n mergeEncryptionParameters(other.getEncryptionParameters());\n }\n if (other.hasVersion()) {\n setVersion(other.getVersion());\n }\n if (extensionBuilder_ == null) {\n if (!other.extension_.isEmpty()) {\n if (extension_.isEmpty()) {\n extension_ = other.extension_;\n bitField0_ = (bitField0_ & ~0x00000400);\n } else {\n ensureExtensionIsMutable();\n extension_.addAll(other.extension_);\n }\n onChanged();\n }\n } else {\n if (!other.extension_.isEmpty()) {\n if (extensionBuilder_.isEmpty()) {\n extensionBuilder_.dispose();\n extensionBuilder_ = null;\n extension_ = other.extension_;\n bitField0_ = (bitField0_ & ~0x00000400);\n extensionBuilder_ = \n com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ?\n getExtensionFieldBuilder() : null;\n } else {\n extensionBuilder_.addAllMessages(other.extension_);\n }\n }\n }\n if (other.hasDescription()) {\n bitField0_ |= 0x00000800;\n description_ = other.description_;\n onChanged();\n }\n if (other.hasKeyRotationTime()) {\n setKeyRotationTime(other.getKeyRotationTime());\n }\n this.mergeUnknownFields(other.getUnknownFields());\n return this;\n }\n\n public final boolean isInitialized() {\n if (!hasNetworkIdentifier()) {\n \n return false;\n }\n for (int i = 0; i < getKeyCount(); i++) {\n if (!getKey(i).isInitialized()) {\n \n return false;\n }\n }\n for (int i = 0; i < getTransactionCount(); i++) {\n if (!getTransaction(i).isInitialized()) {\n \n return false;\n }\n }\n for (int i = 0; i < getWatchedScriptCount(); i++) {\n if (!getWatchedScript(i).isInitialized()) {\n \n return false;\n }\n }\n if (hasEncryptionParameters()) {\n if (!getEncryptionParameters().isInitialized()) {\n \n return false;\n }\n }\n for (int i = 0; i < getExtensionCount(); i++) {\n if (!getExtension(i).isInitialized()) {\n \n return false;\n }\n }\n return true;\n }\n\n public Builder mergeFrom(\n com.google.protobuf.CodedInputStream input,\n com.google.protobuf.ExtensionRegistryLite extensionRegistry)\n throws java.io.IOException {\n org.bitcoinj.wallet.Protos.Wallet parsedMessage = null;\n try {\n parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);\n } catch (com.google.protobuf.InvalidProtocolBufferException e) {\n parsedMessage = (org.bitcoinj.wallet.Protos.Wallet) e.getUnfinishedMessage();\n throw e;\n } finally {\n if (parsedMessage != null) {\n mergeFrom(parsedMessage);\n }\n }\n return this;\n }\n private int bitField0_;\n\n // required string network_identifier = 1;\n private java.lang.Object networkIdentifier_ = \"\";\n /**\n * <code>required string network_identifier = 1;</code>\n *\n * <pre>\n * the network used by this wallet\n * </pre>\n */\n public boolean hasNetworkIdentifier() {\n return ((bitField0_ & 0x00000001) == 0x00000001);\n }\n /**\n * <code>required string network_identifier = 1;</code>\n *\n * <pre>\n * the network used by this wallet\n * </pre>\n */\n public java.lang.String getNetworkIdentifier() {\n java.lang.Object ref = networkIdentifier_;\n if (!(ref instanceof java.lang.String)) {\n java.lang.String s = ((com.google.protobuf.ByteString) ref)\n .toStringUtf8();\n networkIdentifier_ = s;\n return s;\n } else {\n return (java.lang.String) ref;\n }\n }\n /**\n * <code>required string network_identifier = 1;</code>\n *\n * <pre>\n * the network used by this wallet\n * </pre>\n */\n public com.google.protobuf.ByteString\n getNetworkIdentifierBytes() {\n java.lang.Object ref = networkIdentifier_;\n if (ref instanceof String) {\n com.google.protobuf.ByteString b = \n com.google.protobuf.ByteString.copyFromUtf8(\n (java.lang.String) ref);\n networkIdentifier_ = b;\n return b;\n } else {\n return (com.google.protobuf.ByteString) ref;\n }\n }\n /**\n * <code>required string network_identifier = 1;</code>\n *\n * <pre>\n * the network used by this wallet\n * </pre>\n */\n public Builder setNetworkIdentifier(\n java.lang.String value) {\n if (value == null) {\n throw new NullPointerException();\n }\n bitField0_ |= 0x00000001;\n networkIdentifier_ = value;\n onChanged();\n return this;\n }\n /**\n * <code>required string network_identifier = 1;</code>\n *\n * <pre>\n * the network used by this wallet\n * </pre>\n */\n public Builder clearNetworkIdentifier() {\n bitField0_ = (bitField0_ & ~0x00000001);\n networkIdentifier_ = getDefaultInstance().getNetworkIdentifier();\n onChanged();\n return this;\n }\n /**\n * <code>required string network_identifier = 1;</code>\n *\n * <pre>\n * the network used by this wallet\n * </pre>\n */\n public Builder setNetworkIdentifierBytes(\n com.google.protobuf.ByteString value) {\n if (value == null) {\n throw new NullPointerException();\n }\n bitField0_ |= 0x00000001;\n networkIdentifier_ = value;\n onChanged();\n return this;\n }\n\n // optional bytes last_seen_block_hash = 2;\n private com.google.protobuf.ByteString lastSeenBlockHash_ = com.google.protobuf.ByteString.EMPTY;\n /**\n * <code>optional bytes last_seen_block_hash = 2;</code>\n *\n * <pre>\n * The SHA256 hash of the head of the best chain seen by this wallet.\n * </pre>\n */\n public boolean hasLastSeenBlockHash() {\n return ((bitField0_ & 0x00000002) == 0x00000002);\n }\n /**\n * <code>optional bytes last_seen_block_hash = 2;</code>\n *\n * <pre>\n * The SHA256 hash of the head of the best chain seen by this wallet.\n * </pre>\n */\n public com.google.protobuf.ByteString getLastSeenBlockHash() {\n return lastSeenBlockHash_;\n }\n /**\n * <code>optional bytes last_seen_block_hash = 2;</code>\n *\n * <pre>\n * The SHA256 hash of the head of the best chain seen by this wallet.\n * </pre>\n */\n public Builder setLastSeenBlockHash(com.google.protobuf.ByteString value) {\n if (value == null) {\n throw new NullPointerException();\n }\n bitField0_ |= 0x00000002;\n lastSeenBlockHash_ = value;\n onChanged();\n return this;\n }\n /**\n * <code>optional bytes last_seen_block_hash = 2;</code>\n *\n * <pre>\n * The SHA256 hash of the head of the best chain seen by this wallet.\n * </pre>\n */\n public Builder clearLastSeenBlockHash() {\n bitField0_ = (bitField0_ & ~0x00000002);\n lastSeenBlockHash_ = getDefaultInstance().getLastSeenBlockHash();\n onChanged();\n return this;\n }\n\n // optional uint32 last_seen_block_height = 12;\n private int lastSeenBlockHeight_ ;\n /**\n * <code>optional uint32 last_seen_block_height = 12;</code>\n *\n * <pre>\n * The height in the chain of the last seen block.\n * </pre>\n */\n public boolean hasLastSeenBlockHeight() {\n return ((bitField0_ & 0x00000004) == 0x00000004);\n }\n /**\n * <code>optional uint32 last_seen_block_height = 12;</code>\n *\n * <pre>\n * The height in the chain of the last seen block.\n * </pre>\n */\n public int getLastSeenBlockHeight() {\n return lastSeenBlockHeight_;\n }\n /**\n * <code>optional uint32 last_seen_block_height = 12;</code>\n *\n * <pre>\n * The height in the chain of the last seen block.\n * </pre>\n */\n public Builder setLastSeenBlockHeight(int value) {\n bitField0_ |= 0x00000004;\n lastSeenBlockHeight_ = value;\n onChanged();\n return this;\n }\n /**\n * <code>optional uint32 last_seen_block_height = 12;</code>\n *\n * <pre>\n * The height in the chain of the last seen block.\n * </pre>\n */\n public Builder clearLastSeenBlockHeight() {\n bitField0_ = (bitField0_ & ~0x00000004);\n lastSeenBlockHeight_ = 0;\n onChanged();\n return this;\n }\n\n // optional int64 last_seen_block_time_secs = 14;\n private long lastSeenBlockTimeSecs_ ;\n /**\n * <code>optional int64 last_seen_block_time_secs = 14;</code>\n */\n public boolean hasLastSeenBlockTimeSecs() {\n return ((bitField0_ & 0x00000008) == 0x00000008);\n }\n /**\n * <code>optional int64 last_seen_block_time_secs = 14;</code>\n */\n public long getLastSeenBlockTimeSecs() {\n return lastSeenBlockTimeSecs_;\n }\n /**\n * <code>optional int64 last_seen_block_time_secs = 14;</code>\n */\n public Builder setLastSeenBlockTimeSecs(long value) {\n bitField0_ |= 0x00000008;\n lastSeenBlockTimeSecs_ = value;\n onChanged();\n return this;\n }\n /**\n * <code>optional int64 last_seen_block_time_secs = 14;</code>\n */\n public Builder clearLastSeenBlockTimeSecs() {\n bitField0_ = (bitField0_ & ~0x00000008);\n lastSeenBlockTimeSecs_ = 0L;\n onChanged();\n return this;\n }\n\n // repeated .wallet.Key key = 3;\n private java.util.List<org.bitcoinj.wallet.Protos.Key> key_ =\n java.util.Collections.emptyList();\n private void ensureKeyIsMutable() {\n if (!((bitField0_ & 0x00000010) == 0x00000010)) {\n key_ = new java.util.ArrayList<org.bitcoinj.wallet.Protos.Key>(key_);\n bitField0_ |= 0x00000010;\n }\n }\n\n private com.google.protobuf.RepeatedFieldBuilder<\n org.bitcoinj.wallet.Protos.Key, org.bitcoinj.wallet.Protos.Key.Builder, org.bitcoinj.wallet.Protos.KeyOrBuilder> keyBuilder_;\n\n /**\n * <code>repeated .wallet.Key key = 3;</code>\n */\n public java.util.List<org.bitcoinj.wallet.Protos.Key> getKeyList() {\n if (keyBuilder_ == null) {\n return java.util.Collections.unmodifiableList(key_);\n } else {\n return keyBuilder_.getMessageList();\n }\n }\n /**\n * <code>repeated .wallet.Key key = 3;</code>\n */\n public int getKeyCount() {\n if (keyBuilder_ == null) {\n return key_.size();\n } else {\n return keyBuilder_.getCount();\n }\n }\n /**\n * <code>repeated .wallet.Key key = 3;</code>\n */\n public org.bitcoinj.wallet.Protos.Key getKey(int index) {\n if (keyBuilder_ == null) {\n return key_.get(index);\n } else {\n return keyBuilder_.getMessage(index);\n }\n }\n /**\n * <code>repeated .wallet.Key key = 3;</code>\n */\n public Builder setKey(\n int index, org.bitcoinj.wallet.Protos.Key value) {\n if (keyBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureKeyIsMutable();\n key_.set(index, value);\n onChanged();\n } else {\n keyBuilder_.setMessage(index, value);\n }\n return this;\n }\n /**\n * <code>repeated .wallet.Key key = 3;</code>\n */\n public Builder setKey(\n int index, org.bitcoinj.wallet.Protos.Key.Builder builderForValue) {\n if (keyBuilder_ == null) {\n ensureKeyIsMutable();\n key_.set(index, builderForValue.build());\n onChanged();\n } else {\n keyBuilder_.setMessage(index, builderForValue.build());\n }\n return this;\n }\n /**\n * <code>repeated .wallet.Key key = 3;</code>\n */\n public Builder addKey(org.bitcoinj.wallet.Protos.Key value) {\n if (keyBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureKeyIsMutable();\n key_.add(value);\n onChanged();\n } else {\n keyBuilder_.addMessage(value);\n }\n return this;\n }\n /**\n * <code>repeated .wallet.Key key = 3;</code>\n */\n public Builder addKey(\n int index, org.bitcoinj.wallet.Protos.Key value) {\n if (keyBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureKeyIsMutable();\n key_.add(index, value);\n onChanged();\n } else {\n keyBuilder_.addMessage(index, value);\n }\n return this;\n }\n /**\n * <code>repeated .wallet.Key key = 3;</code>\n */\n public Builder addKey(\n org.bitcoinj.wallet.Protos.Key.Builder builderForValue) {\n if (keyBuilder_ == null) {\n ensureKeyIsMutable();\n key_.add(builderForValue.build());\n onChanged();\n } else {\n keyBuilder_.addMessage(builderForValue.build());\n }\n return this;\n }\n /**\n * <code>repeated .wallet.Key key = 3;</code>\n */\n public Builder addKey(\n int index, org.bitcoinj.wallet.Protos.Key.Builder builderForValue) {\n if (keyBuilder_ == null) {\n ensureKeyIsMutable();\n key_.add(index, builderForValue.build());\n onChanged();\n } else {\n keyBuilder_.addMessage(index, builderForValue.build());\n }\n return this;\n }\n /**\n * <code>repeated .wallet.Key key = 3;</code>\n */\n public Builder addAllKey(\n java.lang.Iterable<? extends org.bitcoinj.wallet.Protos.Key> values) {\n if (keyBuilder_ == null) {\n ensureKeyIsMutable();\n super.addAll(values, key_);\n onChanged();\n } else {\n keyBuilder_.addAllMessages(values);\n }\n return this;\n }\n /**\n * <code>repeated .wallet.Key key = 3;</code>\n */\n public Builder clearKey() {\n if (keyBuilder_ == null) {\n key_ = java.util.Collections.emptyList();\n bitField0_ = (bitField0_ & ~0x00000010);\n onChanged();\n } else {\n keyBuilder_.clear();\n }\n return this;\n }\n /**\n * <code>repeated .wallet.Key key = 3;</code>\n */\n public Builder removeKey(int index) {\n if (keyBuilder_ == null) {\n ensureKeyIsMutable();\n key_.remove(index);\n onChanged();\n } else {\n keyBuilder_.remove(index);\n }\n return this;\n }\n /**\n * <code>repeated .wallet.Key key = 3;</code>\n */\n public org.bitcoinj.wallet.Protos.Key.Builder getKeyBuilder(\n int index) {\n return getKeyFieldBuilder().getBuilder(index);\n }\n /**\n * <code>repeated .wallet.Key key = 3;</code>\n */\n public org.bitcoinj.wallet.Protos.KeyOrBuilder getKeyOrBuilder(\n int index) {\n if (keyBuilder_ == null) {\n return key_.get(index); } else {\n return keyBuilder_.getMessageOrBuilder(index);\n }\n }\n /**\n * <code>repeated .wallet.Key key = 3;</code>\n */\n public java.util.List<? extends org.bitcoinj.wallet.Protos.KeyOrBuilder> \n getKeyOrBuilderList() {\n if (keyBuilder_ != null) {\n return keyBuilder_.getMessageOrBuilderList();\n } else {\n return java.util.Collections.unmodifiableList(key_);\n }\n }\n /**\n * <code>repeated .wallet.Key key = 3;</code>\n */\n public org.bitcoinj.wallet.Protos.Key.Builder addKeyBuilder() {\n return getKeyFieldBuilder().addBuilder(\n org.bitcoinj.wallet.Protos.Key.getDefaultInstance());\n }\n /**\n * <code>repeated .wallet.Key key = 3;</code>\n */\n public org.bitcoinj.wallet.Protos.Key.Builder addKeyBuilder(\n int index) {\n return getKeyFieldBuilder().addBuilder(\n index, org.bitcoinj.wallet.Protos.Key.getDefaultInstance());\n }\n /**\n * <code>repeated .wallet.Key key = 3;</code>\n */\n public java.util.List<org.bitcoinj.wallet.Protos.Key.Builder> \n getKeyBuilderList() {\n return getKeyFieldBuilder().getBuilderList();\n }\n private com.google.protobuf.RepeatedFieldBuilder<\n org.bitcoinj.wallet.Protos.Key, org.bitcoinj.wallet.Protos.Key.Builder, org.bitcoinj.wallet.Protos.KeyOrBuilder> \n getKeyFieldBuilder() {\n if (keyBuilder_ == null) {\n keyBuilder_ = new com.google.protobuf.RepeatedFieldBuilder<\n org.bitcoinj.wallet.Protos.Key, org.bitcoinj.wallet.Protos.Key.Builder, org.bitcoinj.wallet.Protos.KeyOrBuilder>(\n key_,\n ((bitField0_ & 0x00000010) == 0x00000010),\n getParentForChildren(),\n isClean());\n key_ = null;\n }\n return keyBuilder_;\n }\n\n // repeated .wallet.Transaction transaction = 4;\n private java.util.List<org.bitcoinj.wallet.Protos.Transaction> transaction_ =\n java.util.Collections.emptyList();\n private void ensureTransactionIsMutable() {\n if (!((bitField0_ & 0x00000020) == 0x00000020)) {\n transaction_ = new java.util.ArrayList<org.bitcoinj.wallet.Protos.Transaction>(transaction_);\n bitField0_ |= 0x00000020;\n }\n }\n\n private com.google.protobuf.RepeatedFieldBuilder<\n org.bitcoinj.wallet.Protos.Transaction, org.bitcoinj.wallet.Protos.Transaction.Builder, org.bitcoinj.wallet.Protos.TransactionOrBuilder> transactionBuilder_;\n\n /**\n * <code>repeated .wallet.Transaction transaction = 4;</code>\n */\n public java.util.List<org.bitcoinj.wallet.Protos.Transaction> getTransactionList() {\n if (transactionBuilder_ == null) {\n return java.util.Collections.unmodifiableList(transaction_);\n } else {\n return transactionBuilder_.getMessageList();\n }\n }\n /**\n * <code>repeated .wallet.Transaction transaction = 4;</code>\n */\n public int getTransactionCount() {\n if (transactionBuilder_ == null) {\n return transaction_.size();\n } else {\n return transactionBuilder_.getCount();\n }\n }\n /**\n * <code>repeated .wallet.Transaction transaction = 4;</code>\n */\n public org.bitcoinj.wallet.Protos.Transaction getTransaction(int index) {\n if (transactionBuilder_ == null) {\n return transaction_.get(index);\n } else {\n return transactionBuilder_.getMessage(index);\n }\n }\n /**\n * <code>repeated .wallet.Transaction transaction = 4;</code>\n */\n public Builder setTransaction(\n int index, org.bitcoinj.wallet.Protos.Transaction value) {\n if (transactionBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureTransactionIsMutable();\n transaction_.set(index, value);\n onChanged();\n } else {\n transactionBuilder_.setMessage(index, value);\n }\n return this;\n }\n /**\n * <code>repeated .wallet.Transaction transaction = 4;</code>\n */\n public Builder setTransaction(\n int index, org.bitcoinj.wallet.Protos.Transaction.Builder builderForValue) {\n if (transactionBuilder_ == null) {\n ensureTransactionIsMutable();\n transaction_.set(index, builderForValue.build());\n onChanged();\n } else {\n transactionBuilder_.setMessage(index, builderForValue.build());\n }\n return this;\n }\n /**\n * <code>repeated .wallet.Transaction transaction = 4;</code>\n */\n public Builder addTransaction(org.bitcoinj.wallet.Protos.Transaction value) {\n if (transactionBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureTransactionIsMutable();\n transaction_.add(value);\n onChanged();\n } else {\n transactionBuilder_.addMessage(value);\n }\n return this;\n }\n /**\n * <code>repeated .wallet.Transaction transaction = 4;</code>\n */\n public Builder addTransaction(\n int index, org.bitcoinj.wallet.Protos.Transaction value) {\n if (transactionBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureTransactionIsMutable();\n transaction_.add(index, value);\n onChanged();\n } else {\n transactionBuilder_.addMessage(index, value);\n }\n return this;\n }\n /**\n * <code>repeated .wallet.Transaction transaction = 4;</code>\n */\n public Builder addTransaction(\n org.bitcoinj.wallet.Protos.Transaction.Builder builderForValue) {\n if (transactionBuilder_ == null) {\n ensureTransactionIsMutable();\n transaction_.add(builderForValue.build());\n onChanged();\n } else {\n transactionBuilder_.addMessage(builderForValue.build());\n }\n return this;\n }\n /**\n * <code>repeated .wallet.Transaction transaction = 4;</code>\n */\n public Builder addTransaction(\n int index, org.bitcoinj.wallet.Protos.Transaction.Builder builderForValue) {\n if (transactionBuilder_ == null) {\n ensureTransactionIsMutable();\n transaction_.add(index, builderForValue.build());\n onChanged();\n } else {\n transactionBuilder_.addMessage(index, builderForValue.build());\n }\n return this;\n }\n /**\n * <code>repeated .wallet.Transaction transaction = 4;</code>\n */\n public Builder addAllTransaction(\n java.lang.Iterable<? extends org.bitcoinj.wallet.Protos.Transaction> values) {\n if (transactionBuilder_ == null) {\n ensureTransactionIsMutable();\n super.addAll(values, transaction_);\n onChanged();\n } else {\n transactionBuilder_.addAllMessages(values);\n }\n return this;\n }\n /**\n * <code>repeated .wallet.Transaction transaction = 4;</code>\n */\n public Builder clearTransaction() {\n if (transactionBuilder_ == null) {\n transaction_ = java.util.Collections.emptyList();\n bitField0_ = (bitField0_ & ~0x00000020);\n onChanged();\n } else {\n transactionBuilder_.clear();\n }\n return this;\n }\n /**\n * <code>repeated .wallet.Transaction transaction = 4;</code>\n */\n public Builder removeTransaction(int index) {\n if (transactionBuilder_ == null) {\n ensureTransactionIsMutable();\n transaction_.remove(index);\n onChanged();\n } else {\n transactionBuilder_.remove(index);\n }\n return this;\n }\n /**\n * <code>repeated .wallet.Transaction transaction = 4;</code>\n */\n public org.bitcoinj.wallet.Protos.Transaction.Builder getTransactionBuilder(\n int index) {\n return getTransactionFieldBuilder().getBuilder(index);\n }\n /**\n * <code>repeated .wallet.Transaction transaction = 4;</code>\n */\n public org.bitcoinj.wallet.Protos.TransactionOrBuilder getTransactionOrBuilder(\n int index) {\n if (transactionBuilder_ == null) {\n return transaction_.get(index); } else {\n return transactionBuilder_.getMessageOrBuilder(index);\n }\n }\n /**\n * <code>repeated .wallet.Transaction transaction = 4;</code>\n */\n public java.util.List<? extends org.bitcoinj.wallet.Protos.TransactionOrBuilder> \n getTransactionOrBuilderList() {\n if (transactionBuilder_ != null) {\n return transactionBuilder_.getMessageOrBuilderList();\n } else {\n return java.util.Collections.unmodifiableList(transaction_);\n }\n }\n /**\n * <code>repeated .wallet.Transaction transaction = 4;</code>\n */\n public org.bitcoinj.wallet.Protos.Transaction.Builder addTransactionBuilder() {\n return getTransactionFieldBuilder().addBuilder(\n org.bitcoinj.wallet.Protos.Transaction.getDefaultInstance());\n }\n /**\n * <code>repeated .wallet.Transaction transaction = 4;</code>\n */\n public org.bitcoinj.wallet.Protos.Transaction.Builder addTransactionBuilder(\n int index) {\n return getTransactionFieldBuilder().addBuilder(\n index, org.bitcoinj.wallet.Protos.Transaction.getDefaultInstance());\n }\n /**\n * <code>repeated .wallet.Transaction transaction = 4;</code>\n */\n public java.util.List<org.bitcoinj.wallet.Protos.Transaction.Builder> \n getTransactionBuilderList() {\n return getTransactionFieldBuilder().getBuilderList();\n }\n private com.google.protobuf.RepeatedFieldBuilder<\n org.bitcoinj.wallet.Protos.Transaction, org.bitcoinj.wallet.Protos.Transaction.Builder, org.bitcoinj.wallet.Protos.TransactionOrBuilder> \n getTransactionFieldBuilder() {\n if (transactionBuilder_ == null) {\n transactionBuilder_ = new com.google.protobuf.RepeatedFieldBuilder<\n org.bitcoinj.wallet.Protos.Transaction, org.bitcoinj.wallet.Protos.Transaction.Builder, org.bitcoinj.wallet.Protos.TransactionOrBuilder>(\n transaction_,\n ((bitField0_ & 0x00000020) == 0x00000020),\n getParentForChildren(),\n isClean());\n transaction_ = null;\n }\n return transactionBuilder_;\n }\n\n // repeated .wallet.Script watched_script = 15;\n private java.util.List<org.bitcoinj.wallet.Protos.Script> watchedScript_ =\n java.util.Collections.emptyList();\n private void ensureWatchedScriptIsMutable() {\n if (!((bitField0_ & 0x00000040) == 0x00000040)) {\n watchedScript_ = new java.util.ArrayList<org.bitcoinj.wallet.Protos.Script>(watchedScript_);\n bitField0_ |= 0x00000040;\n }\n }\n\n private com.google.protobuf.RepeatedFieldBuilder<\n org.bitcoinj.wallet.Protos.Script, org.bitcoinj.wallet.Protos.Script.Builder, org.bitcoinj.wallet.Protos.ScriptOrBuilder> watchedScriptBuilder_;\n\n /**\n * <code>repeated .wallet.Script watched_script = 15;</code>\n */\n public java.util.List<org.bitcoinj.wallet.Protos.Script> getWatchedScriptList() {\n if (watchedScriptBuilder_ == null) {\n return java.util.Collections.unmodifiableList(watchedScript_);\n } else {\n return watchedScriptBuilder_.getMessageList();\n }\n }\n /**\n * <code>repeated .wallet.Script watched_script = 15;</code>\n */\n public int getWatchedScriptCount() {\n if (watchedScriptBuilder_ == null) {\n return watchedScript_.size();\n } else {\n return watchedScriptBuilder_.getCount();\n }\n }\n /**\n * <code>repeated .wallet.Script watched_script = 15;</code>\n */\n public org.bitcoinj.wallet.Protos.Script getWatchedScript(int index) {\n if (watchedScriptBuilder_ == null) {\n return watchedScript_.get(index);\n } else {\n return watchedScriptBuilder_.getMessage(index);\n }\n }\n /**\n * <code>repeated .wallet.Script watched_script = 15;</code>\n */\n public Builder setWatchedScript(\n int index, org.bitcoinj.wallet.Protos.Script value) {\n if (watchedScriptBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureWatchedScriptIsMutable();\n watchedScript_.set(index, value);\n onChanged();\n } else {\n watchedScriptBuilder_.setMessage(index, value);\n }\n return this;\n }\n /**\n * <code>repeated .wallet.Script watched_script = 15;</code>\n */\n public Builder setWatchedScript(\n int index, org.bitcoinj.wallet.Protos.Script.Builder builderForValue) {\n if (watchedScriptBuilder_ == null) {\n ensureWatchedScriptIsMutable();\n watchedScript_.set(index, builderForValue.build());\n onChanged();\n } else {\n watchedScriptBuilder_.setMessage(index, builderForValue.build());\n }\n return this;\n }\n /**\n * <code>repeated .wallet.Script watched_script = 15;</code>\n */\n public Builder addWatchedScript(org.bitcoinj.wallet.Protos.Script value) {\n if (watchedScriptBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureWatchedScriptIsMutable();\n watchedScript_.add(value);\n onChanged();\n } else {\n watchedScriptBuilder_.addMessage(value);\n }\n return this;\n }\n /**\n * <code>repeated .wallet.Script watched_script = 15;</code>\n */\n public Builder addWatchedScript(\n int index, org.bitcoinj.wallet.Protos.Script value) {\n if (watchedScriptBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureWatchedScriptIsMutable();\n watchedScript_.add(index, value);\n onChanged();\n } else {\n watchedScriptBuilder_.addMessage(index, value);\n }\n return this;\n }\n /**\n * <code>repeated .wallet.Script watched_script = 15;</code>\n */\n public Builder addWatchedScript(\n org.bitcoinj.wallet.Protos.Script.Builder builderForValue) {\n if (watchedScriptBuilder_ == null) {\n ensureWatchedScriptIsMutable();\n watchedScript_.add(builderForValue.build());\n onChanged();\n } else {\n watchedScriptBuilder_.addMessage(builderForValue.build());\n }\n return this;\n }\n /**\n * <code>repeated .wallet.Script watched_script = 15;</code>\n */\n public Builder addWatchedScript(\n int index, org.bitcoinj.wallet.Protos.Script.Builder builderForValue) {\n if (watchedScriptBuilder_ == null) {\n ensureWatchedScriptIsMutable();\n watchedScript_.add(index, builderForValue.build());\n onChanged();\n } else {\n watchedScriptBuilder_.addMessage(index, builderForValue.build());\n }\n return this;\n }\n /**\n * <code>repeated .wallet.Script watched_script = 15;</code>\n */\n public Builder addAllWatchedScript(\n java.lang.Iterable<? extends org.bitcoinj.wallet.Protos.Script> values) {\n if (watchedScriptBuilder_ == null) {\n ensureWatchedScriptIsMutable();\n super.addAll(values, watchedScript_);\n onChanged();\n } else {\n watchedScriptBuilder_.addAllMessages(values);\n }\n return this;\n }\n /**\n * <code>repeated .wallet.Script watched_script = 15;</code>\n */\n public Builder clearWatchedScript() {\n if (watchedScriptBuilder_ == null) {\n watchedScript_ = java.util.Collections.emptyList();\n bitField0_ = (bitField0_ & ~0x00000040);\n onChanged();\n } else {\n watchedScriptBuilder_.clear();\n }\n return this;\n }\n /**\n * <code>repeated .wallet.Script watched_script = 15;</code>\n */\n public Builder removeWatchedScript(int index) {\n if (watchedScriptBuilder_ == null) {\n ensureWatchedScriptIsMutable();\n watchedScript_.remove(index);\n onChanged();\n } else {\n watchedScriptBuilder_.remove(index);\n }\n return this;\n }\n /**\n * <code>repeated .wallet.Script watched_script = 15;</code>\n */\n public org.bitcoinj.wallet.Protos.Script.Builder getWatchedScriptBuilder(\n int index) {\n return getWatchedScriptFieldBuilder().getBuilder(index);\n }\n /**\n * <code>repeated .wallet.Script watched_script = 15;</code>\n */\n public org.bitcoinj.wallet.Protos.ScriptOrBuilder getWatchedScriptOrBuilder(\n int index) {\n if (watchedScriptBuilder_ == null) {\n return watchedScript_.get(index); } else {\n return watchedScriptBuilder_.getMessageOrBuilder(index);\n }\n }\n /**\n * <code>repeated .wallet.Script watched_script = 15;</code>\n */\n public java.util.List<? extends org.bitcoinj.wallet.Protos.ScriptOrBuilder> \n getWatchedScriptOrBuilderList() {\n if (watchedScriptBuilder_ != null) {\n return watchedScriptBuilder_.getMessageOrBuilderList();\n } else {\n return java.util.Collections.unmodifiableList(watchedScript_);\n }\n }\n /**\n * <code>repeated .wallet.Script watched_script = 15;</code>\n */\n public org.bitcoinj.wallet.Protos.Script.Builder addWatchedScriptBuilder() {\n return getWatchedScriptFieldBuilder().addBuilder(\n org.bitcoinj.wallet.Protos.Script.getDefaultInstance());\n }\n /**\n * <code>repeated .wallet.Script watched_script = 15;</code>\n */\n public org.bitcoinj.wallet.Protos.Script.Builder addWatchedScriptBuilder(\n int index) {\n return getWatchedScriptFieldBuilder().addBuilder(\n index, org.bitcoinj.wallet.Protos.Script.getDefaultInstance());\n }\n /**\n * <code>repeated .wallet.Script watched_script = 15;</code>\n */\n public java.util.List<org.bitcoinj.wallet.Protos.Script.Builder> \n getWatchedScriptBuilderList() {\n return getWatchedScriptFieldBuilder().getBuilderList();\n }\n private com.google.protobuf.RepeatedFieldBuilder<\n org.bitcoinj.wallet.Protos.Script, org.bitcoinj.wallet.Protos.Script.Builder, org.bitcoinj.wallet.Protos.ScriptOrBuilder> \n getWatchedScriptFieldBuilder() {\n if (watchedScriptBuilder_ == null) {\n watchedScriptBuilder_ = new com.google.protobuf.RepeatedFieldBuilder<\n org.bitcoinj.wallet.Protos.Script, org.bitcoinj.wallet.Protos.Script.Builder, org.bitcoinj.wallet.Protos.ScriptOrBuilder>(\n watchedScript_,\n ((bitField0_ & 0x00000040) == 0x00000040),\n getParentForChildren(),\n isClean());\n watchedScript_ = null;\n }\n return watchedScriptBuilder_;\n }\n\n // optional .wallet.Wallet.EncryptionType encryption_type = 5 [default = UNENCRYPTED];\n private org.bitcoinj.wallet.Protos.Wallet.EncryptionType encryptionType_ = org.bitcoinj.wallet.Protos.Wallet.EncryptionType.UNENCRYPTED;\n /**\n * <code>optional .wallet.Wallet.EncryptionType encryption_type = 5 [default = UNENCRYPTED];</code>\n */\n public boolean hasEncryptionType() {\n return ((bitField0_ & 0x00000080) == 0x00000080);\n }\n /**\n * <code>optional .wallet.Wallet.EncryptionType encryption_type = 5 [default = UNENCRYPTED];</code>\n */\n public org.bitcoinj.wallet.Protos.Wallet.EncryptionType getEncryptionType() {\n return encryptionType_;\n }\n /**\n * <code>optional .wallet.Wallet.EncryptionType encryption_type = 5 [default = UNENCRYPTED];</code>\n */\n public Builder setEncryptionType(org.bitcoinj.wallet.Protos.Wallet.EncryptionType value) {\n if (value == null) {\n throw new NullPointerException();\n }\n bitField0_ |= 0x00000080;\n encryptionType_ = value;\n onChanged();\n return this;\n }\n /**\n * <code>optional .wallet.Wallet.EncryptionType encryption_type = 5 [default = UNENCRYPTED];</code>\n */\n public Builder clearEncryptionType() {\n bitField0_ = (bitField0_ & ~0x00000080);\n encryptionType_ = org.bitcoinj.wallet.Protos.Wallet.EncryptionType.UNENCRYPTED;\n onChanged();\n return this;\n }\n\n // optional .wallet.ScryptParameters encryption_parameters = 6;\n private org.bitcoinj.wallet.Protos.ScryptParameters encryptionParameters_ = org.bitcoinj.wallet.Protos.ScryptParameters.getDefaultInstance();\n private com.google.protobuf.SingleFieldBuilder<\n org.bitcoinj.wallet.Protos.ScryptParameters, org.bitcoinj.wallet.Protos.ScryptParameters.Builder, org.bitcoinj.wallet.Protos.ScryptParametersOrBuilder> encryptionParametersBuilder_;\n /**\n * <code>optional .wallet.ScryptParameters encryption_parameters = 6;</code>\n */\n public boolean hasEncryptionParameters() {\n return ((bitField0_ & 0x00000100) == 0x00000100);\n }\n /**\n * <code>optional .wallet.ScryptParameters encryption_parameters = 6;</code>\n */\n public org.bitcoinj.wallet.Protos.ScryptParameters getEncryptionParameters() {\n if (encryptionParametersBuilder_ == null) {\n return encryptionParameters_;\n } else {\n return encryptionParametersBuilder_.getMessage();\n }\n }\n /**\n * <code>optional .wallet.ScryptParameters encryption_parameters = 6;</code>\n */\n public Builder setEncryptionParameters(org.bitcoinj.wallet.Protos.ScryptParameters value) {\n if (encryptionParametersBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n encryptionParameters_ = value;\n onChanged();\n } else {\n encryptionParametersBuilder_.setMessage(value);\n }\n bitField0_ |= 0x00000100;\n return this;\n }\n /**\n * <code>optional .wallet.ScryptParameters encryption_parameters = 6;</code>\n */\n public Builder setEncryptionParameters(\n org.bitcoinj.wallet.Protos.ScryptParameters.Builder builderForValue) {\n if (encryptionParametersBuilder_ == null) {\n encryptionParameters_ = builderForValue.build();\n onChanged();\n } else {\n encryptionParametersBuilder_.setMessage(builderForValue.build());\n }\n bitField0_ |= 0x00000100;\n return this;\n }\n /**\n * <code>optional .wallet.ScryptParameters encryption_parameters = 6;</code>\n */\n public Builder mergeEncryptionParameters(org.bitcoinj.wallet.Protos.ScryptParameters value) {\n if (encryptionParametersBuilder_ == null) {\n if (((bitField0_ & 0x00000100) == 0x00000100) &&\n encryptionParameters_ != org.bitcoinj.wallet.Protos.ScryptParameters.getDefaultInstance()) {\n encryptionParameters_ =\n org.bitcoinj.wallet.Protos.ScryptParameters.newBuilder(encryptionParameters_).mergeFrom(value).buildPartial();\n } else {\n encryptionParameters_ = value;\n }\n onChanged();\n } else {\n encryptionParametersBuilder_.mergeFrom(value);\n }\n bitField0_ |= 0x00000100;\n return this;\n }\n /**\n * <code>optional .wallet.ScryptParameters encryption_parameters = 6;</code>\n */\n public Builder clearEncryptionParameters() {\n if (encryptionParametersBuilder_ == null) {\n encryptionParameters_ = org.bitcoinj.wallet.Protos.ScryptParameters.getDefaultInstance();\n onChanged();\n } else {\n encryptionParametersBuilder_.clear();\n }\n bitField0_ = (bitField0_ & ~0x00000100);\n return this;\n }\n /**\n * <code>optional .wallet.ScryptParameters encryption_parameters = 6;</code>\n */\n public org.bitcoinj.wallet.Protos.ScryptParameters.Builder getEncryptionParametersBuilder() {\n bitField0_ |= 0x00000100;\n onChanged();\n return getEncryptionParametersFieldBuilder().getBuilder();\n }\n /**\n * <code>optional .wallet.ScryptParameters encryption_parameters = 6;</code>\n */\n public org.bitcoinj.wallet.Protos.ScryptParametersOrBuilder getEncryptionParametersOrBuilder() {\n if (encryptionParametersBuilder_ != null) {\n return encryptionParametersBuilder_.getMessageOrBuilder();\n } else {\n return encryptionParameters_;\n }\n }\n /**\n * <code>optional .wallet.ScryptParameters encryption_parameters = 6;</code>\n */\n private com.google.protobuf.SingleFieldBuilder<\n org.bitcoinj.wallet.Protos.ScryptParameters, org.bitcoinj.wallet.Protos.ScryptParameters.Builder, org.bitcoinj.wallet.Protos.ScryptParametersOrBuilder> \n getEncryptionParametersFieldBuilder() {\n if (encryptionParametersBuilder_ == null) {\n encryptionParametersBuilder_ = new com.google.protobuf.SingleFieldBuilder<\n org.bitcoinj.wallet.Protos.ScryptParameters, org.bitcoinj.wallet.Protos.ScryptParameters.Builder, org.bitcoinj.wallet.Protos.ScryptParametersOrBuilder>(\n encryptionParameters_,\n getParentForChildren(),\n isClean());\n encryptionParameters_ = null;\n }\n return encryptionParametersBuilder_;\n }\n\n // optional int32 version = 7;\n private int version_ ;\n /**\n * <code>optional int32 version = 7;</code>\n *\n * <pre>\n * The version number of the wallet - used to detect wallets that were produced in the future\n * (i.e the wallet may contain some future format this protobuf/ code does not know about)\n * </pre>\n */\n public boolean hasVersion() {\n return ((bitField0_ & 0x00000200) == 0x00000200);\n }\n /**\n * <code>optional int32 version = 7;</code>\n *\n * <pre>\n * The version number of the wallet - used to detect wallets that were produced in the future\n * (i.e the wallet may contain some future format this protobuf/ code does not know about)\n * </pre>\n */\n public int getVersion() {\n return version_;\n }\n /**\n * <code>optional int32 version = 7;</code>\n *\n * <pre>\n * The version number of the wallet - used to detect wallets that were produced in the future\n * (i.e the wallet may contain some future format this protobuf/ code does not know about)\n * </pre>\n */\n public Builder setVersion(int value) {\n bitField0_ |= 0x00000200;\n version_ = value;\n onChanged();\n return this;\n }\n /**\n * <code>optional int32 version = 7;</code>\n *\n * <pre>\n * The version number of the wallet - used to detect wallets that were produced in the future\n * (i.e the wallet may contain some future format this protobuf/ code does not know about)\n * </pre>\n */\n public Builder clearVersion() {\n bitField0_ = (bitField0_ & ~0x00000200);\n version_ = 0;\n onChanged();\n return this;\n }\n\n // repeated .wallet.Extension extension = 10;\n private java.util.List<org.bitcoinj.wallet.Protos.Extension> extension_ =\n java.util.Collections.emptyList();\n private void ensureExtensionIsMutable() {\n if (!((bitField0_ & 0x00000400) == 0x00000400)) {\n extension_ = new java.util.ArrayList<org.bitcoinj.wallet.Protos.Extension>(extension_);\n bitField0_ |= 0x00000400;\n }\n }\n\n private com.google.protobuf.RepeatedFieldBuilder<\n org.bitcoinj.wallet.Protos.Extension, org.bitcoinj.wallet.Protos.Extension.Builder, org.bitcoinj.wallet.Protos.ExtensionOrBuilder> extensionBuilder_;\n\n /**\n * <code>repeated .wallet.Extension extension = 10;</code>\n */\n public java.util.List<org.bitcoinj.wallet.Protos.Extension> getExtensionList() {\n if (extensionBuilder_ == null) {\n return java.util.Collections.unmodifiableList(extension_);\n } else {\n return extensionBuilder_.getMessageList();\n }\n }\n /**\n * <code>repeated .wallet.Extension extension = 10;</code>\n */\n public int getExtensionCount() {\n if (extensionBuilder_ == null) {\n return extension_.size();\n } else {\n return extensionBuilder_.getCount();\n }\n }\n /**\n * <code>repeated .wallet.Extension extension = 10;</code>\n */\n public org.bitcoinj.wallet.Protos.Extension getExtension(int index) {\n if (extensionBuilder_ == null) {\n return extension_.get(index);\n } else {\n return extensionBuilder_.getMessage(index);\n }\n }\n /**\n * <code>repeated .wallet.Extension extension = 10;</code>\n */\n public Builder setExtension(\n int index, org.bitcoinj.wallet.Protos.Extension value) {\n if (extensionBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureExtensionIsMutable();\n extension_.set(index, value);\n onChanged();\n } else {\n extensionBuilder_.setMessage(index, value);\n }\n return this;\n }\n /**\n * <code>repeated .wallet.Extension extension = 10;</code>\n */\n public Builder setExtension(\n int index, org.bitcoinj.wallet.Protos.Extension.Builder builderForValue) {\n if (extensionBuilder_ == null) {\n ensureExtensionIsMutable();\n extension_.set(index, builderForValue.build());\n onChanged();\n } else {\n extensionBuilder_.setMessage(index, builderForValue.build());\n }\n return this;\n }\n /**\n * <code>repeated .wallet.Extension extension = 10;</code>\n */\n public Builder addExtension(org.bitcoinj.wallet.Protos.Extension value) {\n if (extensionBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureExtensionIsMutable();\n extension_.add(value);\n onChanged();\n } else {\n extensionBuilder_.addMessage(value);\n }\n return this;\n }\n /**\n * <code>repeated .wallet.Extension extension = 10;</code>\n */\n public Builder addExtension(\n int index, org.bitcoinj.wallet.Protos.Extension value) {\n if (extensionBuilder_ == null) {\n if (value == null) {\n throw new NullPointerException();\n }\n ensureExtensionIsMutable();\n extension_.add(index, value);\n onChanged();\n } else {\n extensionBuilder_.addMessage(index, value);\n }\n return this;\n }\n /**\n * <code>repeated .wallet.Extension extension = 10;</code>\n */\n public Builder addExtension(\n org.bitcoinj.wallet.Protos.Extension.Builder builderForValue) {\n if (extensionBuilder_ == null) {\n ensureExtensionIsMutable();\n extension_.add(builderForValue.build());\n onChanged();\n } else {\n extensionBuilder_.addMessage(builderForValue.build());\n }\n return this;\n }\n /**\n * <code>repeated .wallet.Extension extension = 10;</code>\n */\n public Builder addExtension(\n int index, org.bitcoinj.wallet.Protos.Extension.Builder builderForValue) {\n if (extensionBuilder_ == null) {\n ensureExtensionIsMutable();\n extension_.add(index, builderForValue.build());\n onChanged();\n } else {\n extensionBuilder_.addMessage(index, builderForValue.build());\n }\n return this;\n }\n /**\n * <code>repeated .wallet.Extension extension = 10;</code>\n */\n public Builder addAllExtension(\n java.lang.Iterable<? extends org.bitcoinj.wallet.Protos.Extension> values) {\n if (extensionBuilder_ == null) {\n ensureExtensionIsMutable();\n super.addAll(values, extension_);\n onChanged();\n } else {\n extensionBuilder_.addAllMessages(values);\n }\n return this;\n }\n /**\n * <code>repeated .wallet.Extension extension = 10;</code>\n */\n public Builder clearExtension() {\n if (extensionBuilder_ == null) {\n extension_ = java.util.Collections.emptyList();\n bitField0_ = (bitField0_ & ~0x00000400);\n onChanged();\n } else {\n extensionBuilder_.clear();\n }\n return this;\n }\n /**\n * <code>repeated .wallet.Extension extension = 10;</code>\n */\n public Builder removeExtension(int index) {\n if (extensionBuilder_ == null) {\n ensureExtensionIsMutable();\n extension_.remove(index);\n onChanged();\n } else {\n extensionBuilder_.remove(index);\n }\n return this;\n }\n /**\n * <code>repeated .wallet.Extension extension = 10;</code>\n */\n public org.bitcoinj.wallet.Protos.Extension.Builder getExtensionBuilder(\n int index) {\n return getExtensionFieldBuilder().getBuilder(index);\n }\n /**\n * <code>repeated .wallet.Extension extension = 10;</code>\n */\n public org.bitcoinj.wallet.Protos.ExtensionOrBuilder getExtensionOrBuilder(\n int index) {\n if (extensionBuilder_ == null) {\n return extension_.get(index); } else {\n return extensionBuilder_.getMessageOrBuilder(index);\n }\n }\n /**\n * <code>repeated .wallet.Extension extension = 10;</code>\n */\n public java.util.List<? extends org.bitcoinj.wallet.Protos.ExtensionOrBuilder> \n getExtensionOrBuilderList() {\n if (extensionBuilder_ != null) {\n return extensionBuilder_.getMessageOrBuilderList();\n } else {\n return java.util.Collections.unmodifiableList(extension_);\n }\n }\n /**\n * <code>repeated .wallet.Extension extension = 10;</code>\n */\n public org.bitcoinj.wallet.Protos.Extension.Builder addExtensionBuilder() {\n return getExtensionFieldBuilder().addBuilder(\n org.bitcoinj.wallet.Protos.Extension.getDefaultInstance());\n }\n /**\n * <code>repeated .wallet.Extension extension = 10;</code>\n */\n public org.bitcoinj.wallet.Protos.Extension.Builder addExtensionBuilder(\n int index) {\n return getExtensionFieldBuilder().addBuilder(\n index, org.bitcoinj.wallet.Protos.Extension.getDefaultInstance());\n }\n /**\n * <code>repeated .wallet.Extension extension = 10;</code>\n */\n public java.util.List<org.bitcoinj.wallet.Protos.Extension.Builder> \n getExtensionBuilderList() {\n return getExtensionFieldBuilder().getBuilderList();\n }\n private com.google.protobuf.RepeatedFieldBuilder<\n org.bitcoinj.wallet.Protos.Extension, org.bitcoinj.wallet.Protos.Extension.Builder, org.bitcoinj.wallet.Protos.ExtensionOrBuilder> \n getExtensionFieldBuilder() {\n if (extensionBuilder_ == null) {\n extensionBuilder_ = new com.google.protobuf.RepeatedFieldBuilder<\n org.bitcoinj.wallet.Protos.Extension, org.bitcoinj.wallet.Protos.Extension.Builder, org.bitcoinj.wallet.Protos.ExtensionOrBuilder>(\n extension_,\n ((bitField0_ & 0x00000400) == 0x00000400),\n getParentForChildren(),\n isClean());\n extension_ = null;\n }\n return extensionBuilder_;\n }\n\n // optional string description = 11;\n private java.lang.Object description_ = \"\";\n /**\n * <code>optional string description = 11;</code>\n *\n * <pre>\n * A UTF8 encoded text description of the wallet that is intended for end user provided text.\n * </pre>\n */\n public boolean hasDescription() {\n return ((bitField0_ & 0x00000800) == 0x00000800);\n }\n /**\n * <code>optional string description = 11;</code>\n *\n * <pre>\n * A UTF8 encoded text description of the wallet that is intended for end user provided text.\n * </pre>\n */\n public java.lang.String getDescription() {\n java.lang.Object ref = description_;\n if (!(ref instanceof java.lang.String)) {\n java.lang.String s = ((com.google.protobuf.ByteString) ref)\n .toStringUtf8();\n description_ = s;\n return s;\n } else {\n return (java.lang.String) ref;\n }\n }\n /**\n * <code>optional string description = 11;</code>\n *\n * <pre>\n * A UTF8 encoded text description of the wallet that is intended for end user provided text.\n * </pre>\n */\n public com.google.protobuf.ByteString\n getDescriptionBytes() {\n java.lang.Object ref = description_;\n if (ref instanceof String) {\n com.google.protobuf.ByteString b = \n com.google.protobuf.ByteString.copyFromUtf8(\n (java.lang.String) ref);\n description_ = b;\n return b;\n } else {\n return (com.google.protobuf.ByteString) ref;\n }\n }\n /**\n * <code>optional string description = 11;</code>\n *\n * <pre>\n * A UTF8 encoded text description of the wallet that is intended for end user provided text.\n * </pre>\n */\n public Builder setDescription(\n java.lang.String value) {\n if (value == null) {\n throw new NullPointerException();\n }\n bitField0_ |= 0x00000800;\n description_ = value;\n onChanged();\n return this;\n }\n /**\n * <code>optional string description = 11;</code>\n *\n * <pre>\n * A UTF8 encoded text description of the wallet that is intended for end user provided text.\n * </pre>\n */\n public Builder clearDescription() {\n bitField0_ = (bitField0_ & ~0x00000800);\n description_ = getDefaultInstance().getDescription();\n onChanged();\n return this;\n }\n /**\n * <code>optional string description = 11;</code>\n *\n * <pre>\n * A UTF8 encoded text description of the wallet that is intended for end user provided text.\n * </pre>\n */\n public Builder setDescriptionBytes(\n com.google.protobuf.ByteString value) {\n if (value == null) {\n throw new NullPointerException();\n }\n bitField0_ |= 0x00000800;\n description_ = value;\n onChanged();\n return this;\n }\n\n // optional uint64 key_rotation_time = 13;\n private long keyRotationTime_ ;\n /**\n * <code>optional uint64 key_rotation_time = 13;</code>\n *\n * <pre>\n * UNIX time in seconds since the epoch. If set, then any keys created before this date are assumed to be no longer\n * wanted. Money sent to them will be re-spent automatically to the first key that was created after this time. It\n * can be used to recover a compromised wallet, or just as part of preventative defence-in-depth measures.\n * </pre>\n */\n public boolean hasKeyRotationTime() {\n return ((bitField0_ & 0x00001000) == 0x00001000);\n }\n /**\n * <code>optional uint64 key_rotation_time = 13;</code>\n *\n * <pre>\n * UNIX time in seconds since the epoch. If set, then any keys created before this date are assumed to be no longer\n * wanted. Money sent to them will be re-spent automatically to the first key that was created after this time. It\n * can be used to recover a compromised wallet, or just as part of preventative defence-in-depth measures.\n * </pre>\n */\n public long getKeyRotationTime() {\n return keyRotationTime_;\n }\n /**\n * <code>optional uint64 key_rotation_time = 13;</code>\n *\n * <pre>\n * UNIX time in seconds since the epoch. If set, then any keys created before this date are assumed to be no longer\n * wanted. Money sent to them will be re-spent automatically to the first key that was created after this time. It\n * can be used to recover a compromised wallet, or just as part of preventative defence-in-depth measures.\n * </pre>\n */\n public Builder setKeyRotationTime(long value) {\n bitField0_ |= 0x00001000;\n keyRotationTime_ = value;\n onChanged();\n return this;\n }\n /**\n * <code>optional uint64 key_rotation_time = 13;</code>\n *\n * <pre>\n * UNIX time in seconds since the epoch. If set, then any keys created before this date are assumed to be no longer\n * wanted. Money sent to them will be re-spent automatically to the first key that was created after this time. It\n * can be used to recover a compromised wallet, or just as part of preventative defence-in-depth measures.\n * </pre>\n */\n public Builder clearKeyRotationTime() {\n bitField0_ = (bitField0_ & ~0x00001000);\n keyRotationTime_ = 0L;\n onChanged();\n return this;\n }\n\n // @@protoc_insertion_point(builder_scope:wallet.Wallet)\n }\n\n static {\n defaultInstance = new Wallet(true);\n defaultInstance.initFields();\n }\n\n // @@protoc_insertion_point(class_scope:wallet.Wallet)\n }\n\n private static com.google.protobuf.Descriptors.Descriptor\n internal_static_wallet_PeerAddress_descriptor;\n private static\n com.google.protobuf.GeneratedMessage.FieldAccessorTable\n internal_static_wallet_PeerAddress_fieldAccessorTable;\n private static com.google.protobuf.Descriptors.Descriptor\n internal_static_wallet_EncryptedPrivateKey_descriptor;\n private static\n com.google.protobuf.GeneratedMessage.FieldAccessorTable\n internal_static_wallet_EncryptedPrivateKey_fieldAccessorTable;\n private static com.google.protobuf.Descriptors.Descriptor\n internal_static_wallet_Key_descriptor;\n private static\n com.google.protobuf.GeneratedMessage.FieldAccessorTable\n internal_static_wallet_Key_fieldAccessorTable;\n private static com.google.protobuf.Descriptors.Descriptor\n internal_static_wallet_Script_descriptor;\n private static\n com.google.protobuf.GeneratedMessage.FieldAccessorTable\n internal_static_wallet_Script_fieldAccessorTable;\n private static com.google.protobuf.Descriptors.Descriptor\n internal_static_wallet_TransactionInput_descriptor;\n private static\n com.google.protobuf.GeneratedMessage.FieldAccessorTable\n internal_static_wallet_TransactionInput_fieldAccessorTable;\n private static com.google.protobuf.Descriptors.Descriptor\n internal_static_wallet_TransactionOutput_descriptor;\n private static\n com.google.protobuf.GeneratedMessage.FieldAccessorTable\n internal_static_wallet_TransactionOutput_fieldAccessorTable;\n private static com.google.protobuf.Descriptors.Descriptor\n internal_static_wallet_TransactionConfidence_descriptor;\n private static\n com.google.protobuf.GeneratedMessage.FieldAccessorTable\n internal_static_wallet_TransactionConfidence_fieldAccessorTable;\n private static com.google.protobuf.Descriptors.Descriptor\n internal_static_wallet_Transaction_descriptor;\n private static\n com.google.protobuf.GeneratedMessage.FieldAccessorTable\n internal_static_wallet_Transaction_fieldAccessorTable;\n private static com.google.protobuf.Descriptors.Descriptor\n internal_static_wallet_ScryptParameters_descriptor;\n private static\n com.google.protobuf.GeneratedMessage.FieldAccessorTable\n internal_static_wallet_ScryptParameters_fieldAccessorTable;\n private static com.google.protobuf.Descriptors.Descriptor\n internal_static_wallet_Extension_descriptor;\n private static\n com.google.protobuf.GeneratedMessage.FieldAccessorTable\n internal_static_wallet_Extension_fieldAccessorTable;\n private static com.google.protobuf.Descriptors.Descriptor\n internal_static_wallet_Wallet_descriptor;\n private static\n com.google.protobuf.GeneratedMessage.FieldAccessorTable\n internal_static_wallet_Wallet_fieldAccessorTable;\n\n public static com.google.protobuf.Descriptors.FileDescriptor\n getDescriptor() {\n return descriptor;\n }\n private static com.google.protobuf.Descriptors.FileDescriptor\n descriptor;\n static {\n java.lang.String[] descriptorData = {\n \"\\n\\rmonacoin.proto\\022\\006wallet\\\"A\\n\\013PeerAddress\\022\\022\" +\n \"\\n\\nip_address\\030\\001 \\002(\\014\\022\\014\\n\\004port\\030\\002 \\002(\\r\\022\\020\\n\\010serv\" +\n \"ices\\030\\003 \\002(\\004\\\"S\\n\\023EncryptedPrivateKey\\022\\035\\n\\025ini\" +\n \"tialisation_vector\\030\\001 \\002(\\014\\022\\035\\n\\025encrypted_pr\" +\n \"ivate_key\\030\\002 \\002(\\014\\\"\\345\\001\\n\\003Key\\022\\036\\n\\004type\\030\\001 \\002(\\0162\\020.\" +\n \"wallet.Key.Type\\022\\023\\n\\013private_key\\030\\002 \\001(\\014\\022:\\n\\025\" +\n \"encrypted_private_key\\030\\006 \\001(\\0132\\033.wallet.Enc\" +\n \"ryptedPrivateKey\\022\\022\\n\\npublic_key\\030\\003 \\001(\\014\\022\\r\\n\\005\" +\n \"label\\030\\004 \\001(\\t\\022\\032\\n\\022creation_timestamp\\030\\005 \\001(\\003\\\"\" +\n \".\\n\\004Type\\022\\014\\n\\010ORIGINAL\\020\\001\\022\\030\\n\\024ENCRYPTED_SCRYP\",\n \"T_AES\\020\\002\\\"5\\n\\006Script\\022\\017\\n\\007program\\030\\001 \\002(\\014\\022\\032\\n\\022cr\" +\n \"eation_timestamp\\030\\002 \\002(\\003\\\"\\203\\001\\n\\020TransactionIn\" +\n \"put\\022\\\"\\n\\032transaction_out_point_hash\\030\\001 \\002(\\014\\022\" +\n \"#\\n\\033transaction_out_point_index\\030\\002 \\002(\\r\\022\\024\\n\\014\" +\n \"script_bytes\\030\\003 \\002(\\014\\022\\020\\n\\010sequence\\030\\004 \\001(\\r\\\"\\177\\n\\021\" +\n \"TransactionOutput\\022\\r\\n\\005value\\030\\001 \\002(\\003\\022\\024\\n\\014scri\" +\n \"pt_bytes\\030\\002 \\002(\\014\\022!\\n\\031spent_by_transaction_h\" +\n \"ash\\030\\003 \\001(\\014\\022\\\"\\n\\032spent_by_transaction_index\\030\" +\n \"\\004 \\001(\\005\\\"\\234\\003\\n\\025TransactionConfidence\\0220\\n\\004type\\030\" +\n \"\\001 \\001(\\0162\\\".wallet.TransactionConfidence.Typ\",\n \"e\\022\\032\\n\\022appeared_at_height\\030\\002 \\001(\\005\\022\\036\\n\\026overrid\" +\n \"ing_transaction\\030\\003 \\001(\\014\\022\\r\\n\\005depth\\030\\004 \\001(\\005\\022\\021\\n\\t\" +\n \"work_done\\030\\005 \\001(\\003\\022)\\n\\014broadcast_by\\030\\006 \\003(\\0132\\023.\" +\n \"wallet.PeerAddress\\0224\\n\\006source\\030\\007 \\001(\\0162$.wal\" +\n \"let.TransactionConfidence.Source\\\"O\\n\\004Type\" +\n \"\\022\\013\\n\\007UNKNOWN\\020\\000\\022\\014\\n\\010BUILDING\\020\\001\\022\\013\\n\\007PENDING\\020\\002\" +\n \"\\022\\025\\n\\021NOT_IN_BEST_CHAIN\\020\\003\\022\\010\\n\\004DEAD\\020\\004\\\"A\\n\\006Sou\" +\n \"rce\\022\\022\\n\\016SOURCE_UNKNOWN\\020\\000\\022\\022\\n\\016SOURCE_NETWOR\" +\n \"K\\020\\001\\022\\017\\n\\013SOURCE_SELF\\020\\002\\\"\\236\\004\\n\\013Transaction\\022\\017\\n\\007\" +\n \"version\\030\\001 \\002(\\005\\022\\014\\n\\004hash\\030\\002 \\002(\\014\\022&\\n\\004pool\\030\\003 \\001(\",\n \"\\0162\\030.wallet.Transaction.Pool\\022\\021\\n\\tlock_time\" +\n \"\\030\\004 \\001(\\r\\022\\022\\n\\nupdated_at\\030\\005 \\001(\\003\\0223\\n\\021transactio\" +\n \"n_input\\030\\006 \\003(\\0132\\030.wallet.TransactionInput\\022\" +\n \"5\\n\\022transaction_output\\030\\007 \\003(\\0132\\031.wallet.Tra\" +\n \"nsactionOutput\\022\\022\\n\\nblock_hash\\030\\010 \\003(\\014\\022 \\n\\030bl\" +\n \"ock_relativity_offsets\\030\\013 \\003(\\005\\0221\\n\\nconfiden\" +\n \"ce\\030\\t \\001(\\0132\\035.wallet.TransactionConfidence\\022\" +\n \"5\\n\\007purpose\\030\\n \\001(\\0162\\033.wallet.Transaction.Pu\" +\n \"rpose:\\007UNKNOWN\\\"Y\\n\\004Pool\\022\\013\\n\\007UNSPENT\\020\\004\\022\\t\\n\\005S\" +\n \"PENT\\020\\005\\022\\014\\n\\010INACTIVE\\020\\002\\022\\010\\n\\004DEAD\\020\\n\\022\\013\\n\\007PENDIN\",\n \"G\\020\\020\\022\\024\\n\\020PENDING_INACTIVE\\020\\022\\\":\\n\\007Purpose\\022\\013\\n\\007\" +\n \"UNKNOWN\\020\\000\\022\\020\\n\\014USER_PAYMENT\\020\\001\\022\\020\\n\\014KEY_ROTAT\" +\n \"ION\\020\\002\\\"N\\n\\020ScryptParameters\\022\\014\\n\\004salt\\030\\001 \\002(\\014\\022\" +\n \"\\020\\n\\001n\\030\\002 \\001(\\003:\\00516384\\022\\014\\n\\001r\\030\\003 \\001(\\005:\\0018\\022\\014\\n\\001p\\030\\004 \\001\" +\n \"(\\005:\\0011\\\"8\\n\\tExtension\\022\\n\\n\\002id\\030\\001 \\002(\\t\\022\\014\\n\\004data\\030\\002\" +\n \" \\002(\\014\\022\\021\\n\\tmandatory\\030\\003 \\002(\\010\\\"\\223\\004\\n\\006Wallet\\022\\032\\n\\022ne\" +\n \"twork_identifier\\030\\001 \\002(\\t\\022\\034\\n\\024last_seen_bloc\" +\n \"k_hash\\030\\002 \\001(\\014\\022\\036\\n\\026last_seen_block_height\\030\\014\" +\n \" \\001(\\r\\022!\\n\\031last_seen_block_time_secs\\030\\016 \\001(\\003\\022\" +\n \"\\030\\n\\003key\\030\\003 \\003(\\0132\\013.wallet.Key\\022(\\n\\013transaction\",\n \"\\030\\004 \\003(\\0132\\023.wallet.Transaction\\022&\\n\\016watched_s\" +\n \"cript\\030\\017 \\003(\\0132\\016.wallet.Script\\022C\\n\\017encryptio\" +\n \"n_type\\030\\005 \\001(\\0162\\035.wallet.Wallet.EncryptionT\" +\n \"ype:\\013UNENCRYPTED\\0227\\n\\025encryption_parameter\" +\n \"s\\030\\006 \\001(\\0132\\030.wallet.ScryptParameters\\022\\017\\n\\007ver\" +\n \"sion\\030\\007 \\001(\\005\\022$\\n\\textension\\030\\n \\003(\\0132\\021.wallet.E\" +\n \"xtension\\022\\023\\n\\013description\\030\\013 \\001(\\t\\022\\031\\n\\021key_rot\" +\n \"ation_time\\030\\r \\001(\\004\\\";\\n\\016EncryptionType\\022\\017\\n\\013UN\" +\n \"ENCRYPTED\\020\\001\\022\\030\\n\\024ENCRYPTED_SCRYPT_AES\\020\\002B\\035\\n\" +\n \"\\023org.bitcoinj.walletB\\006Protos\"\n };\n com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =\n new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() {\n public com.google.protobuf.ExtensionRegistry assignDescriptors(\n com.google.protobuf.Descriptors.FileDescriptor root) {\n descriptor = root;\n internal_static_wallet_PeerAddress_descriptor =\n getDescriptor().getMessageTypes().get(0);\n internal_static_wallet_PeerAddress_fieldAccessorTable = new\n com.google.protobuf.GeneratedMessage.FieldAccessorTable(\n internal_static_wallet_PeerAddress_descriptor,\n new java.lang.String[] { \"IpAddress\", \"Port\", \"Services\", });\n internal_static_wallet_EncryptedPrivateKey_descriptor =\n getDescriptor().getMessageTypes().get(1);\n internal_static_wallet_EncryptedPrivateKey_fieldAccessorTable = new\n com.google.protobuf.GeneratedMessage.FieldAccessorTable(\n internal_static_wallet_EncryptedPrivateKey_descriptor,\n new java.lang.String[] { \"InitialisationVector\", \"EncryptedPrivateKey\", });\n internal_static_wallet_Key_descriptor =\n getDescriptor().getMessageTypes().get(2);\n internal_static_wallet_Key_fieldAccessorTable = new\n com.google.protobuf.GeneratedMessage.FieldAccessorTable(\n internal_static_wallet_Key_descriptor,\n new java.lang.String[] { \"Type\", \"PrivateKey\", \"EncryptedPrivateKey\", \"PublicKey\", \"Label\", \"CreationTimestamp\", });\n internal_static_wallet_Script_descriptor =\n getDescriptor().getMessageTypes().get(3);\n internal_static_wallet_Script_fieldAccessorTable = new\n com.google.protobuf.GeneratedMessage.FieldAccessorTable(\n internal_static_wallet_Script_descriptor,\n new java.lang.String[] { \"Program\", \"CreationTimestamp\", });\n internal_static_wallet_TransactionInput_descriptor =\n getDescriptor().getMessageTypes().get(4);\n internal_static_wallet_TransactionInput_fieldAccessorTable = new\n com.google.protobuf.GeneratedMessage.FieldAccessorTable(\n internal_static_wallet_TransactionInput_descriptor,\n new java.lang.String[] { \"TransactionOutPointHash\", \"TransactionOutPointIndex\", \"ScriptBytes\", \"Sequence\", });\n internal_static_wallet_TransactionOutput_descriptor =\n getDescriptor().getMessageTypes().get(5);\n internal_static_wallet_TransactionOutput_fieldAccessorTable = new\n com.google.protobuf.GeneratedMessage.FieldAccessorTable(\n internal_static_wallet_TransactionOutput_descriptor,\n new java.lang.String[] { \"Value\", \"ScriptBytes\", \"SpentByTransactionHash\", \"SpentByTransactionIndex\", });\n internal_static_wallet_TransactionConfidence_descriptor =\n getDescriptor().getMessageTypes().get(6);\n internal_static_wallet_TransactionConfidence_fieldAccessorTable = new\n com.google.protobuf.GeneratedMessage.FieldAccessorTable(\n internal_static_wallet_TransactionConfidence_descriptor,\n new java.lang.String[] { \"Type\", \"AppearedAtHeight\", \"OverridingTransaction\", \"Depth\", \"WorkDone\", \"BroadcastBy\", \"Source\", });\n internal_static_wallet_Transaction_descriptor =\n getDescriptor().getMessageTypes().get(7);\n internal_static_wallet_Transaction_fieldAccessorTable = new\n com.google.protobuf.GeneratedMessage.FieldAccessorTable(\n internal_static_wallet_Transaction_descriptor,\n new java.lang.String[] { \"Version\", \"Hash\", \"Pool\", \"LockTime\", \"UpdatedAt\", \"TransactionInput\", \"TransactionOutput\", \"BlockHash\", \"BlockRelativityOffsets\", \"Confidence\", \"Purpose\", });\n internal_static_wallet_ScryptParameters_descriptor =\n getDescriptor().getMessageTypes().get(8);\n internal_static_wallet_ScryptParameters_fieldAccessorTable = new\n com.google.protobuf.GeneratedMessage.FieldAccessorTable(\n internal_static_wallet_ScryptParameters_descriptor,\n new java.lang.String[] { \"Salt\", \"N\", \"R\", \"P\", });\n internal_static_wallet_Extension_descriptor =\n getDescriptor().getMessageTypes().get(9);\n internal_static_wallet_Extension_fieldAccessorTable = new\n com.google.protobuf.GeneratedMessage.FieldAccessorTable(\n internal_static_wallet_Extension_descriptor,\n new java.lang.String[] { \"Id\", \"Data\", \"Mandatory\", });\n internal_static_wallet_Wallet_descriptor =\n getDescriptor().getMessageTypes().get(10);\n internal_static_wallet_Wallet_fieldAccessorTable = new\n com.google.protobuf.GeneratedMessage.FieldAccessorTable(\n internal_static_wallet_Wallet_descriptor,\n new java.lang.String[] { \"NetworkIdentifier\", \"LastSeenBlockHash\", \"LastSeenBlockHeight\", \"LastSeenBlockTimeSecs\", \"Key\", \"Transaction\", \"WatchedScript\", \"EncryptionType\", \"EncryptionParameters\", \"Version\", \"Extension\", \"Description\", \"KeyRotationTime\", });\n return null;\n }\n };\n com.google.protobuf.Descriptors.FileDescriptor\n .internalBuildGeneratedFileFrom(descriptorData,\n new com.google.protobuf.Descriptors.FileDescriptor[] {\n }, assigner);\n }\n\n // @@protoc_insertion_point(outer_class_scope)\n}",
"public enum EncryptionType\n implements com.google.protobuf.ProtocolMessageEnum {\n /**\n * <code>UNENCRYPTED = 1;</code>\n *\n * <pre>\n * All keys in the wallet are unencrypted\n * </pre>\n */\n UNENCRYPTED(0, 1),\n /**\n * <code>ENCRYPTED_SCRYPT_AES = 2;</code>\n *\n * <pre>\n * All keys are encrypted with a passphrase based KDF of scrypt and AES encryption\n * </pre>\n */\n ENCRYPTED_SCRYPT_AES(1, 2),\n ;\n\n /**\n * <code>UNENCRYPTED = 1;</code>\n *\n * <pre>\n * All keys in the wallet are unencrypted\n * </pre>\n */\n public static final int UNENCRYPTED_VALUE = 1;\n /**\n * <code>ENCRYPTED_SCRYPT_AES = 2;</code>\n *\n * <pre>\n * All keys are encrypted with a passphrase based KDF of scrypt and AES encryption\n * </pre>\n */\n public static final int ENCRYPTED_SCRYPT_AES_VALUE = 2;\n\n\n public final int getNumber() { return value; }\n\n public static EncryptionType valueOf(int value) {\n switch (value) {\n case 1: return UNENCRYPTED;\n case 2: return ENCRYPTED_SCRYPT_AES;\n default: return null;\n }\n }\n\n public static com.google.protobuf.Internal.EnumLiteMap<EncryptionType>\n internalGetValueMap() {\n return internalValueMap;\n }\n private static com.google.protobuf.Internal.EnumLiteMap<EncryptionType>\n internalValueMap =\n new com.google.protobuf.Internal.EnumLiteMap<EncryptionType>() {\n public EncryptionType findValueByNumber(int number) {\n return EncryptionType.valueOf(number);\n }\n };\n\n public final com.google.protobuf.Descriptors.EnumValueDescriptor\n getValueDescriptor() {\n return getDescriptor().getValues().get(index);\n }\n public final com.google.protobuf.Descriptors.EnumDescriptor\n getDescriptorForType() {\n return getDescriptor();\n }\n public static final com.google.protobuf.Descriptors.EnumDescriptor\n getDescriptor() {\n return org.bitcoinj.wallet.Protos.Wallet.getDescriptor().getEnumTypes().get(0);\n }\n\n private static final EncryptionType[] VALUES = values();\n\n public static EncryptionType valueOf(\n com.google.protobuf.Descriptors.EnumValueDescriptor desc) {\n if (desc.getType() != getDescriptor()) {\n throw new java.lang.IllegalArgumentException(\n \"EnumValueDescriptor is not for this type.\");\n }\n return VALUES[desc.getIndex()];\n }\n\n private final int index;\n private final int value;\n\n private EncryptionType(int index, int value) {\n this.index = index;\n this.value = value;\n }\n\n // @@protoc_insertion_point(enum_scope:wallet.Wallet.EncryptionType)\n}"
] | import com.google.bitcoin.core.*;
import com.google.bitcoin.core.TransactionConfidence.ConfidenceType;
import com.google.bitcoin.crypto.EncryptedPrivateKey;
import com.google.bitcoin.crypto.KeyCrypter;
import com.google.bitcoin.crypto.KeyCrypterScrypt;
import com.google.bitcoin.script.Script;
import com.google.bitcoin.store.UnreadableWalletException;
import com.google.bitcoin.store.WalletProtobufSerializer;
import com.google.bitcoin.wallet.WalletTransaction;
import com.google.common.collect.Lists;
import com.google.protobuf.ByteString;
import com.google.protobuf.TextFormat;
import org.bitcoinj.wallet.Protos;
import org.bitcoinj.wallet.Protos.Wallet.EncryptionType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import static com.google.common.base.Preconditions.checkNotNull; | /**
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.multibit.store;
/**
* Serialize and de-serialize a wallet to a byte stream containing a
* <a href="http://code.google.com/apis/protocolbuffers/docs/overview.html">protocol buffer</a>. Protocol buffers are
* a data interchange format developed by Google with an efficient binary representation, a type safe specification
* language and compilers that generate code to work with those data structures for many languages. Protocol buffers
* can have their format evolved over time: conceptually they represent data using (tag, length, value) tuples. The
* format is defined by the <tt>monacoin.proto</tt> file in the bitcoinj source distribution.<p>
*
* This class is used through its static methods. The most common operations are writeWallet and readWallet, which do
* the obvious operations on Output/InputStreams. You can use a {@link java.io.ByteArrayInputStream} and equivalent
* {@link java.io.ByteArrayOutputStream} if you'd like byte arrays instead. The protocol buffer can also be manipulated
* in its object form if you'd like to modify the flattened data structure before serialization to binary.<p>
*
* You can extend the wallet format with additional fields specific to your application if you want, but make sure
* to either put the extra data in the provided extension areas, or select tag numbers that are unlikely to be used
* by anyone else.<p>
*
* @author Miron Cuperman
*/
public class MultiBitWalletProtobufSerializer extends WalletProtobufSerializer {
private static final Logger log = LoggerFactory.getLogger(MultiBitWalletProtobufSerializer.class);
// Early version of name-value value for use in protecting encrypted wallets from being loaded
// into earlier versions of MultiBit. Unfortunately I merged this into the MultiBit v0.4 code by mistake.
// @deprecated replaced by ORG_MULTIBIT_WALLET_PROTECT_2
public static final String ORG_MULTIBIT_WALLET_PROTECT = "org.multibit.walletProtect";
public static final String ORG_MULTIBIT_WALLET_PROTECT_2 = "org.multibit.walletProtect.2";
public MultiBitWalletProtobufSerializer() {
super();
}
/**
* Formats the given wallet (transactions and keys) to the given output stream in protocol buffer format.<p>
*
* Equivalent to <tt>walletToProto(wallet).writeTo(output);</tt>
*/
public void writeWallet(Wallet wallet, OutputStream output) throws IOException {
Protos.Wallet walletProto = walletToProto(wallet);
walletProto.writeTo(output);
}
/**
* Returns the given wallet formatted as text. The text format is that used by protocol buffers and although it
* can also be parsed using {@link TextFormat#merge(CharSequence, com.google.protobuf.Message.Builder)},
* it is designed more for debugging than storage. It is not well specified and wallets are largely binary data
* structures anyway, consisting as they do of keys (large random numbers) and {@link Transaction}s which also
* mostly contain keys and hashes.
*/
public String walletToText(Wallet wallet) {
Protos.Wallet walletProto = walletToProto(wallet);
return TextFormat.printToString(walletProto);
}
/**
* Converts the given wallet to the object representation of the protocol buffers. This can be modified, or
* additional data fields set, before serialization takes place.
*/
public Protos.Wallet walletToProto(Wallet wallet) {
Protos.Wallet.Builder walletBuilder = Protos.Wallet.newBuilder();
walletBuilder.setNetworkIdentifier(wallet.getNetworkParameters().getId());
if (wallet.getDescription() != null) {
walletBuilder.setDescription(wallet.getDescription());
}
for (WalletTransaction wtx : wallet.getWalletTransactions()) {
Protos.Transaction txProto = makeTxProto(wtx);
walletBuilder.addTransaction(txProto);
}
for (ECKey key : wallet.getKeys()) {
Protos.Key.Builder keyBuilder = Protos.Key.newBuilder().setCreationTimestamp(key.getCreationTimeSeconds() * 1000)
// .setLabel() TODO
.setType(Protos.Key.Type.ORIGINAL);
if (key.getPrivKeyBytes() != null)
keyBuilder.setPrivateKey(ByteString.copyFrom(key.getPrivKeyBytes()));
EncryptedPrivateKey encryptedPrivateKey = key.getEncryptedPrivateKey();
if (encryptedPrivateKey != null) {
// Key is encrypted.
Protos.EncryptedPrivateKey.Builder encryptedKeyBuilder = Protos.EncryptedPrivateKey.newBuilder()
.setEncryptedPrivateKey(ByteString.copyFrom(encryptedPrivateKey.getEncryptedBytes()))
.setInitialisationVector(ByteString.copyFrom(encryptedPrivateKey.getInitialisationVector()));
if (key.getKeyCrypter() == null) {
throw new IllegalStateException("The encrypted key " + key.toString() + " has no KeyCrypter.");
} else {
// If it is a Scrypt + AES encrypted key, set the persisted key type. | if (key.getKeyCrypter().getUnderstoodEncryptionType() == Protos.Wallet.EncryptionType.ENCRYPTED_SCRYPT_AES) { | 4 |
apache/incubator-taverna-mobile | app/src/androidTest/java/org/apache/taverna/mobile/announcement/AnnouncementActivityTest.java | [
"public class FakeRemoteDataSource {\n\n private static TestDataFactory mTestDataFactory = new TestDataFactory();\n\n\n public static Announcements getAnnouncements() {\n return mTestDataFactory.getObjectTypeBean(Announcements.class, FakeXMLName\n .ANNOUNCEMENTS_XML);\n }\n\n public static DetailAnnouncement getAnnouncement() {\n return mTestDataFactory.getObjectTypeBean(DetailAnnouncement.class,\n FakeXMLName.ANNOUNCEMENT_XML);\n }\n\n public static Workflows getWorkflowList() {\n return mTestDataFactory.getObjectTypeBean(Workflows.class, FakeXMLName.WORKFLOWS_XML);\n }\n\n\n public static User getLoginUser() {\n return mTestDataFactory.getObjectTypeBean(User.class, FakeXMLName.USER_XML);\n }\n}",
"public class SingleFragmentActivity extends BaseActivity {\n FrameLayout content;\n\n @Override\n protected void onCreate(@Nullable Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n content = new FrameLayout(this);\n content.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,\n ViewGroup.LayoutParams.MATCH_PARENT));\n content.setId(R.id.container1);\n setContentView(content);\n }\n\n public void setFragment(Fragment fragment) {\n\n getSupportFragmentManager().beginTransaction()\n .add(R.id.container1, fragment, \"TEST\")\n .commit();\n }\n\n public void replaceFragment(Fragment fragment) {\n getSupportFragmentManager().beginTransaction()\n .replace(R.id.container1, fragment).commit();\n }\n\n}",
"public class TestComponentRule implements TestRule {\n\n private final TestComponent mTestComponent;\n private final Context mContext;\n\n private Scheduler schedulerInstance = Schedulers.trampoline();\n\n private Function<Scheduler, Scheduler> schedulerMapper = new Function<Scheduler, Scheduler>() {\n @Override\n public Scheduler apply(Scheduler scheduler) throws Exception {\n return schedulerInstance;\n }\n };\n private Function<Callable<Scheduler>, Scheduler> schedulerMapperLazy =\n new Function<Callable<Scheduler>, Scheduler>() {\n\n\n @Override\n public Scheduler apply(Callable<Scheduler> schedulerCallable) throws Exception {\n return schedulerInstance;\n }\n };\n\n public TestComponentRule(Context context) {\n mContext = context;\n TavernaApplication application = TavernaApplication.get(context);\n mTestComponent = DaggerTestComponent.builder()\n .applicationTestModule(new ApplicationTestModule(application))\n .build();\n }\n\n public Context getContext() {\n return mContext;\n }\n\n public DataManager getMockDataManager() {\n return mTestComponent.dataManager();\n }\n\n @Override\n public Statement apply(final Statement base, Description description) {\n return new Statement() {\n @Override\n public void evaluate() throws Throwable {\n RxAndroidPlugins.reset();\n RxAndroidPlugins.setInitMainThreadSchedulerHandler(schedulerMapperLazy);\n\n RxJavaPlugins.reset();\n RxJavaPlugins.setIoSchedulerHandler(schedulerMapper);\n RxJavaPlugins.setNewThreadSchedulerHandler(schedulerMapper);\n RxJavaPlugins.setComputationSchedulerHandler(schedulerMapper);\n\n TavernaApplication application = TavernaApplication.get(mContext);\n application.setComponent(mTestComponent);\n\n base.evaluate();\n application.setComponent(null);\n RxAndroidPlugins.reset();\n RxJavaPlugins.reset();\n }\n };\n }\n}",
"@Root(name = \"announcements\")\npublic class Announcements implements Parcelable {\n\n @ElementList(name = \"announcement\", inline = true, required = false)\n List<Announcement> announcement;\n\n public List<Announcement> getAnnouncement() {\n return this.announcement;\n }\n\n public void setAnnouncement(List<Announcement> _value) {\n this.announcement = _value;\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeTypedList(this.announcement);\n }\n\n public Announcements() {\n }\n\n protected Announcements(Parcel in) {\n this.announcement = in.createTypedArrayList(Announcement.CREATOR);\n }\n\n public static final Parcelable.Creator<Announcements> CREATOR = new Parcelable\n .Creator<Announcements>() {\n @Override\n public Announcements createFromParcel(Parcel source) {\n return new Announcements(source);\n }\n\n @Override\n public Announcements[] newArray(int size) {\n return new Announcements[size];\n }\n };\n}",
"public class AnnouncementFragment extends Fragment implements RecyclerItemClickListner\n .OnItemClickListener, AnnouncementMvpView {\n\n public final String LOG_TAG = getClass().getSimpleName();\n\n @Inject\n DataManager dataManager;\n\n @Inject\n AnnouncementPresenter mAnnouncementPresenter;\n\n AnnouncementAdapter mAnnouncementAdapter;\n\n @BindView(R.id.rv_movies)\n RecyclerView mRecyclerView;\n\n @BindView(R.id.swipe_refresh)\n ScrollChildSwipeRefreshLayout mSwipeRefresh;\n\n @BindView(R.id.progress_circular)\n ProgressBar mProgressBar;\n\n private AlertDialog alertDialog;\n\n private ProgressDialog dialog;\n\n private Announcements mAnnouncements;\n\n private int mPageNumber = 1;\n\n private DetailAnnouncement mAnnouncementDetail;\n\n\n @Override\n public void onItemClick(View childView, int position) {\n if (mAnnouncements.getAnnouncement().get(position) != null && position != -1) {\n showWaitProgress(true);\n mAnnouncementPresenter.loadAnnouncementDetails(mAnnouncements.getAnnouncement()\n .get(position).getId());\n }\n }\n\n @Override\n public void onItemLongPress(View childView, int position) {\n\n }\n\n\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n ((BaseActivity) getActivity()).getActivityComponent().inject(this);\n setHasOptionsMenu(true);\n }\n\n\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle\n savedInstanceState) {\n View rootView = inflater.inflate(R.layout.fragment_announcement, container, false);\n ButterKnife.bind(this, rootView);\n mAnnouncementPresenter.attachView(this);\n\n\n final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());\n mRecyclerView.setLayoutManager(layoutManager);\n mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListner(getActivity(), this));\n mRecyclerView.setItemAnimator(new DefaultItemAnimator());\n\n\n mSwipeRefresh.setColorSchemeResources(R.color.colorAccent, R.color.colorAccent, R.color\n .colorPrimary);\n mSwipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {\n @Override\n public void onRefresh() {\n if (ConnectionInfo.isConnectingToInternet(getContext())) {\n if (mSwipeRefresh.isRefreshing()) {\n mPageNumber = 1;\n mAnnouncementPresenter.loadAllAnnouncement(mPageNumber);\n Log.i(LOG_TAG, \"Swipe Refresh\");\n }\n } else {\n Log.i(LOG_TAG, \"NO Internet Connection\");\n showSnackBar(R.string.no_internet_connection);\n if (mSwipeRefresh.isRefreshing()) {\n mSwipeRefresh.setRefreshing(false);\n }\n }\n\n }\n });\n\n showProgressbar(true);\n mAnnouncementPresenter.loadAllAnnouncement(mPageNumber);\n\n mRecyclerView.addOnScrollListener(new EndlessRecyclerOnScrollListener(layoutManager) {\n @Override\n public void onLoadMore(int current_page) {\n\n if (ConnectionInfo.isConnectingToInternet(getContext())) {\n mAnnouncements.getAnnouncement().add(null);\n mAnnouncementAdapter.notifyItemInserted(mAnnouncements.getAnnouncement().size\n ());\n mPageNumber = ++mPageNumber;\n mAnnouncementPresenter.loadAllAnnouncement(mPageNumber);\n Log.i(LOG_TAG, \"Loading more\");\n } else {\n Log.i(LOG_TAG, \"Internet not available. Not loading more posts.\");\n showSnackBar(R.string.no_internet_connection);\n }\n }\n });\n return rootView;\n }\n\n @Override\n public void onDestroyView() {\n super.onDestroyView();\n mAnnouncementPresenter.detachView();\n }\n\n\n @Override\n public void showAllAnnouncement(Announcements announcements) {\n if (mPageNumber == 1) {\n mAnnouncements = announcements;\n mAnnouncementAdapter = new AnnouncementAdapter(mAnnouncements.getAnnouncement());\n mRecyclerView.setAdapter(mAnnouncementAdapter);\n } else {\n removeLoadMoreProgressBar();\n mAnnouncements.getAnnouncement().addAll(announcements.getAnnouncement());\n }\n\n mRecyclerView.setVisibility(View.VISIBLE);\n mAnnouncementAdapter.notifyDataSetChanged();\n if (mSwipeRefresh.isRefreshing()) {\n mSwipeRefresh.setRefreshing(false);\n }\n }\n\n @Override\n public void removeLoadMoreProgressBar() {\n mAnnouncements.getAnnouncement().remove(mAnnouncements.getAnnouncement().size() - 1);\n mAnnouncementAdapter.notifyDataSetChanged();\n }\n\n @Override\n public void showProgressbar(boolean status) {\n if (status) {\n mProgressBar.setVisibility(View.VISIBLE);\n } else {\n mProgressBar.setVisibility(View.GONE);\n }\n }\n\n @Override\n public void showAnnouncementDetail(DetailAnnouncement detailAnnouncement) {\n if (alertDialog != null && alertDialog.isShowing()) {\n alertDialog.dismiss();\n }\n mAnnouncementDetail = detailAnnouncement;\n AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getContext());\n LayoutInflater inflater = getActivity().getLayoutInflater();\n View dialogView = inflater.inflate(R.layout.detail_annoucement_dialog_layout, null);\n dialogBuilder.setView(dialogView);\n TextView title = dialogView.findViewById(R.id.tvDialogTitle);\n TextView date = dialogView.findViewById(R.id.tvDialogDate);\n TextView author = dialogView.findViewById(R.id.tvDialogAuthor);\n WebView text = dialogView.findViewById(R.id.wvDialogText);\n Button buttonOk = dialogView.findViewById(R.id.bDialogOK);\n buttonOk.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n alertDialog.dismiss();\n }\n });\n text.loadDataWithBaseURL(\"\", mAnnouncementDetail.getText(), \"text/html\", \"utf-8\", \"\");\n date.setText(mAnnouncementDetail.getDate());\n title.setText(mAnnouncementDetail.getTitle());\n author.setText(mAnnouncementDetail.getAuthor().getContent());\n alertDialog = dialogBuilder.create();\n alertDialog.show();\n }\n\n @Override\n public void onResume() {\n super.onResume();\n }\n\n @Override\n public void showSnackBar(int message) {\n final Snackbar snackbar = make(getActivity().findViewById(android.R.id.content),\n message, Snackbar.LENGTH_LONG);\n snackbar.setAction(getResources().getString(R.string.ok), new View.OnClickListener() {\n @Override\n public void onClick(View view) {\n snackbar.dismiss();\n }\n });\n\n snackbar.show();\n }\n\n @Override\n public void showWaitProgress(boolean b) {\n if (b) {\n if (dialog != null && dialog.isShowing()) {\n dialog.dismiss();\n }\n dialog = ProgressDialog.show(getContext(), \"Loading\", \"Please wait...\", true);\n } else {\n dialog.dismiss();\n }\n }\n\n @Override\n public void onPrepareOptionsMenu(Menu menu) {\n super.onPrepareOptionsMenu(menu);\n MenuItem item = menu.findItem(R.id.action_search);\n item.setVisible(false);\n }\n}",
"public class RecyclerViewItemCountAssertion implements ViewAssertion {\n private final int expectedCount;\n\n public RecyclerViewItemCountAssertion(int expectedCount) {\n this.expectedCount = expectedCount;\n }\n\n @Override\n public void check(View view, NoMatchingViewException noViewFoundException) {\n if (noViewFoundException != null) {\n throw noViewFoundException;\n }\n\n RecyclerView recyclerView = (RecyclerView) view;\n RecyclerView.Adapter adapter = recyclerView.getAdapter();\n ViewMatchers.assertThat(adapter.getItemCount(), equalTo(5));\n }\n}"
] | import org.apache.taverna.mobile.FakeRemoteDataSource;
import org.apache.taverna.mobile.R;
import org.apache.taverna.mobile.SingleFragmentActivity;
import org.apache.taverna.mobile.TestComponentRule;
import org.apache.taverna.mobile.data.model.Announcements;
import org.apache.taverna.mobile.ui.anouncements.AnnouncementFragment;
import org.apache.taverna.mobile.utils.RecyclerViewItemCountAssertion;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.RuleChain;
import org.junit.rules.TestRule;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import android.content.Intent;
import android.support.test.InstrumentationRegistry;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import java.util.HashMap;
import java.util.Map;
import io.reactivex.Observable;
import static android.os.SystemClock.sleep;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId; | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 org.apache.taverna.mobile.announcement;
@RunWith(AndroidJUnit4.class)
public class AnnouncementActivityTest {
private Announcements announcements;
private Map<String, String> option;
private final TestComponentRule component =
new TestComponentRule(InstrumentationRegistry.getTargetContext());
private final ActivityTestRule<SingleFragmentActivity> mAnnouncementActivityTestRule =
new ActivityTestRule<SingleFragmentActivity>(SingleFragmentActivity.class,
false, false) {
@Override
protected Intent getActivityIntent() {
return new Intent(InstrumentationRegistry.getTargetContext(),
SingleFragmentActivity.class);
}
};
/**
* TestComponentRule needs to go first to make sure the Dagger ApplicationTestComponent is set
* in the Application before any Activity is launched.
*/
@Rule
public final TestRule chain = RuleChain.outerRule(component)
.around(mAnnouncementActivityTestRule);
@Before
public void setUp() {
announcements = FakeRemoteDataSource.getAnnouncements();
option = new HashMap<>();
option.put("order", "reverse");
option.put("page", String.valueOf(1));
}
@Test
public void CheckIfRecyclerViewIsLoaded() {
Mockito.when(component.getMockDataManager().getAllAnnouncement(option))
.thenReturn(Observable.just(announcements));
mAnnouncementActivityTestRule.launchActivity(null);
mAnnouncementActivityTestRule.getActivity().setFragment(new AnnouncementFragment());
| onView(withId(R.id.rv_movies)).check(new RecyclerViewItemCountAssertion(5)); | 5 |
agilie/dribbble-android-sdk | dribbble-sdk-library/src/main/java/com/agilie/dribbblesdk/service/auth/DribbbleAuthHelper.java | [
"public class AuthorizationFlow extends AuthorizationCodeFlow {\n\n static final Logger LOGGER = Logger.getLogger(OAuthConstants.TAG);\n\n /** Credential created listener or {@code null} for none. */\n private final CredentialCreatedListener credentialCreatedListener;\n\n /** Temporary token request URL */\n private String temporaryTokenRequestUrl;\n\n /**\n * Listener for a created credential after a successful token response in\n * {@link AuthorizationFlow#createAndStoreCredential(OAuthCredentialsResponse, String)}\n * ,\n * {@link AuthorizationFlow#createAndStoreCredential(TokenResponse, String)}\n * or\n * {@link AuthorizationFlow#createAndStoreCredential(ImplicitResponseUrl, String)}\n * . .\n */\n public interface CredentialCreatedListener extends\n com.google.api.client.auth.oauth2.AuthorizationCodeFlow.CredentialCreatedListener {\n\n /**\n * Notifies of a created credential after a successful token response in\n * {@link AuthorizationFlow#createAndStoreCredential(ImplicitResponseUrl, String)}\n * .\n * <p>\n * Typical use is to parse additional fields from the credential\n * created, such as an ID token.\n * </p>\n * \n * @param credential created credential\n * @param implicitResponse successful implicit response URL\n */\n void onCredentialCreated(Credential credential, ImplicitResponseUrl implicitResponse)\n throws IOException;\n\n /**\n * Notifies of a created credential after a successful token response in\n * {@link AuthorizationFlow#createAndStoreCredential(OAuthCredentialsResponse, String)}\n * \n * @param credential\n * @param oauth10aResponse\n * @throws IOException\n */\n void onCredentialCreated(Credential credential, OAuthCredentialsResponse oauth10aResponse)\n throws IOException;\n }\n\n AuthorizationFlow(Builder builder) {\n super(builder);\n credentialCreatedListener = builder.getGeneralCredentialCreatedListener();\n temporaryTokenRequestUrl = builder.getTemporaryTokenRequestUrl();\n }\n\n /**\n * Returns the Request Token URL in OAuth 1.0a.\n * \n * @return\n */\n public final String getTemporaryTokenRequestUrl() {\n return temporaryTokenRequestUrl;\n }\n\n /**\n * Loads the OAuth 1.0a credential of the given user ID from the credential\n * store.\n * \n * @param userId user ID or {@code null} if not using a persisted credential\n * store\n * @return OAuth 1.0a credential found in the credential store of the given\n * user ID or {@code null} for none found\n */\n public OAuthHmacCredential load10aCredential(String userId) throws IOException {\n if (getCredentialStore() == null) {\n return null;\n }\n OAuthHmacCredential credential = new10aCredential(userId);\n if (!getCredentialStore().load(userId, credential)) {\n return null;\n }\n return credential;\n }\n\n /**\n * Returns the response of a Request Token request as defined in <a\n * href=\"http://oauth.net/core/1.0a/#auth_step1\">Obtaining an Unauthorized\n * Request Token</a>.\n * \n * @param redirectUri the {@code oauth_callback} as defined in <a\n * href=\"http://oauth.net/core/1.0a/#rfc.section.6.1.1\">Consumer\n * Obtains a Request Token</a>\n * @return\n * @throws IOException\n */\n public OAuthCredentialsResponse new10aTemporaryTokenRequest(String redirectUri)\n throws IOException {\n OAuthGetTemporaryToken temporaryToken =\n new OAuthGetTemporaryToken(getTemporaryTokenRequestUrl());\n OAuthHmacSigner signer = new OAuthHmacSigner();\n ClientParametersAuthentication clientAuthentication = (ClientParametersAuthentication) getClientAuthentication();\n signer.clientSharedSecret = clientAuthentication.getClientSecret();\n temporaryToken.signer = signer;\n temporaryToken.consumerKey = clientAuthentication.getClientId();\n temporaryToken.callback = redirectUri;\n temporaryToken.transport = getTransport();\n return temporaryToken.execute();\n }\n\n /**\n * Returns a new instance of a temporary token authorization request URL as\n * defined in <a\n * href=\"http://oauth.net/core/1.0a/#rfc.section.6.2.1\">Consumer Directs the\n * User to the Service Provider</a>.\n * \n * @param temporaryToken\n * @return\n */\n public OAuthAuthorizeTemporaryTokenUrl new10aAuthorizationUrl(String temporaryToken) {\n OAuthAuthorizeTemporaryTokenUrl authorizationUrl =\n new OAuthAuthorizeTemporaryTokenUrl(getAuthorizationServerEncodedUrl());\n authorizationUrl.temporaryToken = temporaryToken;\n return authorizationUrl;\n }\n\n /**\n * Returns a new instance of a token request based on the given verifier\n * code. This step is defined in <a\n * href=\"http://oauth.net/core/1.0a/#auth_step3\">Obtaining an Access\n * Token</a>.\n * \n * @param temporaryCredentials\n * @param verifierCode\n * @return\n */\n public OAuthGetAccessToken new10aTokenRequest(OAuthCredentialsResponse temporaryCredentials,\n String verifierCode) {\n OAuthGetAccessToken request = new OAuthGetAccessToken(getTokenServerEncodedUrl());\n request.temporaryToken = temporaryCredentials.token;\n request.transport = getTransport();\n\n OAuthHmacSigner signer = new OAuthHmacSigner();\n ClientParametersAuthentication clientAuthentication = (ClientParametersAuthentication) getClientAuthentication();\n signer.clientSharedSecret = clientAuthentication.getClientSecret();\n signer.tokenSharedSecret = temporaryCredentials.tokenSecret;\n\n request.signer = signer;\n request.consumerKey = clientAuthentication.getClientId();\n request.verifier = verifierCode;\n return request;\n }\n\n @Override\n public AuthorizationCodeTokenRequest newTokenRequest(String authorizationCode) {\n return new LenientAuthorizationCodeTokenRequest(getTransport(), getJsonFactory(),\n new GenericUrl(getTokenServerEncodedUrl()), authorizationCode)\n .setClientAuthentication(getClientAuthentication())\n .setRequestInitializer(getRequestInitializer())\n .setScopes(getScopes())\n .setRequestInitializer(\n new HttpRequestInitializer() {\n @Override\n public void initialize(HttpRequest request) throws IOException {\n request.getHeaders().setAccept(\"application/json\");\n }\n });\n }\n\n /**\n * Returns a new instance of an explicit authorization code request URL.\n * <p>\n * This is a builder for an authorization web page to allow the end user to\n * authorize the application to access their protected resources and that\n * returns an authorization code. It uses the\n * {@link #getAuthorizationServerEncodedUrl()}, {@link #getClientId()}, and\n * {@link #getScopes()}. Sample usage:\n * </p>\n * \n * <pre>\n * private AuthorizationFlow flow;\n * \n * public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {\n * String url = flow.newExplicitAuthorizationUrl().setState("xyz")\n * .setRedirectUri("https://client.example.com/rd").build();\n * response.sendRedirect(url);\n * }\n * </pre>\n */\n public AuthorizationCodeRequestUrl newExplicitAuthorizationUrl() {\n return newAuthorizationUrl();\n }\n\n /**\n * Returns a new instance of an implicit authorization request URL.\n * <p>\n * This is a builder for an authorization web page to allow the end user to\n * authorize the application to access their protected resources and that\n * returns an access token. It uses the\n * {@link #getAuthorizationServerEncodedUrl()}, {@link #getClientId()}, and\n * {@link #getScopes()}. Sample usage:\n * </p>\n * \n * <pre>\n * private AuthorizationFlow flow;\n * \n * public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {\n * String url = flow.newImplicitAuthorizationUrl().setState("xyz")\n * .setRedirectUri("https://client.example.com/rd").build();\n * response.sendRedirect(url);\n * }\n * </pre>\n */\n public BrowserClientRequestUrl newImplicitAuthorizationUrl() {\n return new BrowserClientRequestUrl(getAuthorizationServerEncodedUrl(), getClientId())\n .setScopes(getScopes());\n }\n\n /**\n * Creates a new credential for the given user ID based on the given token\n * response and store in the credential store.\n * \n * @param response OAuth 1.0a authorization token response\n * @param userId user ID or {@code null} if not using a persisted credential\n * store\n * @return newly created credential\n * @throws IOException\n */\n public OAuthHmacCredential createAndStoreCredential(OAuthCredentialsResponse response,\n String userId) throws IOException {\n OAuthHmacCredential credential = new10aCredential(userId)\n .setAccessToken(response.token)\n .setTokenSharedSecret(response.tokenSecret);\n CredentialStore credentialStore = getCredentialStore();\n if (credentialStore != null) {\n credentialStore.store(userId, credential);\n }\n if (credentialCreatedListener != null) {\n credentialCreatedListener.onCredentialCreated(credential, response);\n }\n return credential;\n }\n\n /**\n * Creates a new credential for the given user ID based on the given token\n * response and store in the credential store.\n * \n * @param response implicit authorization token response\n * @param userId user ID or {@code null} if not using a persisted credential\n * store\n * @return newly created credential\n * @throws IOException\n */\n public Credential createAndStoreCredential(ImplicitResponseUrl implicitResponse, String userId)\n throws IOException {\n Credential credential = newCredential(userId)\n .setAccessToken(implicitResponse.getAccessToken())\n .setExpirationTimeMilliseconds(implicitResponse.getExpiresInSeconds());\n CredentialStore credentialStore = getCredentialStore();\n if (credentialStore != null) {\n credentialStore.store(userId, credential);\n }\n if (credentialCreatedListener != null) {\n credentialCreatedListener.onCredentialCreated(credential, implicitResponse);\n }\n return credential;\n }\n\n /**\n * Returns a new OAuth 1.0a credential instance based on the given user ID.\n * \n * @param userId user ID or {@code null} if not using a persisted credential\n * store\n */\n private OAuthHmacCredential new10aCredential(String userId) {\n ClientParametersAuthentication clientAuthentication = (ClientParametersAuthentication) getClientAuthentication();\n OAuthHmacCredential.Builder builder =\n new OAuthHmacCredential.Builder(getMethod(), clientAuthentication.getClientId(),\n clientAuthentication.getClientSecret())\n .setTransport(getTransport())\n .setJsonFactory(getJsonFactory())\n .setTokenServerEncodedUrl(getTokenServerEncodedUrl())\n .setClientAuthentication(getClientAuthentication())\n .setRequestInitializer(getRequestInitializer())\n .setClock(getClock());\n if (getCredentialStore() != null) {\n builder.addRefreshListener(\n new CredentialStoreRefreshListener(userId, getCredentialStore()));\n }\n\n builder.getRefreshListeners().addAll(getRefreshListeners());\n\n return builder.build();\n }\n\n /**\n * Returns a new OAuth 2.0 credential instance based on the given user ID.\n * \n * @param userId user ID or {@code null} if not using a persisted credential\n * store\n */\n private Credential newCredential(String userId) {\n Credential.Builder builder = new Credential.Builder(getMethod())\n .setTransport(getTransport())\n .setJsonFactory(getJsonFactory())\n .setTokenServerEncodedUrl(getTokenServerEncodedUrl())\n .setClientAuthentication(getClientAuthentication())\n .setRequestInitializer(getRequestInitializer())\n .setClock(getClock());\n if (getCredentialStore() != null) {\n builder.addRefreshListener(\n new CredentialStoreRefreshListener(userId, getCredentialStore()));\n }\n\n builder.getRefreshListeners().addAll(getRefreshListeners());\n\n return builder.build();\n }\n\n /**\n * Authorization flow builder.\n * <p>\n * Implementation is not thread-safe.\n * </p>\n */\n public static class Builder extends\n com.google.api.client.auth.oauth2.AuthorizationCodeFlow.Builder {\n\n /** Credential created listener or {@code null} for none. */\n CredentialCreatedListener credentialCreatedListener;\n\n /** Temporary token request URL */\n String temporaryTokenRequestUrl;\n\n /**\n * @param method method of presenting the access token to the resource\n * server (for example\n * {@link BearerToken#authorizationHeaderAccessMethod})\n * @param transport HTTP transport\n * @param jsonFactory JSON factory\n * @param tokenServerUrl token server URL\n * @param clientAuthentication client authentication or {@code null} for\n * none (see\n * {@link TokenRequest#setClientAuthentication(HttpExecuteInterceptor)}\n * )\n * @param clientId client identifier\n * @param authorizationServerEncodedUrl authorization server encoded URL\n */\n public Builder(AccessMethod method,\n HttpTransport transport,\n JsonFactory jsonFactory,\n GenericUrl tokenServerUrl,\n HttpExecuteInterceptor clientAuthentication,\n String clientId,\n String authorizationServerEncodedUrl) {\n super(method,\n transport,\n jsonFactory,\n tokenServerUrl,\n clientAuthentication,\n clientId,\n authorizationServerEncodedUrl);\n }\n\n /**\n * Returns a new instance of an authorization flow based on this\n * builder.\n */\n public AuthorizationFlow build() {\n return new AuthorizationFlow(this);\n }\n\n /**\n * Sets the temporary token request URL.\n * \n * @param temporaryTokenRequestUrl\n * @return\n */\n public Builder setTemporaryTokenRequestUrl(String temporaryTokenRequestUrl) {\n this.temporaryTokenRequestUrl = temporaryTokenRequestUrl;\n return this;\n }\n\n /**\n * Returns the temporary token request URL.\n * \n * @return\n */\n public String getTemporaryTokenRequestUrl() {\n return temporaryTokenRequestUrl;\n }\n\n @Override\n public Builder setMethod(AccessMethod method) {\n return (Builder) super.setMethod(method);\n }\n\n @Override\n public Builder setTransport(HttpTransport transport) {\n return (Builder) super.setTransport(transport);\n }\n\n @Override\n public Builder setJsonFactory(JsonFactory jsonFactory) {\n return (Builder) super.setJsonFactory(jsonFactory);\n }\n\n @Override\n public Builder setTokenServerUrl(GenericUrl tokenServerUrl) {\n return (Builder) super.setTokenServerUrl(tokenServerUrl);\n }\n\n @Override\n public Builder setClientAuthentication(HttpExecuteInterceptor clientAuthentication) {\n return (Builder) super.setClientAuthentication(clientAuthentication);\n }\n\n @Override\n public Builder setClientId(String clientId) {\n return (Builder) super.setClientId(clientId);\n }\n\n @Override\n public Builder setAuthorizationServerEncodedUrl(String authorizationServerEncodedUrl) {\n return (Builder) super.setAuthorizationServerEncodedUrl(authorizationServerEncodedUrl);\n }\n\n @Override\n public Builder setClock(Clock clock) {\n return (Builder) super.setClock(clock);\n }\n\n @Beta\n @Override\n public Builder setCredentialStore(CredentialStore credentialStore) {\n return (Builder) super.setCredentialStore(credentialStore);\n }\n\n @Override\n public Builder setRequestInitializer(HttpRequestInitializer requestInitializer) {\n return (Builder) super.setRequestInitializer(requestInitializer);\n }\n\n @Beta\n @Deprecated\n @Override\n public Builder setScopes(Iterable<String> scopes) {\n return (Builder) super.setScopes(scopes);\n }\n\n @Beta\n @Deprecated\n @Override\n public Builder setScopes(String... scopes) {\n return (Builder) super.setScopes(scopes);\n }\n\n @Override\n public Builder setScopes(Collection<String> scopes) {\n return (Builder) super.setScopes(scopes);\n }\n\n /**\n * Sets the credential created listener or {@code null} for none. *\n * <p>\n * Overriding is only supported for the purpose of calling the super\n * implementation and changing the return type, but nothing else.\n * </p>\n */\n public Builder setCredentialCreatedListener(\n CredentialCreatedListener credentialCreatedListener) {\n this.credentialCreatedListener = credentialCreatedListener;\n return (Builder) super.setCredentialCreatedListener(credentialCreatedListener);\n }\n\n /**\n * Returns the credential created listener or {@code null} for none.\n */\n public final CredentialCreatedListener getGeneralCredentialCreatedListener() {\n return credentialCreatedListener;\n }\n\n @Override\n public Builder addRefreshListener(CredentialRefreshListener refreshListener) {\n return (Builder) super.addRefreshListener(refreshListener);\n }\n\n @Override\n public Builder setRefreshListeners(Collection<CredentialRefreshListener> refreshListeners) {\n return (Builder) super.setRefreshListeners(refreshListeners);\n }\n\n }\n\n}",
"public interface AuthorizationUIController {\n\n /**\n * Error indicating that the user has cancelled the authorization process,\n * most likely due to cancellation of the authorization dialog.\n */\n String ERROR_USER_CANCELLED = \"user_cancelled\";\n\n /**\n * The request is missing a required parameter, includes an invalid\n * parameter value, includes a parameter more than once, or is otherwise\n * malformed.\n */\n String ERROR_INVALID_REQUEST = \"invalid_request\";\n\n /**\n * The client is not authorized to request an authorization code using this\n * method.\n */\n String ERROR_UNAUTHORIZED_CLIENT = \"unauthorized_client\";\n\n /**\n * The resource owner or authorization server denied the request.\n */\n String ERROR_ACCESS_DENIED = \"access_denied\";\n\n /**\n * The authorization server does not support obtaining an authorization code\n * using this method.\n */\n String ERROR_UNSUPPORTED_RESPONSE_TYPE = \"unsupported_response_type\";\n\n /** The requested scope is invalid, unknown, or malformed. */\n String ERROR_INVALID_SCOPE = \"invalid_scope\";\n\n /**\n * The authorization server encountered an unexpected condition that\n * prevented it from fulfilling the request. (This error code is needed\n * because a 500 Internal Server Error HTTP status code cannot be returned\n * to the client via an HTTP redirect.)\n */\n String ERROR_SERVER_ERROR = \"server_error\";\n\n /**\n * The authorization server is currently unable to handle the request due to\n * a temporary overloading or maintenance of the server. (This error code is\n * needed because a 503 Service Unavailable HTTP status code cannot be\n * returned to the client via an HTTP redirect.)\n */\n String ERROR_TEMPORARILY_UNAVAILABLE = \"temporarily_unavailable\";\n\n /**\n * Handles user authorization by redirecting to the OAuth 1.0a authorization\n * server as defined in <a\n * href=\"http://oauth.net/core/1.0a/#auth_step2\">Obtaining User\n * Authorization</a>.\n * \n * @param authorizationRequestUrl\n */\n void requestAuthorization(OAuthAuthorizeTemporaryTokenUrl authorizationRequestUrl);\n\n /**\n * Handles user authorization by redirecting to the OAuth 2.0 authorization\n * server as defined in <a\n * href=\"http://tools.ietf.org/html/rfc6749#section-4.1.1\">Authorization\n * Request</a>.\n * \n * @param authorizationRequestUrl\n */\n void requestAuthorization(AuthorizationCodeRequestUrl authorizationRequestUrl);\n\n /**\n * Handles user authorization by redirecting to the OAuth 2.0 authorization\n * server as defined in <a\n * href=\"http://tools.ietf.org/html/rfc6749#section-4.2.1\">Authorization\n * Request</a>.\n * \n * @param authorizationRequestUrl\n */\n void requestAuthorization(BrowserClientRequestUrl authorizationRequestUrl);\n\n /** Returns the redirect URI. */\n String getRedirectUri() throws IOException;\n\n /** Waits for OAuth 1.0a verifier code. */\n String waitForVerifierCode() throws IOException;\n\n /** Waits for OAuth 2.0 explicit authorization code. */\n String waitForExplicitCode() throws IOException;\n\n /** Waits for OAuth 2.0 implicit access token response. */\n ImplicitResponseUrl waitForImplicitResponseUrl() throws IOException;\n\n /** Releases any resources and stops any processes started. */\n void stop() throws IOException;\n\n}",
"public abstract class DialogFragmentController implements AuthorizationDialogController {\n\n static final Logger LOGGER = Logger.getLogger(OAuthConstants.TAG);\n\n private static final String FRAGMENT_TAG = \"oauth_dialog\";\n\n /** A boolean to indicate if the dialog fragment needs to be full screen **/\n public final boolean fullScreen;\n\n /** A boolean to indicate if the dialog fragment needs to be horizontal **/\n public final boolean horizontalProgress;\n\n public final boolean hideFullScreenTitle;\n\n private final FragmentManagerCompat fragmentManager;\n\n /** {@link Handler} for running UI in the main thread. */\n private final Handler uiHandler;\n\n /**\n * Verification code (for explicit authorization) or access token (for\n * implicit authorization) or {@code null} for none.\n */\n String codeOrToken;\n\n /** Error code or {@code null} for none. */\n String error;\n\n /** Implicit response URL. */\n ImplicitResponseUrl implicitResponseUrl;\n\n /** Lock on the code and error. */\n final Lock lock = new ReentrantLock();\n\n /** Condition for receiving an authorization response. */\n final Condition gotAuthorizationResponse = lock.newCondition();\n\n /**\n * @param fragmentManager\n */\n public DialogFragmentController(android.support.v4.app.FragmentManager fragmentManager) {\n this(fragmentManager, false);\n }\n\n /**\n * @param fragmentManager\n */\n public DialogFragmentController(android.app.FragmentManager fragmentManager) {\n this(fragmentManager, false);\n }\n\n /**\n *\n * @param fragmentManager\n * @param fullScreen\n */\n public DialogFragmentController(android.support.v4.app.FragmentManager fragmentManager, boolean fullScreen) {\n this(fragmentManager, fullScreen, false);\n }\n\n /**\n *\n * @param fragmentManager\n * @param fullScreen\n */\n public DialogFragmentController(android.app.FragmentManager fragmentManager, boolean fullScreen) {\n this(fragmentManager, fullScreen, false);\n }\n\n /**\n *\n * @param fragmentManager\n * @param fullScreen\n * @param horizontalProgress\n */\n public DialogFragmentController(android.support.v4.app.FragmentManager fragmentManager, boolean fullScreen,\n boolean horizontalProgress) {\n this(fragmentManager, fullScreen, horizontalProgress, false);\n }\n\n /**\n *\n * @param fragmentManager\n * @param fullScreen\n * @param horizontalProgress\n */\n public DialogFragmentController(android.app.FragmentManager fragmentManager, boolean fullScreen,\n boolean horizontalProgress) {\n this(fragmentManager, fullScreen, horizontalProgress, false);\n }\n\n /**\n *\n * @param fragmentManager\n * @param fullScreen\n * @param horizontalProgress\n * @param hideFullScreenTitle if you set this flag to true, {@param horizontalProgress} will be ignored\n */\n public DialogFragmentController(android.support.v4.app.FragmentManager fragmentManager, boolean fullScreen,\n boolean horizontalProgress, boolean hideFullScreenTitle) {\n super();\n this.uiHandler = new Handler(Looper.getMainLooper());\n this.fragmentManager =\n new FragmentManagerCompat(Preconditions.checkNotNull(fragmentManager));\n this.fullScreen = fullScreen;\n this.horizontalProgress = horizontalProgress;\n this.hideFullScreenTitle = hideFullScreenTitle;\n }\n\n /**\n *\n * @param fragmentManager\n * @param fullScreen\n * @param horizontalProgress\n * @param hideFullScreenTitle if you set this flag to true, {@param horizontalProgress} will be ignored\n */\n public DialogFragmentController(android.app.FragmentManager fragmentManager, boolean fullScreen,\n boolean horizontalProgress, boolean hideFullScreenTitle) {\n super();\n this.uiHandler = new Handler(Looper.getMainLooper());\n this.fragmentManager =\n new FragmentManagerCompat(Preconditions.checkNotNull(fragmentManager));\n this.fullScreen = fullScreen;\n this.horizontalProgress = horizontalProgress;\n this.hideFullScreenTitle = hideFullScreenTitle;\n }\n\n Object getFragmentManager() {\n return this.fragmentManager.getFragmentManager();\n }\n\n /**\n * Executes the {@link Runnable} on the main thread.\n *\n * @param runnable\n */\n private void runOnMainThread(Runnable runnable) {\n uiHandler.post(runnable);\n }\n\n private void dismissDialog() {\n runOnMainThread(new Runnable() {\n public void run() {\n DialogFragmentCompat frag = fragmentManager\n .findFragmentByTag(DialogFragmentCompat.class, FRAGMENT_TAG);\n if (frag != null) {\n frag.dismiss();\n }\n }\n });\n }\n\n @Override\n public void set(String codeOrToken, String error, ImplicitResponseUrl implicitResponseUrl,\n boolean signal) {\n lock.lock();\n try {\n this.error = error;\n this.codeOrToken = codeOrToken;\n this.implicitResponseUrl = implicitResponseUrl;\n if (signal) {\n gotAuthorizationResponse.signal();\n }\n } finally {\n lock.unlock();\n }\n }\n\n @Override\n public void requestAuthorization(OAuthAuthorizeTemporaryTokenUrl authorizationRequestUrl) {\n internalRequestAuthorization(authorizationRequestUrl);\n }\n\n @Override\n public void requestAuthorization(AuthorizationCodeRequestUrl authorizationRequestUrl) {\n internalRequestAuthorization(authorizationRequestUrl);\n }\n\n @Override\n public void requestAuthorization(BrowserClientRequestUrl authorizationRequestUrl) {\n internalRequestAuthorization(authorizationRequestUrl);\n }\n\n private void internalRequestAuthorization(final GenericUrl authorizationRequestUrl) {\n runOnMainThread(new Runnable() {\n @Override\n public void run() {\n if(fragmentManager.isDestroyed()) {\n return;\n }\n FragmentTransactionCompat ft = fragmentManager.beginTransaction();\n FragmentCompat prevDialog =\n fragmentManager.findFragmentByTag(FragmentCompat.class, FRAGMENT_TAG);\n if (prevDialog != null) {\n ft.remove(prevDialog);\n }\n DialogFragmentCompat frag =\n OAuthDialogFragment.newInstance(\n authorizationRequestUrl,\n DialogFragmentController.this);\n frag.show(ft, FRAGMENT_TAG);\n }\n });\n }\n\n @Override\n public String waitForVerifierCode() throws IOException {\n return waitForExplicitCode();\n }\n\n @Override\n public String waitForExplicitCode() throws IOException {\n lock.lock();\n try {\n while (codeOrToken == null && error == null) {\n gotAuthorizationResponse.awaitUninterruptibly();\n }\n dismissDialog();\n if (error != null) {\n if (TextUtils.equals(ERROR_USER_CANCELLED, error)) {\n throw new CancellationException(\"User authorization failed (\" + error + \")\");\n } else {\n throw new IOException(\"User authorization failed (\" + error + \")\");\n }\n }\n return codeOrToken;\n } finally {\n lock.unlock();\n }\n }\n\n @Override\n public ImplicitResponseUrl waitForImplicitResponseUrl() throws IOException {\n lock.lock();\n try {\n while (codeOrToken == null && error == null) {\n gotAuthorizationResponse.awaitUninterruptibly();\n }\n dismissDialog();\n if (error != null) {\n if (TextUtils.equals(ERROR_USER_CANCELLED, error)) {\n throw new CancellationException(\"User authorization failed (\" + error + \")\");\n } else {\n throw new IOException(\"User authorization failed (\" + error + \")\");\n }\n }\n return implicitResponseUrl;\n } finally {\n lock.unlock();\n }\n }\n\n @Override\n public void stop() throws IOException {\n set(null, null, null, true);\n dismissDialog();\n }\n\n @Override\n public void onPrepareDialog(Dialog dialog) {\n // do nothing\n }\n\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {\n // use default implementation in DialogFragment\n return null;\n }\n\n @Override\n public boolean setProgressShown(String url, View view, int newProgress) {\n // use default implementation in DialogFragment\n return false;\n }\n\n}",
"public class OAuthManager {\n\n static final Logger LOGGER = Logger.getLogger(OAuthConstants.TAG);\n\n private final AuthorizationFlow mFlow;\n private final AuthorizationUIController mUIController;\n\n /** Handler that runs in the UI thread. */\n private final Handler mMainHandler = new Handler(Looper.getMainLooper());\n\n /** ExecutorService that runs tasks in background threads. */\n private final ExecutorService mExecutor;\n\n public OAuthManager(AuthorizationFlow flow, AuthorizationUIController uiController) {\n this(flow, uiController, Executors.newSingleThreadExecutor());\n }\n\n public OAuthManager(AuthorizationFlow flow, AuthorizationUIController uiController,\n ExecutorService executor) {\n super();\n this.mFlow = flow;\n this.mUIController = uiController;\n this.mExecutor = Preconditions.checkNotNull(executor);\n }\n\n public OAuthFuture<Boolean> deleteCredential(final String userId,\n final OAuthCallback<Boolean> callback, Handler handler) {\n Preconditions.checkNotNull(userId);\n\n final Future2Task<Boolean> task = new Future2Task<Boolean>(handler, callback) {\n\n @Override\n public void doWork() throws Exception {\n LOGGER.info(\"deleteCredential\");\n CredentialStore store = mFlow.getCredentialStore();\n if (store == null) {\n set(false);\n return;\n }\n\n store.delete(userId, null);\n set(true);\n }\n\n };\n\n // run the task in a background thread\n submitTaskToExecutor(task);\n\n return task;\n }\n\n /**\n * Authorizes the Android application to access user's protected data using\n * the authorization flow in OAuth 1.0a.\n * \n * @param userId user ID or {@code null} if not using a persisted credential\n * store\n * @param callback Callback to invoke when the request completes,\n * {@code null} for no callback\n * @param handler {@link Handler} identifying the callback thread,\n * {@code null} for the main thread\n * @return An {@link OAuthFuture} which resolves to a {@link Credential}\n */\n public OAuthFuture<Credential> authorize10a(final String userId,\n final OAuthCallback<Credential> callback, Handler handler) {\n Preconditions.checkNotNull(userId);\n\n final Future2Task<Credential> task = new Future2Task<Credential>(handler, callback) {\n\n @Override\n public void doWork() throws Exception {\n try {\n LOGGER.info(\"authorize10a\");\n OAuthHmacCredential credential = mFlow.load10aCredential(userId);\n if (credential != null && credential.getAccessToken() != null\n && (credential.getRefreshToken() != null\n || credential.getExpiresInSeconds() == null\n || credential.getExpiresInSeconds() > 60)) {\n set(credential);\n return;\n }\n\n String redirectUri = mUIController.getRedirectUri();\n\n OAuthCredentialsResponse tempCredentials =\n mFlow.new10aTemporaryTokenRequest(redirectUri);\n OAuthAuthorizeTemporaryTokenUrl authorizationUrl =\n mFlow.new10aAuthorizationUrl(tempCredentials.token);\n mUIController.requestAuthorization(authorizationUrl);\n\n String code = mUIController.waitForVerifierCode();\n OAuthCredentialsResponse response =\n mFlow.new10aTokenRequest(tempCredentials, code).execute();\n credential = mFlow.createAndStoreCredential(response, userId);\n set(credential);\n } finally {\n mUIController.stop();\n }\n }\n\n };\n\n // run the task in a background thread\n submitTaskToExecutor(task);\n\n return task;\n }\n\n /**\n * Authorizes the Android application to access user's protected data using\n * the Explicit Authorization Code flow in OAuth 2.0.\n * \n * @param userId user ID or {@code null} if not using a persisted credential\n * store\n * @param callback Callback to invoke when the request completes,\n * {@code null} for no callback\n * @param handler {@link Handler} identifying the callback thread,\n * {@code null} for the main thread\n * @return An {@link OAuthFuture} which resolves to a {@link Credential}\n */\n public OAuthFuture<Credential> authorizeExplicitly(final String userId,\n final OAuthCallback<Credential> callback, Handler handler) {\n Preconditions.checkNotNull(userId);\n\n final Future2Task<Credential> task = new Future2Task<Credential>(handler, callback) {\n\n @Override\n public void doWork() throws Exception {\n try {\n Credential credential = mFlow.loadCredential(userId);\n LOGGER.info(\"authorizeExplicitly\");\n if (credential != null && credential.getAccessToken() != null\n && (credential.getRefreshToken() != null ||\n credential.getExpiresInSeconds() == null ||\n credential.getExpiresInSeconds() > 60)) {\n set(credential);\n return;\n }\n\n String redirectUri = mUIController.getRedirectUri();\n\n AuthorizationCodeRequestUrl authorizationUrl = mFlow\n .newExplicitAuthorizationUrl()\n .setRedirectUri(redirectUri);\n mUIController.requestAuthorization(authorizationUrl);\n\n String code = mUIController.waitForExplicitCode();\n TokenResponse response = mFlow.newTokenRequest(code)\n .setRedirectUri(redirectUri).execute();\n credential = mFlow.createAndStoreCredential(response, userId);\n set(credential);\n } finally {\n mUIController.stop();\n }\n }\n\n };\n\n // run the task in a background thread\n submitTaskToExecutor(task);\n\n return task;\n }\n\n /**\n * Authorizes the Android application to access user's protected data using\n * the Implicit Authorization flow in OAuth 2.0.\n * \n * @param userId user ID or {@code null} if not using a persisted credential\n * store\n * @param callback Callback to invoke when the request completes,\n * {@code null} for no callback\n * @param handler {@link Handler} identifying the callback thread,\n * {@code null} for the main thread\n * @return An {@link OAuthFuture} which resolves to a {@link Credential}\n */\n public OAuthFuture<Credential> authorizeImplicitly(final String userId,\n final OAuthCallback<Credential> callback, Handler handler) {\n Preconditions.checkNotNull(userId);\n\n final Future2Task<Credential> task = new Future2Task<Credential>(handler, callback) {\n\n @Override\n public void doWork() throws TokenResponseException, Exception {\n try {\n LOGGER.info(\"authorizeImplicitly\");\n Credential credential = mFlow.loadCredential(userId);\n if (credential != null && credential.getAccessToken() != null\n && (credential.getRefreshToken() != null ||\n credential.getExpiresInSeconds() == null ||\n credential.getExpiresInSeconds() > 60)) {\n set(credential);\n return;\n }\n\n String redirectUri = mUIController.getRedirectUri();\n\n BrowserClientRequestUrl authorizationUrl = mFlow.newImplicitAuthorizationUrl()\n .setRedirectUri(redirectUri);\n mUIController.requestAuthorization(authorizationUrl);\n\n ImplicitResponseUrl implicitResponse = mUIController\n .waitForImplicitResponseUrl();\n credential = mFlow.createAndStoreCredential(implicitResponse, userId);\n set(credential);\n } finally {\n mUIController.stop();\n }\n }\n\n };\n\n // run the task in a background thread\n submitTaskToExecutor(task);\n\n return task;\n }\n\n /**\n * An {@code OAuthCallback} represents the callback handler to be invoked\n * when an asynchronous {@link OAuthManager} call is completed.\n * \n * @author David Wu\n * @param <T>\n */\n public static interface OAuthCallback<T> {\n /**\n * Callback method that is invoked when an asynchronous\n * {@link OAuthManager} call is completed.\n * \n * @param future An {@link OAuthFuture} that represents the result of an\n * asynchronous {@link OAuthManager} call.\n */\n void run(OAuthFuture<T> future);\n }\n\n /**\n * An {@code OAuthFuture} represents the result of an asynchronous\n * {@link OAuthManager} call. Methods are provided to check if the\n * computation is complete, to wait for its completion, and to retrieve the\n * result of the computation. The result can only be retrieved using method\n * {@link #getResult()} or {@link #getResult(long, TimeUnit)} when the\n * computation has completed, blocking if necessary until it is ready.\n * Cancellation is performed by the {@link #cancel(boolean)} method.\n * Additional methods are provided to determine if the task completed\n * normally or was cancelled. Once a computation has completed, the\n * computation cannot be cancelled.\n * \n * @author David Wu\n * @param <V>\n */\n public static interface OAuthFuture<V> {\n\n /**\n * Attempts to cancel execution of this task. This attempt will fail if\n * the task has already completed, has already been cancelled, or could\n * not be cancelled for some other reason. If successful, and this task\n * has not started when {@link #cancel(boolean)} is called, this task\n * should never run. If the task has already started, then the\n * {@code mayInterruptIfRunning} parameter determines whether the thread\n * executing this task should be interrupted in an attempt to stop the\n * task.\n * <p>\n * After this method returns, subsequent calls to {@link #isDone()} will\n * always return {@code true}. Subsequent calls to\n * {@link #isCancelled()} will always return {@code true} if this method\n * returns {@code true}.\n * </p>\n * \n * @param mayInterruptIfRunning {@code true} if the thread executing\n * this task should be interrupted; otherwise, in-progress\n * tasks are allowed to complete\n * @return {@code false} if the task could not be cancelled, typically\n * because it has already completed normally; {@code true}\n * otherwise\n */\n boolean cancel(boolean mayInterruptIfRunning);\n\n /**\n * Returns {@code true} if this task was cancelled before it completed\n * normally.\n * \n * @return {@code true} if this task was cancelled before it completed\n */\n boolean isCancelled();\n\n /**\n * Returns {@code true} if this task completed.\n * <p>\n * Completion may be due to normal termination, an exception, or\n * cancellation -- in all of these cases, this method will return\n * {@code true}.\n * </p>\n * \n * @return {@code true} if this task completed\n */\n boolean isDone();\n\n /**\n * Accessor for the future result the {@link OAuthFuture} represents.\n * This call will block until the result is available. In order to check\n * if the result is available without blocking, one may call\n * {@link #isDone()} and {@link #isCancelled()}. If the request that\n * generated this result fails or is canceled then an exception will be\n * thrown rather than the call returning normally.\n * \n * @return the actual result\n * @throws CancellationException if the request was canceled for any\n * reason\n * @throws IOException if an IOException occurred while communicating\n * with the server.\n */\n V getResult() throws CancellationException, IOException;\n\n /**\n * Accessor for the future result the {@link OAuthFuture} represents.\n * This call will block until the result is available. In order to check\n * if the result is available without blocking, one may call\n * {@link #isDone()} and {@link #isCancelled()}. If the request that\n * generated this result fails or is canceled then an exception will be\n * thrown rather than the call returning normally. If a timeout is\n * specified then the request will automatically be canceled if it does\n * not complete in that amount of time.\n * \n * @param timeout the maximum time to wait\n * @param unit the time unit of the timeout argument. This must not be\n * null.\n * @return the actual result\n * @throws CancellationException if the request was canceled for any\n * reason\n * @throws IOException if an IOException occurred while communicating\n * with the server.\n */\n V getResult(long timeout, TimeUnit unit) throws CancellationException, IOException;\n }\n\n protected final void submitTaskToExecutor(final Future2Task<?> task) {\n // run the task in a background thread\n mExecutor.submit(new Runnable() {\n public void run() {\n task.start();\n }\n });\n }\n\n private abstract class BaseFutureTask<T> extends FutureTask<T> {\n final Handler mHandler;\n\n public BaseFutureTask(Handler handler) {\n super(new Callable<T>() {\n public T call() throws Exception {\n throw new IllegalStateException(\"this should never be called\");\n }\n });\n this.mHandler = handler;\n }\n\n public abstract void doWork() throws Exception;\n\n protected void startTask() {\n try {\n doWork();\n } catch (Exception e) {\n setException(e);\n }\n }\n\n protected void postRunnableToHandler(Runnable runnable) {\n Handler handler = (mHandler == null) ? mMainHandler : mHandler;\n handler.post(runnable);\n }\n }\n\n public abstract class Future2Task<T> extends BaseFutureTask<T> implements\n OAuthFuture<T> {\n\n final OAuthCallback<T> mCallback;\n\n public Future2Task(Handler handler, OAuthCallback<T> callback) {\n super(handler);\n mCallback = callback;\n }\n\n public Future2Task<T> start() {\n startTask();\n return this;\n }\n\n @Override\n protected void done() {\n if (mCallback != null) {\n postRunnableToHandler(new Runnable() {\n public void run() {\n mCallback.run(Future2Task.this);\n }\n });\n }\n }\n\n @Override\n public T getResult() throws CancellationException, IOException {\n return internalGetResult(null, null);\n }\n\n @Override\n public T getResult(long timeout, TimeUnit unit) throws CancellationException,\n IOException {\n return internalGetResult(timeout, unit);\n }\n\n private T internalGetResult(Long timeout, TimeUnit unit) throws CancellationException,\n IOException {\n if (!isDone()) {\n ensureNotOnMainThread();\n }\n try {\n if (timeout == null) {\n return get();\n } else {\n return get(timeout, unit);\n }\n } catch (CancellationException e) {\n throw new CancellationException(e.getMessage());\n } catch (TimeoutException e) {\n // fall through and cancel\n } catch (InterruptedException e) {\n // fall through and cancel\n } catch (ExecutionException e) {\n final Throwable cause = e.getCause();\n if (cause instanceof LenientTokenResponseException) {\n throw (LenientTokenResponseException) cause;\n } else if (cause instanceof TokenResponseException) {\n throw (TokenResponseException) cause;\n } else if (cause instanceof IOException) {\n throw (IOException) cause;\n } else if (cause instanceof RuntimeException) {\n throw (RuntimeException) cause;\n } else if (cause instanceof Error) {\n throw (Error) cause;\n } else {\n throw new IllegalStateException(cause);\n }\n } finally {\n cancel(true /* interrupt if running */);\n }\n throw new CancellationException();\n }\n\n private void ensureNotOnMainThread() {\n final Looper looper = Looper.myLooper();\n if (looper != null && looper == Looper.getMainLooper()) {\n final IllegalStateException exception = new IllegalStateException(\n \"calling this from your main thread can lead to deadlock\");\n LOGGER.log(Level.WARNING,\n \"calling this from your main thread can lead to deadlock and/or ANRs\",\n exception);\n throw exception;\n }\n }\n\n }\n\n}",
"public class ImplicitResponseUrl extends GenericUrl {\n\n /** Access token issued by the authorization server. */\n @Key(\"access_token\")\n private String accessToken;\n\n /**\n * Token type (as specified in <a\n * href=\"http://tools.ietf.org/html/rfc6749#section-7.1\">Access Token\n * Types</a>).\n */\n @Key(\"token_type\")\n private String tokenType;\n\n /**\n * Lifetime in seconds of the access token (for example 3600 for an hour) or\n * {@code null} for none.\n */\n @Key(\"expires_in\")\n private Long expiresInSeconds;\n\n /**\n * Scope of the access token as specified in <a\n * href=\"http://tools.ietf.org/html/rfc6749#section-3.3\">Access Token\n * Scope</a> or {@code null} for none.\n */\n @Key\n private String scope;\n\n /**\n * State parameter matching the state parameter in the authorization request\n * or {@code null} for none.\n */\n @Key\n private String state;\n\n /**\n * Error code ({@code \"invalid_request\"}, {@code \"unauthorized_client\"},\n * {@code \"access_denied\"}, {@code \"unsupported_response_type\"},\n * {@code \"invalid_scope\"}, {@code \"server_error\"},\n * {@code \"temporarily_unavailable\"}, or an extension error code as\n * specified in <a\n * href=\"http://tools.ietf.org/html/rfc6749#section-8.5\">Defining Additional\n * Error Codes</a>) or {@code null} for none.\n */\n @Key\n private String error;\n\n /**\n * Human-readable text providing additional information used to assist the\n * client developer in understanding the error that occurred or {@code null}\n * for none.\n */\n @Key(\"error_description\")\n private String errorDescription;\n\n /**\n * URI identifying a human-readable web page with information about the\n * error used to provide the client developer with additional information\n * about the error or {@code null} for none.\n */\n @Key(\"error_uri\")\n private String errorUri;\n\n ImplicitResponseUrl() {\n super();\n }\n\n public ImplicitResponseUrl(String encodedUrl) {\n this(toURI(encodedUrl));\n }\n\n ImplicitResponseUrl(URI uri) {\n this(uri.getScheme(),\n uri.getHost(),\n uri.getPort(),\n uri.getRawPath(),\n uri.getRawFragment(),\n uri.getRawQuery(),\n uri.getRawUserInfo());\n }\n\n ImplicitResponseUrl(URL url) {\n this(url.getProtocol(),\n url.getHost(),\n url.getPort(),\n url.getPath(),\n url.getRef(),\n url.getQuery(),\n url.getUserInfo());\n }\n\n private ImplicitResponseUrl(String scheme, String host, int port, String path, String fragment,\n String query, String userInfo) {\n setScheme(scheme);\n setHost(host);\n setPort(port);\n setPathParts(toPathParts(path));\n setFragment(fragment != null ? CharEscapers.decodeUri(fragment) : null);\n if (fragment != null) {\n UrlEncodedParser.parse(fragment, this);\n }\n // no need for query parameters\n setUserInfo(userInfo != null ? CharEscapers.decodeUri(userInfo) : null);\n }\n\n /** Returns the access token issued by the authorization server. */\n public final String getAccessToken() {\n return accessToken;\n }\n\n /**\n * Sets the access token issued by the authorization server.\n * <p>\n * Overriding is only supported for the purpose of calling the super\n * implementation and changing the return type, but nothing else.\n * </p>\n */\n public ImplicitResponseUrl setAccessToken(String accessToken) {\n this.accessToken = Preconditions.checkNotNull(accessToken);\n return this;\n }\n\n /**\n * Returns the token type (as specified in <a\n * href=\"http://tools.ietf.org/html/rfc6749#section-7.1\">Access Token\n * Types</a>).\n */\n public final String getTokenType() {\n return tokenType;\n }\n\n /**\n * Sets the token type (as specified in <a\n * href=\"http://tools.ietf.org/html/rfc6749#section-7.1\">Access Token\n * Types</a>).\n * <p>\n * Overriding is only supported for the purpose of calling the super\n * implementation and changing the return type, but nothing else.\n * </p>\n */\n public ImplicitResponseUrl setTokenType(String tokenType) {\n this.tokenType = Preconditions.checkNotNull(tokenType);\n return this;\n }\n\n /**\n * Returns the lifetime in seconds of the access token (for example 3600 for\n * an hour) or {@code null} for none.\n */\n public final Long getExpiresInSeconds() {\n return expiresInSeconds;\n }\n\n /**\n * Sets the lifetime in seconds of the access token (for example 3600 for an\n * hour) or {@code null} for none.\n * <p>\n * Overriding is only supported for the purpose of calling the super\n * implementation and changing the return type, but nothing else.\n * </p>\n */\n public ImplicitResponseUrl setExpiresInSeconds(Long expiresInSeconds) {\n this.expiresInSeconds = expiresInSeconds;\n return this;\n }\n\n /**\n * Returns the scope of the access token or {@code null} for none.\n */\n public final String getScope() {\n return scope;\n }\n\n /**\n * Sets the scope of the access token or {@code null} for none.\n * <p>\n * Overriding is only supported for the purpose of calling the super\n * implementation and changing the return type, but nothing else.\n * </p>\n */\n public ImplicitResponseUrl setScope(String scope) {\n this.scope = scope;\n return this;\n }\n\n /**\n * Returns the state parameter matching the state parameter in the\n * authorization request or {@code null} for none.\n */\n public final String getState() {\n return state;\n }\n\n /**\n * Sets the state parameter matching the state parameter in the\n * authorization request or {@code null} for none.\n * <p>\n * Overriding is only supported for the purpose of calling the super\n * implementation and changing the return type, but nothing else.\n * </p>\n */\n public ImplicitResponseUrl setState(String state) {\n this.state = state;\n return this;\n }\n\n /**\n * Returns the error code ({@code \"invalid_request\"},\n * {@code \"unauthorized_client\"}, {@code \"access_denied\"},\n * {@code \"unsupported_response_type\"}, {@code \"invalid_scope\"},\n * {@code \"server_error\"}, {@code \"temporarily_unavailable\"}, or an\n * extension error code as specified in <a\n * href=\"http://tools.ietf.org/html/rfc6749#section-8.5\">Defining Additional\n * Error Codes</a>) or {@code null} for none.\n */\n public final String getError() {\n return error;\n }\n\n /**\n * Sets the error code ({@code \"invalid_request\"},\n * {@code \"unauthorized_client\"}, {@code \"access_denied\"},\n * {@code \"unsupported_response_type\"}, {@code \"invalid_scope\"},\n * {@code \"server_error\"}, {@code \"temporarily_unavailable\"}, or an\n * extension error code as specified in <a\n * href=\"http://tools.ietf.org/html/rfc6749#section-8.5\">Defining Additional\n * Error Codes</a>) or {@code null} for none.\n * <p>\n * Overriding is only supported for the purpose of calling the super\n * implementation and changing the return type, but nothing else.\n * </p>\n */\n public ImplicitResponseUrl setError(String error) {\n this.error = error;\n return this;\n }\n\n /**\n * Returns the human-readable text providing additional information used to\n * assist the client developer in understanding the error that occurred or\n * {@code null} for none.\n */\n public final String getErrorDescription() {\n return errorDescription;\n }\n\n /**\n * Sets the human-readable text providing additional information used to\n * assist the client developer in understanding the error that occurred or\n * {@code null} for none.\n * <p>\n * Overriding is only supported for the purpose of calling the super\n * implementation and changing the return type, but nothing else.\n * </p>\n */\n public ImplicitResponseUrl setErrorDescription(String errorDescription) {\n this.errorDescription = errorDescription;\n return this;\n }\n\n /**\n * Returns the URI identifying a human-readable web page with information\n * about the error used to provide the client developer with additional\n * information about the error or {@code null} for none.\n */\n public final String getErrorUri() {\n return errorUri;\n }\n\n /**\n * Sets the URI identifying a human-readable web page with information about\n * the error used to provide the client developer with additional\n * information about the error or {@code null} for none.\n * <p>\n * Overriding is only supported for the purpose of calling the super\n * implementation and changing the return type, but nothing else.\n * </p>\n */\n public ImplicitResponseUrl setErrorUri(String errorUri) {\n this.errorUri = errorUri;\n return this;\n }\n\n @Override\n public ImplicitResponseUrl set(String fieldName, Object value) {\n return (ImplicitResponseUrl) super.set(fieldName, value);\n }\n\n @Override\n public ImplicitResponseUrl clone() {\n return (ImplicitResponseUrl) super.clone();\n }\n\n /**\n * Returns the URI for the given encoded URL.\n * <p>\n * Any {@link URISyntaxException} is wrapped in an\n * {@link IllegalArgumentException}.\n * </p>\n * \n * @param encodedUrl encoded URL\n * @return URI\n */\n private static URI toURI(String encodedUrl) {\n try {\n return new URI(encodedUrl);\n } catch (URISyntaxException e) {\n throw new IllegalArgumentException(e);\n }\n }\n\n}",
"@TargetApi(Build.VERSION_CODES.GINGERBREAD)\npublic class SharedPreferencesCredentialStore implements CredentialStore {\n\n /** Json factory for serializing user credentials. */\n private final JsonFactory jsonFactory;\n\n private final SharedPreferences prefs;\n\n /**\n * @param context Context in which to store user credentials\n * @param name Name by which the SharedPreferences file is stored as\n * @param jsonFactory JSON factory to serialize user credentials\n */\n public SharedPreferencesCredentialStore(Context context, String name, JsonFactory jsonFactory) {\n Preconditions.checkNotNull(context);\n Preconditions.checkNotNull(name);\n this.prefs = Preconditions.checkNotNull(\n context.getSharedPreferences(name, Context.MODE_PRIVATE));\n this.jsonFactory = Preconditions.checkNotNull(jsonFactory);\n }\n\n @Override\n public boolean load(String userId, Credential credential) throws IOException {\n Preconditions.checkNotNull(userId);\n String credentialJson = prefs.getString(userId, null);\n if (TextUtils.isEmpty(credentialJson)) {\n return false;\n }\n FilePersistedCredential fileCredential = jsonFactory.fromString(\n credentialJson, FilePersistedCredential.class);\n if (fileCredential == null) {\n return false;\n }\n fileCredential.load(credential);\n return true;\n }\n\n @Override\n public void store(String userId, Credential credential) throws IOException {\n Preconditions.checkNotNull(userId);\n FilePersistedCredential fileCredential = new FilePersistedCredential();\n fileCredential.store(credential);\n String credentialJson = jsonFactory.toString(fileCredential);\n prefs.edit().putString(userId, credentialJson).apply();\n }\n\n @Override\n public void delete(String userId, Credential credential) throws IOException {\n Preconditions.checkNotNull(userId);\n prefs.edit().remove(userId).apply();\n }\n\n}"
] | import android.os.Build;
import android.support.v4.app.FragmentActivity;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import com.google.api.client.auth.oauth2.BearerToken;
import com.google.api.client.auth.oauth2.ClientParametersAuthentication;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.http.GenericUrl;
import com.google.api.client.json.jackson.JacksonFactory;
import com.agilie.dribbblesdk.oAuth.AuthorizationFlow;
import com.agilie.dribbblesdk.oAuth.AuthorizationUIController;
import com.agilie.dribbblesdk.oAuth.DialogFragmentController;
import com.agilie.dribbblesdk.oAuth.OAuthManager;
import com.agilie.dribbblesdk.oAuth.oauth2.implicit.ImplicitResponseUrl;
import com.agilie.dribbblesdk.oAuth.oauth2.store.SharedPreferencesCredentialStore;
import java.io.IOException;
import java.util.concurrent.CancellationException; | package com.agilie.dribbblesdk.service.auth;
public class DribbbleAuthHelper {
public interface AuthListener {
void onSuccess(Credential credential);
void onError(Exception ex);
}
public static void startOauthDialog(final FragmentActivity activity,
final AuthCredentials credentials,
final AuthListener listener) {
new Thread() {
@Override
public void run() {
super.run();
try {
final Credential credential = getOauth(activity, credentials).authorizeExplicitly(DribbbleConstants.USER_ID, null, null).getResult();
if (listener != null) {
listener.onSuccess(credential);
}
} catch (IOException | CancellationException ex) {
if (listener != null) {
listener.onError(ex);
}
}
}
}.start();
}
| private static OAuthManager getOauth(FragmentActivity activity, final AuthCredentials credentials) { | 3 |
mikolajmitura/java-properties-to-json | src/main/java/pl/jalokim/propertiestojson/resolvers/ArrayJsonTypeResolver.java | [
"public static ArrayJsonType createOrGetNextDimensionOfArray(ArrayJsonType currentArray, List<Integer> indexes, int indexToTest,\n PathMetadata currentPathMetadata) {\n if (currentArray.existElementByGivenIndex(indexes.get(indexToTest))) {\n AbstractJsonType element = currentArray.getElement(indexes.get(indexToTest));\n if (element instanceof ArrayJsonType) {\n return (ArrayJsonType) element;\n } else {\n List<Integer> currentIndexes = indexes.subList(0, indexToTest + 1);\n String indexesAsText = currentIndexes.stream()\n .map(Object::toString)\n .reduce(EMPTY_STRING, (oldText, index) -> oldText + ARRAY_START_SIGN + index + ARRAY_END_SIGN);\n throw new CannotOverrideFieldException(currentPathMetadata.getCurrentFullPathWithoutIndexes() + indexesAsText, element,\n currentPathMetadata.getOriginalPropertyKey());\n }\n } else {\n ArrayJsonType newArray = new ArrayJsonType();\n currentArray.addElement(indexes.get(indexToTest), newArray, currentPathMetadata);\n return newArray;\n }\n}",
"public final class JsonObjectFieldsValidator {\n\n private JsonObjectFieldsValidator() {\n }\n\n public static void checkThatFieldCanBeSet(ObjectJsonType currentObjectJson, PathMetadata currentPathMetaData, String propertyKey) {\n if (currentObjectJson.containsField(currentPathMetaData.getFieldName())) {\n AbstractJsonType abstractJsonType = currentObjectJson.getField(currentPathMetaData.getFieldName());\n if (currentPathMetaData.isArrayField()) {\n if (isArrayJson(abstractJsonType)) {\n ArrayJsonType jsonArray = currentObjectJson.getJsonArray(currentPathMetaData.getFieldName());\n AbstractJsonType elementByDimArray = jsonArray.getElementByGivenDimIndexes(currentPathMetaData);\n if (elementByDimArray != null) {\n throwErrorWhenCannotMerge(currentPathMetaData, propertyKey, elementByDimArray);\n }\n } else {\n throw new CannotOverrideFieldException(currentPathMetaData.getCurrentFullPathWithoutIndexes(), abstractJsonType, propertyKey);\n }\n } else {\n throwErrorWhenCannotMerge(currentPathMetaData, propertyKey, abstractJsonType);\n }\n }\n }\n\n private static void throwErrorWhenCannotMerge(PathMetadata currentPathMetaData, String propertyKey, AbstractJsonType oldJsonValue) {\n if (!isMergableJsonType(oldJsonValue)) {\n throw new CannotOverrideFieldException(currentPathMetaData.getCurrentFullPath(), oldJsonValue, propertyKey);\n }\n }\n\n public static void checkEarlierWasJsonObject(String propertyKey, PathMetadata currentPathMetaData, AbstractJsonType jsonType) {\n if (!isObjectJson(jsonType)) {\n throw new CannotOverrideFieldException(currentPathMetaData.getCurrentFullPath(), jsonType, propertyKey);\n }\n }\n\n public static boolean isObjectJson(AbstractJsonType jsonType) {\n return ObjectJsonType.class.isAssignableFrom(jsonType.getClass());\n }\n\n public static boolean isPrimitiveValue(AbstractJsonType jsonType) {\n return PrimitiveJsonType.class.isAssignableFrom(jsonType.getClass()) || JsonNullReferenceType.class.isAssignableFrom(jsonType.getClass());\n }\n\n public static boolean isArrayJson(AbstractJsonType jsonType) {\n return ArrayJsonType.class.isAssignableFrom(jsonType.getClass());\n }\n\n public static boolean isMergableJsonType(Object jsonType) {\n return MergableObject.class.isAssignableFrom(jsonType.getClass());\n }\n}",
"@Getter\npublic class PropertyArrayHelper {\n\n private List<Integer> dimensionalIndexes;\n private String arrayFieldName;\n\n public PropertyArrayHelper(String field) {\n arrayFieldName = getNameFromArray(field);\n dimensionalIndexes = getIndexesFromArrayField(field);\n }\n\n public static String getNameFromArray(String fieldName) {\n return fieldName.replaceFirst(INDEXES_PATTERN + \"$\", EMPTY_STRING);\n }\n\n public static List<Integer> getIndexesFromArrayField(String fieldName) {\n String indexesAsText = fieldName.replace(getNameFromArray(fieldName), EMPTY_STRING);\n String[] indexesAsTextArray = indexesAsText\n .replace(ARRAY_START_SIGN, EMPTY_STRING)\n .replace(ARRAY_END_SIGN, SIMPLE_ARRAY_DELIMITER)\n .replaceAll(\"\\\\s\", EMPTY_STRING)\n .split(SIMPLE_ARRAY_DELIMITER);\n List<Integer> indexes = new ArrayList<>();\n for (String indexAsText : indexesAsTextArray) {\n indexes.add(Integer.valueOf(indexAsText));\n }\n return indexes;\n }\n}",
"public abstract class AbstractJsonType {\r\n\r\n /**\r\n * This one simply concatenate to rest of json. Simply speaking when will not converted then will not create whole json correctly.\r\n *\r\n * @return string for part of json.\r\n */\r\n public abstract String toStringJson();\r\n\r\n @Override\r\n public final String toString() {\r\n return toStringJson();\r\n }\r\n}\r",
"public class ArrayJsonType extends AbstractJsonType implements MergableObject<ArrayJsonType> {\n\n public static final int INIT_SIZE = 100;\n private AbstractJsonType[] elements = new AbstractJsonType[INIT_SIZE];\n private int maxIndex = -1;\n\n public ArrayJsonType() {\n }\n\n @SuppressWarnings(\"PMD.ConstructorCallsOverridableMethod\")\n public ArrayJsonType(PrimitiveJsonTypesResolver primitiveJsonTypesResolver, Collection<?> elements, PathMetadata currentPathMetadata, String propertyKey) {\n Iterator<?> iterator = elements.iterator();\n int index = 0;\n while (iterator.hasNext()) {\n Object element = iterator.next();\n addElement(index, primitiveJsonTypesResolver.resolvePrimitiveTypeAndReturn(element, propertyKey), currentPathMetadata);\n index++;\n }\n }\n\n public static ArrayJsonType createOrGetNextDimensionOfArray(ArrayJsonType currentArray, List<Integer> indexes, int indexToTest,\n PathMetadata currentPathMetadata) {\n if (currentArray.existElementByGivenIndex(indexes.get(indexToTest))) {\n AbstractJsonType element = currentArray.getElement(indexes.get(indexToTest));\n if (element instanceof ArrayJsonType) {\n return (ArrayJsonType) element;\n } else {\n List<Integer> currentIndexes = indexes.subList(0, indexToTest + 1);\n String indexesAsText = currentIndexes.stream()\n .map(Object::toString)\n .reduce(EMPTY_STRING, (oldText, index) -> oldText + ARRAY_START_SIGN + index + ARRAY_END_SIGN);\n throw new CannotOverrideFieldException(currentPathMetadata.getCurrentFullPathWithoutIndexes() + indexesAsText, element,\n currentPathMetadata.getOriginalPropertyKey());\n }\n } else {\n ArrayJsonType newArray = new ArrayJsonType();\n currentArray.addElement(indexes.get(indexToTest), newArray, currentPathMetadata);\n return newArray;\n }\n }\n\n public void addElement(int index, AbstractJsonType elementToAdd, PathMetadata currentPathMetadata) {\n if (maxIndex < index) {\n maxIndex = index;\n }\n rewriteArrayWhenIsFull(index);\n AbstractJsonType oldObject = elements[index];\n\n if (oldObject == null) {\n elements[index] = elementToAdd;\n } else {\n if (oldObject instanceof MergableObject && elementToAdd instanceof MergableObject) {\n mergeObjectIfPossible(oldObject, elementToAdd, currentPathMetadata);\n } else {\n throw new CannotOverrideFieldException(currentPathMetadata.getCurrentFullPath(), oldObject, currentPathMetadata.getOriginalPropertyKey());\n }\n }\n }\n\n public void addElement(PropertyArrayHelper propertyArrayHelper, AbstractJsonType elementToAdd, PathMetadata currentPathMetadata) {\n List<Integer> indexes = propertyArrayHelper.getDimensionalIndexes();\n int size = propertyArrayHelper.getDimensionalIndexes().size();\n ArrayJsonType currentArray = this;\n for (int index = 0; index < size; index++) {\n if (isLastIndex(propertyArrayHelper.getDimensionalIndexes(), index)) {\n currentArray.addElement(indexes.get(index), elementToAdd, currentPathMetadata);\n } else {\n currentArray = createOrGetNextDimensionOfArray(currentArray, indexes, index, currentPathMetadata);\n }\n }\n }\n\n public AbstractJsonType getElementByGivenDimIndexes(PathMetadata currentPathMetaData) {\n PropertyArrayHelper propertyArrayHelper = currentPathMetaData.getPropertyArrayHelper();\n List<Integer> indexes = propertyArrayHelper.getDimensionalIndexes();\n int size = propertyArrayHelper.getDimensionalIndexes().size();\n ArrayJsonType currentArray = this;\n for (int i = 0; i < size; i++) {\n if (isLastIndex(propertyArrayHelper.getDimensionalIndexes(), i)) {\n return currentArray.getElement(indexes.get(i));\n } else {\n AbstractJsonType element = currentArray.getElement(indexes.get(i));\n if (element == null) {\n return null;\n }\n if (element instanceof ArrayJsonType) {\n currentArray = (ArrayJsonType) element;\n } else {\n List<Integer> currentIndexes = indexes.subList(0, i + 1);\n String indexesAsText = currentIndexes.stream()\n .map(Object::toString)\n .reduce(EMPTY_STRING, (oldText, index) -> oldText + ARRAY_START_SIGN + index + ARRAY_END_SIGN);\n throw new CannotOverrideFieldException(currentPathMetaData.getCurrentFullPathWithoutIndexes() + indexesAsText, element,\n currentPathMetaData.getOriginalPropertyKey());\n }\n }\n }\n throw new UnsupportedOperationException(\n \"cannot return expected object for \" + currentPathMetaData.getCurrentFullPath() + \" \" + currentPathMetaData.getPropertyArrayHelper()\n .getDimensionalIndexes());\n }\n\n public boolean existElementByGivenIndex(int index) {\n return getElement(index) != null;\n }\n\n private void rewriteArrayWhenIsFull(int index) {\n if (indexHigherThanArraySize(index)) {\n int predictedNewSize = elements.length + INIT_SIZE;\n int newSize = predictedNewSize > index ? predictedNewSize : index + 1;\n AbstractJsonType[] elementsTemp = new AbstractJsonType[newSize];\n System.arraycopy(elements, 0, elementsTemp, 0, elements.length);\n elements = elementsTemp;\n }\n }\n\n private boolean indexHigherThanArraySize(int index) {\n return index > getLastIndex(elements);\n }\n\n public AbstractJsonType getElement(int index) {\n rewriteArrayWhenIsFull(index);\n return elements[index];\n }\n\n @Override\n public String toStringJson() {\n StringBuilder result = new StringBuilder().append(ARRAY_START_SIGN);\n int index = 0;\n List<AbstractJsonType> elementsAsList = convertToListWithoutRealNull();\n int lastIndex = getLastIndex(elementsAsList);\n for (AbstractJsonType element : elementsAsList) {\n if (!(element instanceof SkipJsonField)) {\n String lastSign = index == lastIndex ? EMPTY_STRING : NEW_LINE_SIGN;\n result.append(element.toStringJson())\n .append(lastSign);\n }\n index++;\n }\n return result.append(ARRAY_END_SIGN).toString();\n }\n\n public List<AbstractJsonType> convertToListWithoutRealNull() {\n List<AbstractJsonType> elementsList = new ArrayList<>();\n\n for (int i = 0; i < maxIndex + 1; i++) {\n AbstractJsonType element = elements[i];\n if (element == null) {\n elementsList.add(NULL_OBJECT);\n } else {\n elementsList.add(element);\n }\n }\n return elementsList;\n }\n\n private List<AbstractJsonType> convertToListWithRealNull() {\n List<AbstractJsonType> elementsList = new ArrayList<>();\n for (int i = 0; i < maxIndex + 1; i++) {\n AbstractJsonType element = elements[i];\n elementsList.add(element);\n }\n return elementsList;\n }\n\n @Override\n public void merge(ArrayJsonType mergeWith, PathMetadata currentPathMetadata) {\n int index = 0;\n for (AbstractJsonType abstractJsonType : mergeWith.convertToListWithRealNull()) {\n addElement(index, abstractJsonType, currentPathMetadata);\n index++;\n }\n }\n}",
"public class ObjectJsonType extends AbstractJsonType implements MergableObject<ObjectJsonType> {\n\n @SuppressWarnings(\"PMD.UseConcurrentHashMap\")\n private final Map<String, AbstractJsonType> fields = new LinkedHashMap<>();\n\n public void addField(final String field, final AbstractJsonType object, PathMetadata currentPathMetaData) {\n if (object instanceof SkipJsonField) {\n return;\n }\n\n AbstractJsonType oldFieldValue = fields.get(field);\n if (oldFieldValue == null) {\n fields.put(field, object);\n } else {\n if (oldFieldValue instanceof MergableObject && object instanceof MergableObject) {\n mergeObjectIfPossible(oldFieldValue, object, currentPathMetaData);\n } else {\n throw new CannotOverrideFieldException(currentPathMetaData.getCurrentFullPath(),\n oldFieldValue,\n currentPathMetaData.getOriginalPropertyKey());\n }\n }\n }\n\n public boolean containsField(String field) {\n return fields.containsKey(field);\n }\n\n public AbstractJsonType getField(String field) {\n return fields.get(field);\n }\n\n public ArrayJsonType getJsonArray(String field) {\n return (ArrayJsonType) fields.get(field);\n }\n\n @Override\n public String toStringJson() {\n StringBuilder result = new StringBuilder().append(JSON_OBJECT_START);\n int index = 0;\n int lastIndex = getLastIndex(fields.keySet());\n for (Map.Entry<String, AbstractJsonType> entry : fields.entrySet()) {\n AbstractJsonType object = entry.getValue();\n String lastSign = index == lastIndex ? EMPTY_STRING : NEW_LINE_SIGN;\n result.append(StringToJsonStringWrapper.wrap(entry.getKey()))\n .append(':')\n .append(object.toStringJson())\n .append(lastSign);\n index++;\n }\n result.append(JSON_OBJECT_END);\n return result.toString();\n }\n\n @Override\n public void merge(ObjectJsonType mergeWith, PathMetadata currentPathMetadata) {\n for (String fieldName : mergeWith.fields.keySet()) {\n addField(fieldName, mergeWith.getField(fieldName), currentPathMetadata);\n }\n }\n}",
"@Data\npublic class PathMetadata {\n\n private static final String NUMBER_PATTERN = \"([1-9]\\\\d*)|0\";\n public static final String INDEXES_PATTERN = \"\\\\s*(\\\\[\\\\s*((\" + NUMBER_PATTERN + \")|\\\\*)\\\\s*]\\\\s*)+\";\n\n private static final String WORD_PATTERN = \"(.)*\";\n\n private final String originalPropertyKey;\n private PathMetadata parent;\n private String fieldName;\n private String originalFieldName;\n private PathMetadata child;\n private PropertyArrayHelper propertyArrayHelper;\n private Object rawValue;\n private AbstractJsonType jsonValue;\n\n public boolean isLeaf() {\n return child == null;\n }\n\n public boolean isRoot() {\n return parent == null;\n }\n\n public String getCurrentFullPath() {\n return parent == null ? originalFieldName : parent.getCurrentFullPath() + NORMAL_DOT + originalFieldName;\n }\n\n public PathMetadata getLeaf() {\n PathMetadata current = this;\n while (current.getChild() != null) {\n current = current.getChild();\n }\n return current;\n }\n\n public void setFieldName(String fieldName) {\n this.fieldName = fieldName;\n if (fieldName.matches(WORD_PATTERN + INDEXES_PATTERN)) {\n propertyArrayHelper = new PropertyArrayHelper(fieldName);\n this.fieldName = propertyArrayHelper.getArrayFieldName();\n }\n }\n\n public void setRawValue(Object rawValue) {\n if (!isLeaf()) {\n throw new NotLeafValueException(\"Cannot set value for not leaf: \" + getCurrentFullPath());\n }\n this.rawValue = rawValue;\n }\n\n public String getOriginalPropertyKey() {\n return originalPropertyKey;\n }\n\n public PathMetadata getRoot() {\n PathMetadata current = this;\n while (current.getParent() != null) {\n current = current.getParent();\n }\n return current;\n }\n\n public String getCurrentFullPathWithoutIndexes() {\n String parentFullPath = isRoot() ? EMPTY_STRING : getParent().getCurrentFullPath() + NORMAL_DOT;\n return parentFullPath + getFieldName();\n }\n\n public AbstractJsonType getJsonValue() {\n return jsonValue;\n }\n\n public void setJsonValue(AbstractJsonType jsonValue) {\n if (!isLeaf()) {\n throw new NotLeafValueException(\"Cannot set value for not leaf: \" + getCurrentFullPath());\n }\n this.jsonValue = jsonValue;\n }\n\n @Override\n public String toString() {\n return \"field='\" + fieldName + '\\''\n + \", rawValue=\" + rawValue\n + \", fullPath='\" + getCurrentFullPath() + '}';\n }\n\n public boolean isArrayField() {\n return propertyArrayHelper != null;\n }\n}"
] | import static pl.jalokim.propertiestojson.object.ArrayJsonType.createOrGetNextDimensionOfArray;
import static pl.jalokim.utils.collection.CollectionUtils.isLastIndex;
import java.util.List;
import pl.jalokim.propertiestojson.JsonObjectFieldsValidator;
import pl.jalokim.propertiestojson.PropertyArrayHelper;
import pl.jalokim.propertiestojson.object.AbstractJsonType;
import pl.jalokim.propertiestojson.object.ArrayJsonType;
import pl.jalokim.propertiestojson.object.ObjectJsonType;
import pl.jalokim.propertiestojson.path.PathMetadata; | package pl.jalokim.propertiestojson.resolvers;
public class ArrayJsonTypeResolver extends JsonTypeResolver {
@Override
public ObjectJsonType traverse(PathMetadata currentPathMetaData) {
fetchJsonObjectAndCreateArrayWhenNotExist(currentPathMetaData);
return currentObjectJsonType;
}
private void fetchJsonObjectAndCreateArrayWhenNotExist(PathMetadata currentPathMetaData) {
if (isArrayExist(currentPathMetaData.getFieldName())) {
fetchArrayAndAddElement(currentPathMetaData);
} else {
createArrayAndAddElement(currentPathMetaData);
}
}
private boolean isArrayExist(String field) {
return currentObjectJsonType.containsField(field);
}
private void fetchArrayAndAddElement(PathMetadata currentPathMetaData) {
PropertyArrayHelper propertyArrayHelper = currentPathMetaData.getPropertyArrayHelper();
ArrayJsonType arrayJsonType = getArrayJsonWhenIsValid(currentPathMetaData);
List<Integer> dimIndexes = propertyArrayHelper.getDimensionalIndexes();
ArrayJsonType currentArray = arrayJsonType;
for (int index = 0; index < dimIndexes.size(); index++) {
if (isLastIndex(dimIndexes, index)) {
int lastDimIndex = dimIndexes.get(index);
if (currentArray.existElementByGivenIndex(lastDimIndex)) {
fetchJsonObjectWhenIsValid(currentPathMetaData, lastDimIndex, currentArray);
} else {
createJsonObjectAndAddToArray(lastDimIndex, currentArray, currentPathMetaData);
}
} else { | currentArray = createOrGetNextDimensionOfArray(currentArray, dimIndexes, index, currentPathMetaData); | 0 |
WolfgangFahl/Mediawiki-Japi | src/test/java/com/bitplan/mediawiki/japi/TestAPI_Allpages.java | [
"@XmlAccessorType(XmlAccessType.FIELD)\n@XmlType(name = \"\")\npublic class Bl {\n\n @XmlAttribute(name = \"pageid\")\n protected Integer pageid;\n @XmlAttribute(name = \"ns\")\n protected Integer ns;\n @XmlAttribute(name = \"title\")\n protected String title;\n\n /**\n * Ruft den Wert der pageid-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link Integer }\n * \n */\n public Integer getPageid() {\n return pageid;\n }\n\n /**\n * Legt den Wert der pageid-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link Integer }\n * \n */\n public void setPageid(Integer value) {\n this.pageid = value;\n }\n\n /**\n * Ruft den Wert der ns-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link Integer }\n * \n */\n public Integer getNs() {\n return ns;\n }\n\n /**\n * Legt den Wert der ns-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link Integer }\n * \n */\n public void setNs(Integer value) {\n this.ns = value;\n }\n\n /**\n * Ruft den Wert der title-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getTitle() {\n return title;\n }\n\n /**\n * Legt den Wert der title-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setTitle(String value) {\n this.title = value;\n }\n\n}",
"@XmlAccessorType(XmlAccessType.FIELD)\n@XmlType(name = \"\")\npublic class Ii {\n\n @XmlAttribute(name = \"timestamp\")\n @XmlSchemaType(name = \"dateTime\")\n protected XMLGregorianCalendar timestamp;\n @XmlAttribute(name = \"user\")\n protected String user;\n @XmlAttribute(name = \"userid\")\n protected Integer userid;\n @XmlAttribute(name = \"size\")\n protected Integer size;\n @XmlAttribute(name = \"width\")\n protected Short width;\n @XmlAttribute(name = \"height\")\n protected Short height;\n @XmlAttribute(name = \"parsedcomment\")\n protected String parsedcomment;\n @XmlAttribute(name = \"comment\")\n protected String comment;\n @XmlAttribute(name = \"html\")\n protected String html;\n @XmlAttribute(name = \"canonicaltitle\")\n protected String canonicaltitle;\n @XmlAttribute(name = \"url\")\n protected String url;\n @XmlAttribute(name = \"descriptionurl\")\n protected String descriptionurl;\n @XmlAttribute(name = \"sha1\")\n protected String sha1;\n @XmlAttribute(name = \"mime\")\n protected String mime;\n @XmlAttribute(name = \"mediatype\")\n protected String mediatype;\n @XmlAttribute(name = \"bitdepth\")\n protected BigInteger bitdepth;\n\n /**\n * Ruft den Wert der timestamp-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link XMLGregorianCalendar }\n * \n */\n public XMLGregorianCalendar getTimestamp() {\n return timestamp;\n }\n\n /**\n * Legt den Wert der timestamp-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link XMLGregorianCalendar }\n * \n */\n public void setTimestamp(XMLGregorianCalendar value) {\n this.timestamp = value;\n }\n\n /**\n * Ruft den Wert der user-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getUser() {\n return user;\n }\n\n /**\n * Legt den Wert der user-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setUser(String value) {\n this.user = value;\n }\n\n /**\n * Ruft den Wert der userid-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link Integer }\n * \n */\n public Integer getUserid() {\n return userid;\n }\n\n /**\n * Legt den Wert der userid-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link Integer }\n * \n */\n public void setUserid(Integer value) {\n this.userid = value;\n }\n\n /**\n * Ruft den Wert der size-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link Integer }\n * \n */\n public Integer getSize() {\n return size;\n }\n\n /**\n * Legt den Wert der size-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link Integer }\n * \n */\n public void setSize(Integer value) {\n this.size = value;\n }\n\n /**\n * Ruft den Wert der width-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link Short }\n * \n */\n public Short getWidth() {\n return width;\n }\n\n /**\n * Legt den Wert der width-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link Short }\n * \n */\n public void setWidth(Short value) {\n this.width = value;\n }\n\n /**\n * Ruft den Wert der height-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link Short }\n * \n */\n public Short getHeight() {\n return height;\n }\n\n /**\n * Legt den Wert der height-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link Short }\n * \n */\n public void setHeight(Short value) {\n this.height = value;\n }\n\n /**\n * Ruft den Wert der parsedcomment-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getParsedcomment() {\n return parsedcomment;\n }\n\n /**\n * Legt den Wert der parsedcomment-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setParsedcomment(String value) {\n this.parsedcomment = value;\n }\n\n /**\n * Ruft den Wert der comment-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getComment() {\n return comment;\n }\n\n /**\n * Legt den Wert der comment-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setComment(String value) {\n this.comment = value;\n }\n\n /**\n * Ruft den Wert der html-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getHtml() {\n return html;\n }\n\n /**\n * Legt den Wert der html-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setHtml(String value) {\n this.html = value;\n }\n\n /**\n * Ruft den Wert der canonicaltitle-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getCanonicaltitle() {\n return canonicaltitle;\n }\n\n /**\n * Legt den Wert der canonicaltitle-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setCanonicaltitle(String value) {\n this.canonicaltitle = value;\n }\n\n /**\n * Ruft den Wert der url-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getUrl() {\n return url;\n }\n\n /**\n * Legt den Wert der url-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setUrl(String value) {\n this.url = value;\n }\n\n /**\n * Ruft den Wert der descriptionurl-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getDescriptionurl() {\n return descriptionurl;\n }\n\n /**\n * Legt den Wert der descriptionurl-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setDescriptionurl(String value) {\n this.descriptionurl = value;\n }\n\n /**\n * Ruft den Wert der sha1-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getSha1() {\n return sha1;\n }\n\n /**\n * Legt den Wert der sha1-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setSha1(String value) {\n this.sha1 = value;\n }\n\n /**\n * Ruft den Wert der mime-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getMime() {\n return mime;\n }\n\n /**\n * Legt den Wert der mime-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setMime(String value) {\n this.mime = value;\n }\n\n /**\n * Ruft den Wert der mediatype-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getMediatype() {\n return mediatype;\n }\n\n /**\n * Legt den Wert der mediatype-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setMediatype(String value) {\n this.mediatype = value;\n }\n\n /**\n * Ruft den Wert der bitdepth-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link BigInteger }\n * \n */\n public BigInteger getBitdepth() {\n return bitdepth;\n }\n\n /**\n * Legt den Wert der bitdepth-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link BigInteger }\n * \n */\n public void setBitdepth(BigInteger value) {\n this.bitdepth = value;\n }\n\n}",
"@XmlAccessorType(XmlAccessType.FIELD)\n@XmlType(name = \"\")\npublic class Im {\n\n @XmlAttribute(name = \"ns\")\n protected Integer ns;\n @XmlAttribute(name = \"title\")\n protected String title;\n\n /**\n * Gets the value of the ns property.\n * \n * @return\n * possible object is\n * {@link Integer }\n * \n */\n public Integer getNs() {\n return ns;\n }\n\n /**\n * Sets the value of the ns property.\n * \n * @param value\n * allowed object is\n * {@link Integer }\n * \n */\n public void setNs(Integer value) {\n this.ns = value;\n }\n\n /**\n * Gets the value of the title property.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getTitle() {\n return title;\n }\n\n /**\n * Sets the value of the title property.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setTitle(String value) {\n this.title = value;\n }\n\n}",
"@XmlAccessorType(XmlAccessType.FIELD)\n@XmlType(name = \"\")\npublic class Img {\n\n @XmlAttribute(name = \"name\")\n protected String name;\n @XmlAttribute(name = \"timestamp\")\n @XmlSchemaType(name = \"dateTime\")\n protected XMLGregorianCalendar timestamp;\n @XmlAttribute(name = \"url\")\n protected String url;\n @XmlAttribute(name = \"descriptionurl\")\n protected String descriptionurl;\n @XmlAttribute(name = \"ns\")\n protected Integer ns;\n @XmlAttribute(name = \"title\")\n protected String title;\n\n /**\n * Ruft den Wert der name-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getName() {\n return name;\n }\n\n /**\n * Legt den Wert der name-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setName(String value) {\n this.name = value;\n }\n\n /**\n * Ruft den Wert der timestamp-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link XMLGregorianCalendar }\n * \n */\n public XMLGregorianCalendar getTimestamp() {\n return timestamp;\n }\n\n /**\n * Legt den Wert der timestamp-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link XMLGregorianCalendar }\n * \n */\n public void setTimestamp(XMLGregorianCalendar value) {\n this.timestamp = value;\n }\n\n /**\n * Ruft den Wert der url-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getUrl() {\n return url;\n }\n\n /**\n * Legt den Wert der url-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setUrl(String value) {\n this.url = value;\n }\n\n /**\n * Ruft den Wert der descriptionurl-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getDescriptionurl() {\n return descriptionurl;\n }\n\n /**\n * Legt den Wert der descriptionurl-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setDescriptionurl(String value) {\n this.descriptionurl = value;\n }\n\n /**\n * Ruft den Wert der ns-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link Integer }\n * \n */\n public Integer getNs() {\n return ns;\n }\n\n /**\n * Legt den Wert der ns-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link Integer }\n * \n */\n public void setNs(Integer value) {\n this.ns = value;\n }\n\n /**\n * Ruft den Wert der title-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getTitle() {\n return title;\n }\n\n /**\n * Legt den Wert der title-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setTitle(String value) {\n this.title = value;\n }\n\n}",
"@XmlAccessorType(XmlAccessType.FIELD)\n@XmlType(name = \"\")\npublic class Iu {\n\n @XmlAttribute(name = \"pageid\")\n protected Integer pageid;\n @XmlAttribute(name = \"ns\")\n protected Integer ns;\n @XmlAttribute(name = \"title\")\n protected String title;\n\n /**\n * Ruft den Wert der pageid-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link Integer }\n * \n */\n public Integer getPageid() {\n return pageid;\n }\n\n /**\n * Legt den Wert der pageid-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link Integer }\n * \n */\n public void setPageid(Integer value) {\n this.pageid = value;\n }\n\n /**\n * Ruft den Wert der ns-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link Integer }\n * \n */\n public Integer getNs() {\n return ns;\n }\n\n /**\n * Legt den Wert der ns-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link Integer }\n * \n */\n public void setNs(Integer value) {\n this.ns = value;\n }\n\n /**\n * Ruft den Wert der title-Eigenschaft ab.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getTitle() {\n return title;\n }\n\n /**\n * Legt den Wert der title-Eigenschaft fest.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setTitle(String value) {\n this.title = value;\n }\n\n}",
"@XmlAccessorType(XmlAccessType.FIELD)\n@XmlType(name = \"\", propOrder = {\n \"value\"\n})\npublic class P {\n\n @XmlValue\n protected String value;\n @XmlAttribute(name = \"pageid\")\n protected Integer pageid;\n @XmlAttribute(name = \"ns\")\n protected Byte ns;\n @XmlAttribute(name = \"title\")\n protected String title;\n\n /**\n * Gets the value of the value property.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getValue() {\n return value;\n }\n\n /**\n * Sets the value of the value property.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setValue(String value) {\n this.value = value;\n }\n\n /**\n * Gets the value of the pageid property.\n * \n * @return\n * possible object is\n * {@link Integer }\n * \n */\n public Integer getPageid() {\n return pageid;\n }\n\n /**\n * Sets the value of the pageid property.\n * \n * @param value\n * allowed object is\n * {@link Integer }\n * \n */\n public void setPageid(Integer value) {\n this.pageid = value;\n }\n\n /**\n * Gets the value of the ns property.\n * \n * @return\n * possible object is\n * {@link Byte }\n * \n */\n public Byte getNs() {\n return ns;\n }\n\n /**\n * Sets the value of the ns property.\n * \n * @param value\n * allowed object is\n * {@link Byte }\n * \n */\n public void setNs(Byte value) {\n this.ns = value;\n }\n\n /**\n * Gets the value of the title property.\n * \n * @return\n * possible object is\n * {@link String }\n * \n */\n public String getTitle() {\n return title;\n }\n\n /**\n * Sets the value of the title property.\n * \n * @param value\n * allowed object is\n * {@link String }\n * \n */\n public void setTitle(String value) {\n this.title = value;\n }\n\n}"
] | import com.bitplan.mediawiki.japi.api.Ii;
import com.bitplan.mediawiki.japi.api.Im;
import com.bitplan.mediawiki.japi.api.Img;
import com.bitplan.mediawiki.japi.api.Iu;
import com.bitplan.mediawiki.japi.api.P;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.List;
import java.util.logging.Level;
import org.junit.Test;
import com.bitplan.mediawiki.japi.api.Bl; | /**
*
* This file is part of the https://github.com/WolfgangFahl/Mediawiki-Japi open source project
*
* Copyright 2015-2021 BITPlan GmbH https://github.com/BITPlan
*
* 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.bitplan.mediawiki.japi;
/**
* test https://www.mediawiki.org/wiki/API:Allpages
*
* @author wf
*
*/
public class TestAPI_Allpages extends APITestbase {
@Test
public void testAllpages() throws Exception {
ExampleWiki lWiki = ewm.get(ExampleWiki.DEFAULT_WIKI_ID);
debug = true;
if (hasWikiUser(lWiki)) {
lWiki.login();
String apfrom = null;
int aplimit = 25000;
List<P> pages = lWiki.wiki.getAllPages(apfrom, aplimit);
if (debug) {
LOGGER.log(Level.INFO, "page #=" + pages.size());
}
assertTrue(pages.size() >= 6);
}
}
@Test
public void testGetAllImagesByTimeStamp() throws Exception {
ExampleWiki lWiki = ewm.get("bitplanwiki");
String[] expectedUsage = { "PDF Example", "Picture Example" };
String[] expected = { "Wuthering_Heights_NT.pdf",
"Radcliffe_Chastenay_-_Les_Mysteres_d_Udolphe_frontispice_T6.jpg" };
String aistart = "20210703131900";
String aiend = "20210703132500";
int ailimit = 500;
// lWiki.wiki.setDebug(true);
List<Img> images = lWiki.wiki.getAllImagesByTimeStamp(aistart, aiend, ailimit);
// debug = true;
if (debug) {
LOGGER.log(Level.INFO, "found images:" + images.size());
int i=0;
for (Img image:images) {
i++;
LOGGER.log(Level.INFO,String.format("%d: %s %s",i, image.getTimestamp(),image.getName()));
}
}
assertEquals(expected.length, images.size());
for (int i = 0; i < expected.length; i++) {
assertEquals(expected[i], images.get(i).getName());
}
// lWiki.wiki.setDebug(true);
int i = 0;
for (Img img : images) {
if (!"Index.png".equals(img.getName())) {
List<Iu> ius = lWiki.wiki.getImageUsage("File:" + img.getName(), "", 50);
assertTrue(img.getName(), ius.size() > 1);
assertEquals(expectedUsage[i], ius.get(0).getTitle());
i++;
}
}
}
@Test
public void testBacklink() throws Exception {
ExampleWiki lWiki = ewm.get("bitplanwiki");
// lWiki.wiki.setDebug(true);
String pageTitle = "Picture Example";
List<Bl> bls = lWiki.wiki.getBacklinks(pageTitle, "", 50);
assertTrue(bls.size() >= 1);
assertEquals("PDF Example", bls.get(0).getTitle());
}
@Test
public void testImagesOnPage() throws Exception {
ExampleWiki lWiki = ewm.get("bitplanwiki");
// lWiki.wiki.setDebug(true);
String pageTitles[] = { "Picture Example", "PDF Example", "Image Example" };
String[][] expected = { { "File:Radcliffe Chastenay - Les Mysteres d Udolphe frontispice T6.jpg" },
{ "File:Wuthering Heights NT.pdf" },
{ "File:Radcliffe Chastenay - Les Mysteres d Udolphe frontispice T6.jpg",
"File:Wuthering Heights NT.pdf" } };
int i = 0;
for (String pageTitle : pageTitles) { | List<Im> images = lWiki.wiki.getImagesOnPage(pageTitle, 100); | 2 |
aw20/MongoWorkBench | src/org/aw20/mongoworkbench/eclipse/view/wizard/MapReduceWizard.java | [
"public enum Event {\n\n\tDOCUMENT_VIEW,\n\tELEMENT_VIEW,\n\t\n\tWRITERESULT,\n\t\n\tEXCEPTION, \n\t\n\tTOWIZARD\n\t\n}",
"public class EventWorkBenchManager extends Object {\n\tprivate static EventWorkBenchManager thisInst;\n\t\n\tpublic static synchronized EventWorkBenchManager getInst(){\n\t\tif ( thisInst == null )\n\t\t\tthisInst = new EventWorkBenchManager();\n\n\t\treturn thisInst;\n\t}\n\n\tprivate Set<EventWorkBenchListener>\tlisteners;\n\t\n\tprivate EventWorkBenchManager(){\n\t\tlisteners\t= new HashSet<EventWorkBenchListener>();\n\t}\n\t\n\tpublic void registerListener(EventWorkBenchListener listener){\n\t\tlisteners.add(listener);\n\t}\n\t\n\tpublic void deregisterListener(EventWorkBenchListener listener){\n\t\tlisteners.remove(listener);\n\t}\n\n\tpublic void onEvent( final Event event, final Object data ){\n\t\t\n\t\tnew Thread(\"EventWorkBenchEventFire\"){ \n\t\t\tpublic void run(){\n\t\t\t\tIterator<EventWorkBenchListener>\tit\t= listeners.iterator();\n\t\t\t\twhile ( it.hasNext() ){\n\t\t\t\t\ttry{\n\t\t\t\t\t\tit.next().onEventWorkBench(event, data);\n\t\t\t\t\t}catch(Exception e){\n\t\t\t\t\t\tSystem.out.println(e);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}.start();\n\n\t}\n\t\n}",
"public class MongoFactory extends Thread {\n\n\tprivate static MongoFactory\tthisInst = null;\n\t\n\tpublic static synchronized MongoFactory getInst(){\n\t\tif ( thisInst == null )\n\t\t\tthisInst = new MongoFactory();\n\n\t\treturn thisInst;\n\t}\n\t\n\tprivate Map<String,MongoClient>\tmongoMap;\n\t\n\tprivate Set<MongoCommandListener>\tmongoListeners;\n\tprivate Set<MDocumentView>\tdocumentViewListeners;\n\t\n\tprivate List<MongoCommand>\tcommandQueue;\n\tprivate Map<String, Class>\tcommandMap;\n\tprivate boolean bRun = true;\n\n\t\n\tprivate String activeServer = null, activeDB = null, activeCollection = null;\n\t\n\tpublic MongoFactory(){\n\t\tmongoMap\t\t\t\t\t\t\t= new HashMap<String,MongoClient>();\n\t\tcommandQueue\t\t\t\t\t=\tnew ArrayList<MongoCommand>(); \n\t\tmongoListeners\t\t\t\t= new HashSet<MongoCommandListener>();\n\t\tdocumentViewListeners\t= new HashSet<MDocumentView>();\n\t\tcommandMap\t\t\t\t\t\t= new HashMap<String,Class>();\n\n\t\t// Register the Commands\n\t\tcommandMap.put(\"^db\\\\.[^\\\\(]+\\\\.find\\\\(.*\", FindMongoCommand.class);\n\t\tcommandMap.put(\"^db\\\\.[^\\\\(]+\\\\.findOne\\\\(.*\", FindOneMongoCommand.class);\n\t\tcommandMap.put(\"^db\\\\.[^\\\\(]+\\\\.save\\\\(.*\", SaveMongoCommand.class);\n\t\tcommandMap.put(\"^db\\\\.[^\\\\(]+\\\\.update\\\\(.*\", UpdateMongoCommand.class);\n\t\tcommandMap.put(\"^db\\\\.[^\\\\(]+\\\\.remove\\\\(.*\", RemoveMongoCommand.class);\n\t\tcommandMap.put(\"^db\\\\.[^\\\\(]+\\\\.group\\\\(.*\", GroupMongoCommand.class);\n\t\tcommandMap.put(\"^db\\\\.[^\\\\(]+\\\\.aggregate\\\\(.*\", AggregateMongoCommand.class);\n\t\tcommandMap.put(\"^db\\\\.[^\\\\(]+\\\\.mapReduce\\\\(.*\", MapReduceMongoCommand.class);\n\t\tcommandMap.put(\"^use\\\\s+.*\", UseMongoCommand.class);\n\t\tcommandMap.put(\"^show dbs\", ShowDbsMongoCommand.class);\n\t\tcommandMap.put(\"^show collections\", ShowCollectionsMongoCommand.class);\n\t\tcommandMap.put(\"^db\\\\.serverStatus\\\\(.*\", DBserverStatsMongoCommand.class);\n\t\tcommandMap.put(\"^db\\\\.getStats\\\\(.*\", DBStatsMongoCommand.class);\n\n\t\tsetName( \"MongoFactory\" );\n\t\tstart();\n\t}\n\t\n\tpublic void registerListener(MongoCommandListener listener){\n\t\tif ( listener instanceof MDocumentView )\n\t\t\tdocumentViewListeners.add( (MDocumentView)listener );\n\t\telse\n\t\t\tmongoListeners.add(listener);\n\t}\n\t\n\tpublic void deregisterListener(MongoCommandListener listener){\n\t\tif ( listener instanceof MDocumentView )\n\t\t\tdocumentViewListeners.remove( (MDocumentView)listener );\n\t\telse\n\t\t\tmongoListeners.remove(listener);\n\t}\n\t\t\n\tpublic void removeMongo(String sName){\n\t\tMongoClient\tmclient\t= mongoMap.remove(sName);\n\t\tif ( mclient != null )\n\t\t\tmclient.close();\n\t}\n\t\n\t\n\tpublic MongoClient getMongo(String sName) {\n\t\tactiveServer = sName;\n\t\t\n\t\tif ( mongoMap.containsKey(sName) )\n\t\t\treturn mongoMap.get(sName);\n\t\telse{\n\t\t\ttry {\n\t\t\t\tMongoClient mc\t= Activator.getDefault().getMongoClient(sName);\n\t\t\t\tmongoMap.put( sName, mc );\n\t\t\t\treturn mc;\n\t\t\t} catch (UnknownHostException e) {\n\t\t\t\tEventWorkBenchManager.getInst().onEvent( org.aw20.mongoworkbench.Event.EXCEPTION, e);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t}\n\t\n\tpublic void destroy(){\n\t\tbRun = false;\n\t}\n\t\n\tpublic String getActiveServer(){\n\t\treturn activeServer;\n\t}\n\t\n\tpublic String getActiveDB(){\n\t\treturn activeDB;\n\t}\n\t\n\tpublic void setActiveDB(String db){\n\t\tthis.activeDB = db;\n\t}\n\t\n\tpublic MongoCommand\tcreateCommand( String cmd ) throws Exception {\n\t\t\n\t\t// remove line breaks\n\t\tcmd = cmd.replaceAll(\"(\\\\r|\\\\n)\", \"\");\n\t\tcmd = cmd.replaceAll(\"\\\\t+\", \" \");\n\t\tcmd\t= cmd.trim();\n\n\t\tIterator p = commandMap.keySet().iterator();\n\t\twhile (p.hasNext()) {\n\t\t\tString patternStr = (String) p.next();\n\t\t\tif (cmd.matches(patternStr)) {\n\t\t\t\tClass clazz = (Class) commandMap.get(patternStr);\n\t\t\t\ttry {\n\t\t\t\t\tMongoCommand mcmd = (MongoCommand)clazz.newInstance();\n\t\t\t\t\tmcmd.setConnection(activeServer, activeDB);\n\t\t\t\t\tmcmd.setCommandStr( cmd );\n\t\t\t\t\tmcmd.parseCommandStr();\n\t\t\t\t\treturn mcmd;\n\t\t\t\t} catch (Exception e) {\n\t\t\t\t\tEventWorkBenchManager.getInst().onEvent( Event.EXCEPTION, e);\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\t// Determine if this is a command\n\t\tif ( cmd.startsWith(\"db.\") || cmd.startsWith(\"sh.\") || cmd.startsWith(\"rs.\") ){\n\t\t\tMongoCommand mcmd = new PassThruMongoCommand();\n\t\t\tmcmd.setConnection(activeServer, activeDB);\n\t\t\tmcmd.setCommandStr(cmd);\n\t\t\treturn mcmd;\n\t\t}\n\t\t\t\n\t\t\n\t\treturn null;\n\t}\n\t\n\tpublic void submitExecution( MongoCommand mcmd ){\n\t\tsynchronized(commandQueue){\n\t\t\tcommandQueue.add(mcmd);\n\t\t\tcommandQueue.notify();\n\t\t}\n\t}\n\n\tpublic MongoClient getMongoActive() {\n\t\treturn mongoMap.get(activeServer);\n\t}\n\n\tpublic DB getMongoActiveDB() {\n\t\treturn mongoMap.get(activeServer).getDB(activeDB);\n\t}\n\t\n\tpublic void run(){\n\t\tMongoCommand\tcmd;\n\t\t\n\t\twhile (bRun){\n\t\t\t\n\t\t\twhile ( commandQueue.size() == 0 ){\n\t\t\t\tsynchronized (commandQueue) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tcommandQueue.wait();\n\t\t\t\t\t} catch (InterruptedException e) {\n\t\t\t\t\t\tbRun = false;\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tsynchronized(commandQueue){\n\t\t\t\tcmd\t= commandQueue.remove(0);\n\t\t\t\tif ( cmd == null )\n\t\t\t\t\tcontinue;\n\t\t\t}\n\n\n\t\t\t// Now let the listeners know we are about to start\n\t\t\talertDocumentViewsOnMongoCommandStart(cmd);\n\t\t\talertListenersOnMongoCommandStart(cmd);\n\t\t\t\n\t\t\t// Execute the command\n\t\t\tlong startTime\t= System.currentTimeMillis();\n\t\t\ttry{\n\t\t\t\tcmd.execute();\n\t\t\t}catch(Throwable t){\n\t\t\t\tt.printStackTrace();\n\t\t\t}finally{\n\t\t\t\tcmd.setExecTime( System.currentTimeMillis() - startTime );\n\t\t\t\tcmd.hasRun();\n\t\t\t}\n\n\t\t\tif ( cmd.getCollection() != null )\n\t\t\t\tactiveCollection = cmd.getCollection();\n\t\t\t\n\n\t\t\t// Now let the listeners know we have finished\n\t\t\talertDocumentViewsOnMongoCommandFinished(cmd);\n\t\t\talertListenersOnMongoCommandFinished(cmd);\n\t\t}\n\t}\n\n\tpublic void setActiveServerDB(String name, String db) {\n\t\tactiveServer = name;\n\t\tactiveDB = db;\n\t}\n\n\tpublic String getActiveCollection() {\n\t\treturn activeCollection;\n\t}\n\t\n\t\n\tprivate void alertListenersOnMongoCommandStart( MongoCommand cmd ){\n\t\tIterator<MongoCommandListener>\tit\t= mongoListeners.iterator();\n\t\twhile ( it.hasNext() ){\n\t\t\ttry{\n\t\t\t\tit.next().onMongoCommandStart(cmd);\n\t\t\t}catch(Exception e){\n\t\t\t\tEventWorkBenchManager.getInst().onEvent( Event.EXCEPTION, e);\n\t\t\t}\n\t\t}\n\t}\n\t\n\tprivate void alertListenersOnMongoCommandFinished( MongoCommand cmd ){\n\t\tIterator<MongoCommandListener>\tit\t= mongoListeners.iterator();\n\t\twhile ( it.hasNext() ){\n\t\t\ttry{\n\t\t\t\tit.next().onMongoCommandFinished(cmd);\n\t\t\t}catch(Exception e){\n\t\t\t\tEventWorkBenchManager.getInst().onEvent( Event.EXCEPTION, e);\n\t\t\t}\n\t\t}\n\t}\n\t\n\t\n\tprivate void alertDocumentViewsOnMongoCommandStart( MongoCommand cmd ){}\n\t\n\tprivate void alertDocumentViewsOnMongoCommandFinished( MongoCommand cmd ){\n\t\tif ( !cmd.hasQueryData() )\n\t\t\treturn;\n\t\t\n\t\tfindDocumentView(cmd);\n\t}\n\t\n\tprivate void findDocumentView(final MongoCommand cmd){\n\t\tIterator<MDocumentView>\tit\t= documentViewListeners.iterator();\n\t\t\n\t\tfinal String id\t= ( cmd.getDB() != null ? cmd.getDB() : \"DB\" ) + \"-\" + ( cmd.getCollection() != null ? cmd.getCollection() : \"Output\" );\n\t\t\n\t\twhile ( it.hasNext() ){\n\t\t\tMDocumentView view = it.next();\n\t\t\t\n\t\t\tif ( view.getViewTitle().equals(id) ){\n\t\t\t\tfinal MDocumentView finalView = view;\n\t\t\t\tActivator.getDefault().getShell().getDisplay().asyncExec(new Runnable() {\n\t\t\t\t\tpublic void run() {\n\t\t\t\t\t\tActivator.getDefault().showView(\"org.aw20.mongoworkbench.eclipse.view.MDocumentView\", id );\n\t\t\t\t\t\t((MDocumentView)finalView).onMongoCommandFinished(cmd);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\t\n\t\t\n\t\t/* Need to create a new one */\n\t\tActivator.getDefault().getShell().getDisplay().asyncExec(new Runnable() {\n\t\t\tpublic void run() {\n\t\t\t\tObject view = Activator.getDefault().showView(\"org.aw20.mongoworkbench.eclipse.view.MDocumentView\", id );\n\t\t\t\tif ( view != null && view instanceof MDocumentView )\n\t\t\t\t\t((MDocumentView)view).onMongoCommandFinished(cmd);\n\t\t\t}\n\t\t});\n\t\t\n\t}\n}",
"public class MapReduceMongoCommand extends FindMongoCommand {\n\n\tprotected BasicDBList dbListResult = null;\n\t\n\t@SuppressWarnings(\"deprecation\")\n\t@Override\n\tpublic void execute() throws Exception {\n\t\tMongoClient mdb = MongoFactory.getInst().getMongo( sName );\n\t\t\n\t\tif ( mdb == null )\n\t\t\tthrow new Exception(\"no server selected\");\n\t\t\n\t\tif ( sDb == null )\n\t\t\tthrow new Exception(\"no database selected\");\n\t\t\n\t\tMongoFactory.getInst().setActiveDB(sDb);\n\t\t\n\t\tDB db\t= mdb.getDB(sDb);\n\t\tBasicDBObject cmdMap\t= parseMongoCommandString(db, cmd);\n\t\t\n\t\tif ( !cmdMap.containsField(\"mapreduceArgs\") )\n\t\t\tthrow new Exception(\"no mapReduce document\");\n\n\t\tDBCollection\tcollection\t= db.getCollection(sColl);\n\t\t\n\t\t// Build the Map\n\t\tBasicDBObject\toptions\t= (BasicDBObject)((BasicDBList)cmdMap.get(\"mapreduceArgs\")).get(2);\n\t\t\n\t\tString outputCollection = null;\n\t\tString outputDB = null;\n\t\tMapReduceCommand.OutputType\toutputType = MapReduceCommand.OutputType.INLINE;\n\t\t\n\t\tif ( options.get(\"out\") instanceof String ){\n\t\t\toutputCollection \t= (String)options.get(\"out\");\n\t\t\toutputType\t\t\t\t= MapReduceCommand.OutputType.REPLACE;\n\t\t}else if ( options.get(\"out\") instanceof BasicDBObject ) {\n\t\t\tBasicDBObject out\t= (BasicDBObject)options.get(\"out\");\n\t\t\t\n\t\t\tif ( out.containsField(\"inline\") ){\n\t\t\t\toutputCollection = null;\n\t\t\t} else if ( out.containsField(\"replace\") ){\n\t\t\t\toutputCollection\t= (String)out.get(\"replace\");\n\t\t\t\toutputType\t= MapReduceCommand.OutputType.REPLACE;\n\t\t\t} else if ( out.containsField(\"merge\") ){\n\t\t\t\toutputCollection\t= (String)out.get(\"merge\");\n\t\t\t\toutputType\t= MapReduceCommand.OutputType.MERGE;\n\t\t\t} else if ( out.containsField(\"reduce\") ){\n\t\t\t\toutputCollection\t= (String)out.get(\"reduce\");\n\t\t\t\toutputType\t= MapReduceCommand.OutputType.REDUCE;\n\t\t\t}\n\t\t\t\n\t\t\tif ( out.containsField(\"db\") )\n\t\t\t\toutputDB\t= (String)out.get(\"db\");\n\t\t}\n\t\t\n\t\tMapReduceCommand\tmrc\t= new MapReduceCommand(\n\t\t\tcollection,\n\t\t\t((Code)((BasicDBList)cmdMap.get(\"mapreduceArgs\")).get(0)).getCode(),\n\t\t\t((Code)((BasicDBList)cmdMap.get(\"mapreduceArgs\")).get(1)).getCode(),\n\t\t\toutputCollection,\n\t\t\toutputType,\n\t\t\t(BasicDBObject)options.get(\"query\")\n\t\t\t\t);\n\t\t\n\t\tif ( outputDB != null )\n\t\t\tmrc.setOutputDB(outputDB);\n\t\t\n\t\tif ( options.containsField(\"sort\") && options.get(\"sort\") instanceof DBObject )\n\t\t\tmrc.setSort( (DBObject)options.get(\"sort\") );\n\t\t\n\t\tif ( options.containsField(\"scope\") && options.get(\"scope\") instanceof DBObject )\n\t\t\tmrc.setScope( ((DBObject)options.get(\"scope\")).toMap() );\n\t\t\n\t\tif ( options.containsField(\"finalize\") && options.get(\"scope\") instanceof Code )\n\t\t\tmrc.setFinalize( ((Code)options.get(\"scope\")).getCode() );\n\t\t\n\t\tif ( options.containsField(\"limit\") )\n\t\t\tmrc.setLimit( StringUtil.toInteger( options.get(\"limit\"), -1) );\n\t\n\t\tmrc.addExtraOption(\"jsMode\", StringUtil.toBoolean( options.get(\"jsMode\"), false) );\n\t\tmrc.setVerbose( StringUtil.toBoolean( options.get(\"verbose\"), false) );\n\t\t\n\t\t// Run the actual mapreduce function\n\t\tMapReduceOutput\tmro\t= collection.mapReduce(mrc);\n\t\t\n\n\t\t// Pull the inline results\n\t\tif ( mro.getOutputCollection() == null ){\n\t\t\tdbListResult\t= new BasicDBList();\n\t\t\tIterable<DBObject> it = mro.results();\n\t\t\tfor ( DBObject dbo : it ){\n\t\t\t\tdbListResult.add(dbo);\n\t\t\t}\n\t\t}\n\t\t\n\t\tBasicDBObject dbo = mro.getRaw();\n\t\tStringBuilder sb = new StringBuilder();\n\n\t\tif ( dbo.containsField(\"timeMillis\") )\n\t\t\tsb.append(\"Time=\").append( dbo.get(\"timeMillis\") ).append(\"ms; \");\n\t\t\n\t\tif ( dbo.containsField(\"counts\") ){\n\t\t\tBasicDBObject counts = (BasicDBObject)dbo.get(\"counts\");\n\t\t\tsb.append( \"Counts: input=\" + counts.get(\"input\") );\n\t\t\tsb.append( \"; emit=\" + counts.get(\"emit\") );\n\t\t\tsb.append( \"; reduce=\" + counts.get(\"reduce\") );\n\t\t\tsb.append( \"; output=\" + counts.get(\"output\") );\n\t\t}\n\n\t\tsetMessage( sb.toString() );\n\t}\n\t\n\tpublic BasicDBList getResults(){\n\t\treturn dbListResult;\n\t}\n\t\n\t@Override\n\tpublic void parseCommandStr() throws Exception {\n\t\tsColl = getCollNameFromAction(cmd, \"mapReduce\");\n\t\t\n\t\tif ( sColl == null || sColl.length() == 0 )\n\t\t\tthrow new Exception(\"failed to determine collection from command\");\n\t}\n}",
"public abstract class MongoCommand extends Object {\n\n\tpublic static String KEY_NAME = \"_name\";\n\n\tpublic static String KEY_COUNT = \"_count\";\n\n\tprotected String sName = null, sDb = null, sColl = null, rteMessage = \"\", cmd = null;\n\n\tprotected Exception lastException = null;\n\n\tprotected boolean hasRun = false;\n\n\tprivate long execTime = -1;\n\n\t/**\n\t * Sets the connection details to which this command pertains to\n\t * \n\t * @param mongoName\n\t * @param database\n\t * @param collection\n\t */\n\tpublic MongoCommand setConnection(String mongoName, String database, String collection) {\n\t\tthis.sName = mongoName;\n\t\tthis.sDb = database;\n\t\tthis.sColl = collection;\n\t\treturn this;\n\t}\n\n\tpublic MongoCommand setConnection(String mongoName, String database) {\n\t\tthis.sName = mongoName;\n\t\tthis.sDb = database;\n\t\treturn this;\n\t}\n\n\tpublic MongoCommand setConnection(String mongoName) {\n\t\tthis.sName = mongoName;\n\t\treturn this;\n\t}\n\n\tpublic MongoCommand setConnection(MongoCommand mcmd) {\n\t\tthis.sName = mcmd.sName;\n\t\tthis.sDb = mcmd.sDb;\n\t\tthis.sColl = mcmd.sColl;\n\t\treturn this;\n\t}\n\n\tpublic boolean isSuccess() {\n\t\treturn lastException == null;\n\t}\n\t\n\tpublic boolean hasQueryData(){\n\t\treturn false;\n\t}\n\n\tpublic boolean hasRun() {\n\t\treturn hasRun;\n\t}\n\n\tpublic void markAsRun() {\n\t\thasRun = true;\n\t}\n\n\tpublic Exception getException() {\n\t\treturn lastException;\n\t}\n\n\tpublic void setException(Exception e) {\n\t\tlastException = e;\n\t}\n\n\tpublic String getExceptionMessage() {\n\t\tif (lastException == null)\n\t\t\treturn \"\";\n\n\t\tif (lastException instanceof MongoException) {\n\t\t\tString e = lastException.getMessage();\n\t\t\tif (e.startsWith(\"command failed [$eval]: {\") && e.endsWith(\"}\")) {\n\t\t\t\ttry {\n\t\t\t\t\tMap m = (Map) JSON.parse(e.substring(e.indexOf(\"{\")));\n\t\t\t\t\treturn (String) m.get(\"errmsg\");\n\t\t\t\t} catch (Exception ee) {\n\t\t\t\t\treturn lastException.getMessage();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn lastException.getMessage();\n\t}\n\n\tpublic long getExecTime() {\n\t\treturn execTime;\n\t}\n\n\tprotected void setMessage(String string) {\n\t\trteMessage = string;\n\t}\n\n\tpublic String getMessage() {\n\t\treturn rteMessage;\n\t}\n\n\tpublic String getName() {\n\t\treturn sName;\n\t}\n\n\tpublic String getDB() {\n\t\treturn sDb;\n\t}\n\n\tpublic String getCollection() {\n\t\treturn sColl;\n\t}\n\n\t/**\n\t * Override this function to provide the body of the command\n\t */\n\tpublic abstract void execute() throws Exception;\n\n\tpublic String getCommandString() {\n\t\treturn this.cmd;\n\t}\n\n\tpublic void setExecTime(long l) {\n\t\texecTime = l;\n\t}\n\n\tpublic void setCommandStr(String cmd) {\n\t\tthis.cmd = cmd;\n\t}\n\n\tpublic void parseCommandStr() throws Exception {}\n\n\tpublic String getMatchIgnoreCase(String patternStr, String target) {\n\t\tPattern pattern = Pattern.compile(patternStr, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);\n\t\tMatcher matcher = pattern.matcher(target);\n\t\tif (matcher.find()) {\n\t\t\tif (matcher.groupCount() > 0) {\n\t\t\t\treturn matcher.group(1);\n\t\t\t} else {\n\t\t\t\treturn target.substring(matcher.start(), matcher.end());\n\t\t\t}\n\t\t} else {\n\t\t\treturn \"\";\n\t\t}\n\t}\n\t\n\t\n\tpublic BasicDBObject parse() throws Exception{\n\t\tMongoClient mdb = MongoFactory.getInst().getMongo( sName );\n\t\t\n\t\tif ( mdb == null )\n\t\t\tthrow new Exception(\"no server selected\");\n\t\t\n\t\tif ( sDb == null )\n\t\t\tthrow new Exception(\"no database selected\");\n\t\t\n\t\tMongoFactory.getInst().setActiveDB(sDb);\n\t\t\n\t\tDB db\t= mdb.getDB(sDb);\n\t\treturn parseMongoCommandString(db, cmd);\n\t}\n\t\n\t\n\tprotected BasicDBObject parseMongoCommandString(DB db, String cmd) throws Exception {\n\t\t\n\t\tString newCmd = cmd.replaceFirst(\"db.\" + sColl, \"a\");\n\t\tString jsStr = StreamUtil.readToString( this.getClass().getResourceAsStream(\"parseCommand.txt\") ); \n\t\tjsStr = StringUtil.tokenReplace(jsStr, new String[]{\"//_QUERY_\"}, new String[]{newCmd} );\n\n\t\tBasicDBObject cmdMap = (BasicDBObject)db.eval(jsStr, (Object[])null);\n\t\t\n\t\t/*\n\t\t * Using JavaScript Engine\n\t\tContext cx = Context.enter();\n\t\tcx.setLanguageVersion(Context.VERSION_1_7);\n\t\tScriptable scope = cx.initStandardObjects();\n\t\tObject returnObj = cx.evaluateString(scope, jsStr, \"CustomJS\", 1, null);\n\t\t\n\t\tMap cmdMap = (Map) jsConvert2cfData( (IdScriptableObject)returnObj );\n\t\t*/\n\t\t\n\t\t// Remove the helper methods\n\t\tcmdMap.remove(\"find\");\n\t\tcmdMap.remove(\"findOne\");\n\t\tcmdMap.remove(\"group\");\n\t\tcmdMap.remove(\"aggregate\");\n\t\tcmdMap.remove(\"save\");\n\t\tcmdMap.remove(\"mapReduce\");\n\t\tcmdMap.remove(\"update\");\n\t\tcmdMap.remove(\"remove\");\n\t\tcmdMap.remove(\"limit\");\n\t\tcmdMap.remove(\"skip\");\n\t\tcmdMap.remove(\"sort\");\n\t\t\n\t\treturn new BasicDBObject( cmdMap );\n\t}\n\n\t\n\tpublic static Object jsConvert2cfData(IdScriptableObject obj) throws Exception {\n\n\t\tif (obj instanceof NativeObject) {\n\t\t\tMap struct = new HashMap();\n\n\t\t\tNativeObject nobj = (NativeObject) obj;\n\t\t\tObject[] elements = nobj.getAllIds();\n\n\t\t\tObject cfdata;\n\t\t\t\n\t\t\tfor (int x = 0; x < elements.length; x++) {\n\t\t\t\tObject jsObj = nobj.get(elements[x]);\n\n\t\t\t\tif (jsObj == null)\n\t\t\t\t\tcfdata = null;\n\t\t\t\telse if (jsObj instanceof NativeObject || jsObj instanceof NativeArray)\n\t\t\t\t\tcfdata = jsConvert2cfData((IdScriptableObject) jsObj);\n\t\t\t\telse\n\t\t\t\t\tcfdata = jsObj;\n\n\t\t\t\tstruct.put((String) elements[x], cfdata);\n\t\t\t}\n\n\t\t\treturn struct;\n\t\t} else if (obj instanceof NativeArray) {\n\t\t\tList array = new ArrayList();\n\n\t\t\tNativeArray nobj = (NativeArray) obj;\n\t\t\tObject cfdata;\n\t\t\tint len = (int) nobj.getLength();\n\n\t\t\tfor (int x = 0; x < len; x++) {\n\t\t\t\tObject jsObj = nobj.get(x);\n\n\t\t\t\tif (jsObj == null)\n\t\t\t\t\tcfdata = null;\n\t\t\t\telse if (jsObj instanceof NativeObject || jsObj instanceof NativeArray)\n\t\t\t\t\tcfdata = jsConvert2cfData((IdScriptableObject) jsObj);\n\t\t\t\telse\n\t\t\t\t\tcfdata = jsObj;\n\t\t\t\t\n\t\t\t\tarray.add(cfdata);\n\t\t\t}\n\n\t\t\treturn array;\n\t\t} else {\n\t\t\treturn null;\n\t\t}\n\t}\n\n\t\n\tprotected BasicDBObject\tfixNumbers( BasicDBObject dbo ){\n\t\tIterator<String> it\t= dbo.keySet().iterator();\n\t\twhile (it.hasNext()){\n\t\t\tString field\t= it.next();\n\t\t\tObject o\t= dbo.get(field);\n\t\t\tif ( o instanceof Double ){\n\t\t\t\tdbo.put(field, NumberUtil.fixDouble( (Double)o) );\n\t\t\t}else if ( o instanceof BasicDBObject ){\n\t\t\t\tdbo.put(field, fixNumbers((BasicDBObject)o) );\n\t\t\t}else if ( o instanceof BasicDBList ){\n\t\t\t\tdbo.put(field, fixNumbers((BasicDBList)o) );\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn dbo;\n\t}\n\t\n\t\n\tprotected BasicDBList\tfixNumbers( BasicDBList dbo ){\n\t\tfor ( int x=0; x < dbo.size(); x++ ){\n\t\t\tObject o =\tdbo.get(x);\n\t\t\t\n\t\t\tif ( o instanceof Double ){\n\t\t\t\tdbo.set(x, NumberUtil.fixDouble( (Double)o) );\n\t\t\t}else if ( o instanceof BasicDBObject ){\n\t\t\t\tdbo.set(x, fixNumbers((BasicDBObject)o) );\n\t\t\t}else if ( o instanceof BasicDBList ){\n\t\t\t\tdbo.set(x, fixNumbers((BasicDBList)o) );\n\t\t\t}\n\t\t}\n\n\t\treturn dbo;\n\t}\n}",
"public interface WizardParentI {\n\n\t/**\n\t * Returns the active DB\n\t * @return\n\t */\n\tpublic String getActiveDB();\n\t\n\t/**\n\t * Returns the active collection\n\t * @return\n\t */\n\tpublic String getActiveCollection();\n\t\n}",
"public class JSONFormatter extends Object {\n\n\tprivate StringBuilder sb;\n\tprivate String tab;\n\tprivate String nl = System.getProperty(\"line.separator\");\n\n\tpublic static String format( Object object ){\n\t\treturn new JSONFormatter().parseObject(object);\n\t}\n\t\n\tpublic JSONFormatter() {\n\t\tthis(\" \");\n\t}\n\t\n\tpublic JSONFormatter(String _tab) {\n\t\tthis.tab = _tab;\n\t}\n\t\n\t/**\n\t * Treats a List, Map, String, Integer, Long, Float, Double, or Boolean as a JSON Object and formats it in JSON format.\n\t * \n\t * Unrecognized Object Types will be marked \"binary-object\"\n\t * \n\t * @param _o A valid object to be parsed may be a Boolean, Integer, Float, String, or Map or List containing any of the other object\n\t * @return Formatted Json\n\t */\n\tpublic String parseObject(Object _o) {\n\t\tsb = new StringBuilder(256);\n\t\tparseValue(_o);\n\t\treturn sb.toString();\n\t}\n\t\n\tprivate void parseValue(Object _o) {\n\t\tparseValue(_o, 0);\n\t}\n\t\n\tprivate void parseValue(Object _o, int _depth) {\n\t\t\n\t\tif ( _o instanceof String || _o instanceof Character ){\n\t\t\tsb.append(\"\\\"\" + _o.toString() + \"\\\"\");\n\t\t} else if (_o instanceof Map) {\n\t\t\tsb.append(\"{\");\n\t\t\tparseObject((Map<String, Object>)_o, _depth + 1);\n\t\t\tsb.append(\"}\");\n\t\t} else if (_o instanceof List) {\n\t\t\tsb.append(\"[\");\n\t\t\tparseArray((List)_o, _depth + 1);\n\t\t\tsb.append(\"]\");\n\t\t} else if (_o instanceof Float || _o instanceof Double) {\n\t\t\tString d = String.valueOf(_o);\n\t\t\tif ( d.endsWith(\".0\") )\n\t\t\t\tsb.append(d.substring(0,d.length()-2));\n\t\t\telse\n\t\t\t\tsb.append(d);\n\t\t} else if (_o instanceof Integer || _o instanceof Long || _o instanceof Boolean) {\n\t\t\tsb.append(_o.toString());\n\t\t} else if (_o == null) {\n\t\t\tsb.append(\"null\");\n\t\t} else if ( _o instanceof Date ){\n\t\t\tsb.append( \"ISODate(\\\"\" );\n\t\t\tsb.append( DateUtil.getDateString( (Date)_o, \"yyyy-MM-dd'T'HH:mm:ss.SSS\") );\n\t\t\tsb.append( \"Z\\\")\");\n\t\t} else if ( _o instanceof ObjectId ){\n\t\t\tsb.append( \"ObjectId(\\\"\" );\n\t\t\tsb.append( (ObjectId)_o );\n\t\t\tsb.append( \"\\\")\");\n\t\t} else if ( _o instanceof Pattern ){\n\t\t\tsb.append( \"/\" );\n\t\t\tsb.append( (Pattern)_o );\n\t\t\tsb.append( \"/\");\n\t\t} else if ( _o instanceof byte[] ){\t\n\t\t\tsb.append( \"BinData(0,\\\"\" );\n\t\t\tsb.append( Base64.encodeBytes((byte[])_o) );\n\t\t\tsb.append( \"\\\")\");\n\t\t} else {\n\t\t\tsb.append( _o.getClass().getName() );\n\t\t}\n\t}\n\t\n\tprivate void parseObject(Map<String, Object> _map, int _depth) {\n\t\tString margin = getMargin(_depth);\n\t\t\n\t\tString[] keyArr = (String[])_map.keySet().toArray(new String[0]);\n\t\tArrays.sort(keyArr);\n\t\tfor ( String key : keyArr ){\n\t\t\tObject value = _map.get(key);\n\t\t\t\n\t\t\t// Write out this key/value pair\n\t\t\tsb.append(nl)\n\t\t\t\t.append(margin)\n\t\t\t\t.append(\"\\\"\")\n\t\t\t\t.append( key )\n\t\t\t\t.append(\"\\\" : \");\n\t\t\tparseValue(value, _depth);\n\t\t\tsb.append(\",\");\n\t\t}\n\t\t\n\t\t// Remove final comma\n\t\tif ( sb.charAt(sb.length()-1) == ','){\n\t\t\tsb.delete(sb.length() - 1, sb.length());\n\t\t\tsb.append(nl).append(getMargin(_depth - 1));\n\t\t} else {\n\t\t\tsb.append(\" \");\n\t\t}\n\t}\n\t\n\tprivate void parseArray(List _list, int _depth) {\n\t\t\n\t\t// Parse through an array\n\t\tboolean empty = true;\n\t\tfor( Object o : _list) {\n\t\t\tempty = false;\n\t\t\tparseValue(o, _depth);\n\t\t\tsb.append(\", \");\n\t\t}\n\n\t\t// Remove final comma\n\t\tif (!empty)\n\t\t\tsb.delete(sb.length() - 2, sb.length());\n\t\telse\n\t\t\tsb.append(\" \");\n\t}\n\t\n\t// Gets the margin for the specified _depth level\n\tprivate String getMargin(int _depth) {\n\t\tStringBuilder margin = new StringBuilder(32);\n\t\tfor (int i = 0; i < _depth; i++)\n\t\t\tmargin.append(this.tab);\n\t\t\n\t\treturn margin.toString();\n\t}\n}",
"public class MSwtUtil extends Object {\n\n\tpublic static Text createText( Composite comp ){\n\t\tText txt = new Text(comp, SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.CANCEL | SWT.MULTI);\n\t\ttxt.setFont(SWTResourceManager.getFont(\"Courier New\", 9, SWT.NORMAL));\n\t\ttxt.setTabs(2);\n\t\treturn txt;\n\t}\n\t\n\tpublic static void addListenerToMenuItems(Menu menu, Listener listener) {\n\t\tMenuItem[] itemArray = menu.getItems();\n\t\tfor (int i = 0; i < itemArray.length; ++i) {\n\t\t\titemArray[i].addListener(SWT.Selection, listener);\n\t\t}\n\t}\n\n\tpublic static void copyToClipboard(String s) {\n\t\tDisplay display = Display.findDisplay(Thread.currentThread());\n\t\tClipboard clipboard = new Clipboard(display);\n\t\tTextTransfer textTransfer = TextTransfer.getInstance();\n\t\tclipboard.setContents(new Object[] { s }, new Transfer[] { textTransfer });\n\t\tclipboard.dispose();\n\t}\n\n\tpublic static Image getImage(Device device, String imageFileName) {\n\t\tInputStream in = null;\n\t\ttry {\n\t\t\tin = StreamUtil.getResourceStream(\"org/aw20/mongoworkbench/eclipse/resources/\" + imageFileName);\n\t\t\tImageData imageData = new ImageData(in);\n\t\t\treturn new Image(device, imageData);\n\t\t} catch (Exception e) {\n\t\t\treturn null;\n\t\t} finally {\n\t\t\tStreamUtil.closeStream(in);\n\t\t}\n\t}\n\t\n}",
"public class StringUtil extends Object {\n\n\t/**\n\t * Takes a string filled with tokens and replaces them with their corresponding value\n\t * \n\t * @param _template\n\t * @param _keys\n\t * @param _values\n\t * @return\n\t */\n\tpublic static String tokenReplace(String _template, String[] _tokens, String[] _values) {\n\t\tif ((_values != null && _tokens.length != _values.length) || _template == null)\n\t\t\treturn _template;\n\n\t\tint c1 = -1, jump = 0;\n\t\tfor (int x = 0; x < _tokens.length; x++) {\n\n\t\t\tc1 = _template.indexOf(_tokens[x]);\n\t\t\twhile (c1 != -1) {\n\t\t\t\tif (_values != null && _values[x] != null) {\n\t\t\t\t\t_template = _template.substring(0, c1) + _values[x] + _template.substring(c1 + _tokens[x].length());\n\t\t\t\t\tjump = _values[x].length();\n\t\t\t\t} else {\n\t\t\t\t\t_template = _template.substring(0, c1) + _template.substring(c1 + _tokens[x].length());\n\t\t\t\t\tjump = 0;\n\t\t\t\t}\n\n\t\t\t\tc1 = _template.indexOf(_tokens[x], c1 + jump);\n\t\t\t}\n\t\t}\n\n\t\treturn _template;\n\t}\n\t\n\tpublic static double toDouble(Object _value, double _default) {\n\t\tif (_value == null)\n\t\t\treturn _default;\n\t\telse if (_value instanceof Integer)\n\t\t\treturn ((Integer) _value).doubleValue();\n\t\telse if (_value instanceof Long)\n\t\t\treturn ((Long) _value).doubleValue();\n\t\telse if (_value instanceof Double)\n\t\t\treturn (Double) _value;\n\t\telse if (_value instanceof Float)\n\t\t\treturn ((Float) _value).doubleValue();\n\t\telse\n\t\t\treturn toDouble(_value.toString(), _default);\n\t}\n\n\tpublic static double toDouble(String _value, double _default) {\n\t\tif (_value == null || _value.length() == 0)\n\t\t\treturn _default;\n\t\telse {\n\t\t\ttry {\n\t\t\t\treturn Double.parseDouble(_value);\n\t\t\t} catch (Exception e) {\n\t\t\t\treturn _default;\n\t\t\t}\n\t\t}\n\t}\n\n\n\t/**\n\t * Converts a string to an integer, and if unable to do so, returns the default value\n\t * \n\t * @param _value\n\t * @param _default\n\t * @return\n\t */\n\tpublic static int toInteger(Object _value, int _default) {\n\t\tif (_value == null)\n\t\t\treturn _default;\n\t\telse if (_value instanceof Integer)\n\t\t\treturn (Integer) _value;\n\t\telse if (_value instanceof Long)\n\t\t\treturn ((Long) _value).intValue();\n\t\telse if (_value instanceof Double)\n\t\t\treturn ((Double) _value).intValue();\n\t\telse if (_value instanceof Float)\n\t\t\treturn ((Float) _value).intValue();\n\t\telse\n\t\t\treturn toInteger(_value.toString(), _default, 10);\n\t}\n\n\tpublic static int toInteger(String _value, int _default) {\n\t\treturn toInteger(_value, _default, 10);\n\t}\n\n\tpublic static int toInteger(String _value, int _default, int _radix) {\n\t\tif (_value == null || _value.length() == 0)\n\t\t\treturn _default;\n\t\telse {\n\t\t\ttry {\n\t\t\t\treturn Integer.parseInt(_value, _radix);\n\t\t\t} catch (Exception e) {\n\t\t\t\treturn _default;\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static boolean toBoolean(Object _value, boolean _default) {\n\t\tif ( _value == null )\n\t\t\treturn _default;\n\t\telse if ( _value instanceof Boolean )\n\t\t\treturn (Boolean)_value;\n\t\telse\n\t\t\treturn toBoolean( _value.toString(), _default );\n\t}\n\t\n\tpublic static boolean toBoolean(String _value, boolean _default) {\n\t\tif (_value == null || _value.length() == 0)\n\t\t\treturn _default;\n\n\t\tif (_value.equalsIgnoreCase(\"true\"))\n\t\t\treturn true;\n\t\telse if (_value.equalsIgnoreCase(\"false\"))\n\t\t\treturn false;\n\t\telse if (_value.equalsIgnoreCase(\"yes\"))\n\t\t\treturn true;\n\t\telse if (_value.equalsIgnoreCase(\"no\"))\n\t\t\treturn false;\n\t\telse if (StringUtil.toInteger(_value, 0) >= 1)\n\t\t\treturn true;\n\t\telse if (StringUtil.toInteger(_value, 0) == 0)\n\t\t\treturn false;\n\n\t\treturn _default;\n\t}\n\n\t/**\n\t * Converts a string to an integer, and if unable to do so, returns the default value\n\t * \n\t * @param _value\n\t * @param _default\n\t * @return\n\t */\n\tpublic static long toLong(Object _value, long _default) {\n\t\tif (_value == null)\n\t\t\treturn _default;\n\t\telse if (_value instanceof Integer)\n\t\t\treturn ((Integer) _value).longValue();\n\t\telse if (_value instanceof Long)\n\t\t\treturn ((Long) _value);\n\t\telse if (_value instanceof Double)\n\t\t\treturn ((Double) _value).longValue();\n\t\telse if (_value instanceof Float)\n\t\t\treturn ((Float) _value).longValue();\n\t\telse\n\t\t\treturn toLong(_value.toString(), _default, 10);\n\t}\n\n\tpublic static long toLong(String _value, long _default) {\n\t\treturn toLong(_value, _default, 10);\n\t}\n\n\tpublic static long toLong(String _value, long _default, int _radix) {\n\t\tif (_value == null || _value.length() == 0)\n\t\t\treturn _default;\n\t\telse {\n\t\t\ttry {\n\t\t\t\treturn Long.parseLong(_value, _radix);\n\t\t\t} catch (Exception e) {\n\t\t\t\treturn _default;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Tries to cast Object to String. If object is null, it will return null.\n\t * \n\t * @param _o\n\t * @return String value of _o\n\t */\n\tpublic static String toString(Object _o) {\n\t\treturn toString(_o, null);\n\t}\n\n\t/**\n\t * Tries to cast Object to String. If object is null, it will return the default value supplied..\n\t * \n\t * @param _o\n\t * @param _default\n\t * @return String value of _o\n\t */\n\tpublic static String toString(Object _o, String _default) {\n\t\tif (_o == null) {\n\t\t\treturn _default;\n\t\t} else {\n\t\t\ttry {\n\t\t\t\treturn (String) _o;\n\t\t\t} catch (ClassCastException e) {\n\t\t\t\treturn _default;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Removes the tags from a string\n\t */\n\tpublic static String removeTags(String _str) {\n\t\treturn _str.replaceAll(\"</?\\\\s*(\\\\w+)(\\\\s+[\\\\w-]+=([\\\\w\\\\.]+|\\\"[^\\\"]*\\\"|'[^']*'))*\\\\s*/?>\", \"\");\n\t}\n\n\t/**\n\t * Replaces all occurrences of specified characters in a String with the given String replacements\n\t * \n\t * @param _src\n\t * The String in which the chars should be replaced\n\t * @param _old\n\t * A list of characters to be replaced\n\t * @param _new\n\t * A list of Strings to use as replacements. The first String will be used when an occurence of the first char is found, and so on.\n\t * @throws IllegalArgumentException\n\t * if the size of the _old and _new arrays don't match\n\t * @return String with replacements inserted\n\t */\n\tpublic static String replaceChars(String _src, char[] _old, String[] _new) {\n\t\tif (_old.length != _new.length) {\n\t\t\tthrow new IllegalArgumentException(\"Method misuse: _old.length != _new.length\");\n\t\t}\n\t\tint strLen = _src.length();\n\t\tint charsLen = _old.length;\n\t\tStringBuffer buffer = new StringBuffer(_src);\n\t\tStringWriter writer = new StringWriter(strLen);\n\t\tchar nextChar;\n\t\tboolean foundCh;\n\n\t\tfor (int i = 0; i < strLen; i++) {\n\t\t\tnextChar = buffer.charAt(i);\n\t\t\tfoundCh = false;\n\n\t\t\tfor (int j = 0; j < charsLen; j++) {\n\t\t\t\tif (nextChar == _old[j]) {\n\t\t\t\t\twriter.write(_new[j]);\n\t\t\t\t\tfoundCh = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (!foundCh) {\n\t\t\t\twriter.write(nextChar);\n\t\t\t}\n\t\t}\n\n\t\treturn writer.toString();\n\t}\n\n\t/*\n\t * Makes an HTML friendly version of the string, escaping the necessary tags > < \" '\n\t * \n\t * @param str The string of HTML @return String with HTML\n\t */\n\tpublic static String escapeForHtml(String str) {\n\t\treturn replaceChars(str, new char[] { '&', '<', '>', '\\\"' }, new String[] { \"&\", \"<\", \">\", \""\" });\n\t}\n\n\t/**\n\t * Decodes back from HTML\n\t * \n\t * @param str\n\t * @return\n\t */\n\tpublic static String escapeFromHtml(String str) {\n\t\ttry {\n\t\t\treturn tokenReplace(str, new String[] { \"&\", \"<\", \">\", \""\" }, new String[] { \"&\", \"<\", \">\", \"\\\"\" });\n\t\t} catch (Exception e) {\n\t\t\treturn str;\n\t\t}\n\t}\n\n\t/*\n\t * Fully encodes a string for html, replacing characters outwith the a-zA-Z0-9 ranges with the html escaped version\n\t * \n\t * from http://www.owasp.org/index.php/How_to_perform_HTML_entity_encoding_in_Java\n\t * \n\t * @_html the html string to escape\n\t */\n\tpublic static StringBuilder escapeHtmlFull(String _html) {\n\t\tStringBuilder b = new StringBuilder(_html.length());\n\t\tfor (int i = 0; i < _html.length(); i++) {\n\t\t\tchar ch = _html.charAt(i);\n\t\t\tif (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch >= '0' && ch <= '9') {\n\t\t\t\t// safe\n\t\t\t\tb.append(ch);\n\t\t\t} else if (Character.isWhitespace(ch)) {\n\t\t\t\t// paranoid version: whitespaces are unsafe - escape\n\t\t\t\t// conversion of (int)ch is naive\n\t\t\t\tb.append(\"&#\").append((int) ch).append(\";\");\n\t\t\t} else if (Character.isISOControl(ch)) {\n\t\t\t\t// paranoid version:isISOControl which are not isWhitespace removed !\n\t\t\t\t// do nothing do not include in output !\n\t\t\t} else {\n\t\t\t\t// paranoid version\n\t\t\t\t// the rest is unsafe, including <127 control chars\n\t\t\t\tb.append(\"&#\" + (int) ch + \";\");\n\t\t\t}\n\t\t}\n\t\treturn b;\n\t}\n\n\t/*\n\t * Takes a string of items and returns them back as a List object\n\t * \n\t * @param str The string list @param delimitor the delimitor of the string list\n\t */\n\tpublic static List<String> listToList(String str, String delimitor) {\n\t\tif (str == null || str.length() == 0)\n\t\t\treturn new ArrayList<String>();\n\n\t\tString[] array = listToArray(str, delimitor);\n\t\tArrayList<String> list = new ArrayList<String>();\n\t\tfor (int x = 0; x < array.length; x++)\n\t\t\tlist.add(array[x]);\n\n\t\treturn list;\n\t}\n\n\tpublic static List<String> listToList(String str) {\n\t\treturn listToList(str, \",\");\n\t}\n\n\t/*\n\t * Takes a string of items and returns them back as an Array of Strings\n\t * \n\t * @param str The string list @param delimitor the delimitor of the string list\n\t */\n\tpublic static String[] listToArray(String str, String delimitor) {\n\t\tif (str == null || str.length() == 0)\n\t\t\treturn new String[0];\n\n\t\treturn str.split(delimitor);\n\t}\n\n\tpublic static String[] listToArray(String str) {\n\t\treturn listToArray(str, \",\");\n\t}\n\n\tpublic static String readToString(Reader _reader) throws IOException {\n\t\tStringBuffer sb = new StringBuffer();\n\t\tchar[] buff = new char[1024];\n\t\tint read;\n\t\twhile ((read = _reader.read(buff)) != -1)\n\t\t\tsb.append(buff, 0, read);\n\t\treturn sb.toString();\n\n\t}\n\n\t/**\n\t * Takes a string representation of an IP address, a.b.c.d, and converts into a long\n\t * \n\t * \"192.168.1.1\" --> 3232235777\n\t * \n\t * @param ipAddress\n\t * @return\n\t */\n\tpublic static long ipStringToLong(String ipAddress) {\n\t\tString[] addressParts = ipAddress.split(\"\\\\.\");\n\t\tif (addressParts.length != 4)\n\t\t\treturn -1;\n\n\t\tString hexVal = \"\";\n\t\tfor (int i = 0; i < 4; i++) {\n\t\t\tint intVal = StringUtil.toInteger(addressParts[i], 0);\n\t\t\tString hexTemp = Integer.toHexString(intVal);\n\t\t\tif (hexTemp.length() < 2) {\n\t\t\t\thexTemp = \"0\" + hexTemp;\n\t\t\t}\n\t\t\t// Builds a String of the hex values for each byte\n\t\t\thexVal = hexVal + hexTemp;\n\t\t}\n\t\treturn Long.parseLong(hexVal, 16);\n\t}\n}"
] | import java.io.IOException;
import org.aw20.mongoworkbench.Event;
import org.aw20.mongoworkbench.EventWorkBenchManager;
import org.aw20.mongoworkbench.MongoFactory;
import org.aw20.mongoworkbench.command.MapReduceMongoCommand;
import org.aw20.mongoworkbench.command.MongoCommand;
import org.aw20.mongoworkbench.eclipse.view.WizardParentI;
import org.aw20.util.JSONFormatter;
import org.aw20.util.MSwtUtil;
import org.aw20.util.StringUtil;
import org.bson.types.Code;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Text;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject; | sb.append( textMRMap.getText().trim() ).append(", ");
}
// Reduce attribute
if ( textMRReduce.getText().trim().equals(JS_REDUCE) ){
EventWorkBenchManager.getInst().onEvent(Event.EXCEPTION, new Exception("no reduce function supplied") );
return;
}else{
sb.append( textMRReduce.getText().trim() ).append(", {");
}
// Output attribute
String output = combo.getText();
if ( output == null || output.length() == 0 ){
EventWorkBenchManager.getInst().onEvent(Event.EXCEPTION, new Exception("no output type specified") );
return;
}
if ( output.equals("inline") ){
sb.append( " out : { inline : 1}," );
}else if (output.equals("replace") || output.equals("merge") || output.equals("reduce")){
sb.append( " out : {");
String collection = textMRCollection.getText().trim();
if ( collection.length() == 0 ){
EventWorkBenchManager.getInst().onEvent(Event.EXCEPTION, new Exception("no collection was specified") );
return;
}else
sb.append( output ).append( " : \"" ).append(collection).append("\",");
String db = textMRDatabase.getText().trim();
if ( db.length() == 0 ){
sb.append( "db : \"" ).append(db).append("\",");
}
sb.append( "sharded:" ).append( btnSharded.getSelection() ).append(",");
sb.append( "nonAtomic:" ).append( btnNonatomic.getSelection() );
sb.append("},");
}
// Query
if ( textMRQuery.getText().trim().length() != 0 ){
if ( !textMRQuery.getText().trim().startsWith("{") && !textMRQuery.getText().trim().endsWith("}") ){
EventWorkBenchManager.getInst().onEvent(Event.EXCEPTION, new Exception("query does not look like a document") );
return;
}
sb.append( " query : " ).append( textMRQuery.getText().trim() ).append(",");
}
// Sort
if ( textMRSort.getText().trim().length() != 0 ){
if ( !textMRSort.getText().trim().startsWith("{") && !textMRSort.getText().trim().endsWith("}") ){
EventWorkBenchManager.getInst().onEvent(Event.EXCEPTION, new Exception("sort does not look like a document") );
return;
}
sb.append( " sort : " ).append( textMRSort.getText().trim() ).append(",");
}
// limit
if ( textMRLimit.getText().trim().length() != 0 ){
if ( StringUtil.toInteger(textMRLimit.getText().trim(), -1) == -1 ){
EventWorkBenchManager.getInst().onEvent(Event.EXCEPTION, new Exception("limit is not a number") );
return;
}
sb.append( " limit : " ).append( textMRLimit.getText().trim() ).append(",");
}
// finalize
if ( !textMRFinalize.getText().trim().equals(JS_FINALIZE) ){
sb.append( " finalize : " ).append( textMRFinalize.getText().trim() ).append(",");
}
// scope
if ( textMRScope.getText().trim().length() != 0 ){
if ( !textMRScope.getText().trim().startsWith("{") && !textMRScope.getText().trim().endsWith("}") ){
EventWorkBenchManager.getInst().onEvent(Event.EXCEPTION, new Exception("scope does not look like a document") );
return;
}
sb.append( " scope : " ).append( textMRScope.getText().trim() ).append(",");
}
// flags
sb.append( "jsMode:" ).append( btnJsmode.getSelection() ).append(",");
sb.append( "verbose:" ).append( btnVerbose.getSelection() );
sb.append( "} )" );
try {
MongoCommand mcmd = MongoFactory.getInst().createCommand(sb.toString());
if ( mcmd != null )
MongoFactory.getInst().submitExecution( mcmd.setConnection( MongoFactory.getInst().getActiveServer(), wizardparent.getActiveDB() ) );
}catch (Exception e) {
EventWorkBenchManager.getInst().onEvent( org.aw20.mongoworkbench.Event.EXCEPTION, e );
}
}
@Override
public boolean onWizardCommand(MongoCommand cmd, BasicDBObject dbo) {
if ( !cmd.getClass().getName().equals( MapReduceMongoCommand.class.getName() ) )
return false;
if ( !dbo.containsField("mapreduceArgs") )
return false;
BasicDBList dbList = (BasicDBList)dbo.get("mapreduceArgs");
BasicDBObject options = (BasicDBObject)dbList.get(2);
// Input section
if ( options.containsField("query") ){ | textMRQuery.setText( JSONFormatter.format( options.get("query") ) ); | 6 |
evolvingstuff/RecurrentJava | src/ExampleEmbeddedReberGrammar.java | [
"public interface Model extends Serializable {\n\tMatrix forward(Matrix input, Graph g) throws Exception;\n\tvoid resetState();\n\tList<Matrix> getParameters();\n}",
"public class Trainer {\n\t\n\tpublic static double decayRate = 0.999;\n\tpublic static double smoothEpsilon = 1e-8;\n\tpublic static double gradientClipValue = 5;\n\tpublic static double regularization = 0.000001; // L2 regularization strength\n\t\n\tpublic static double train(int trainingEpochs, double learningRate, Model model, DataSet data, int reportEveryNthEpoch, Random rng) throws Exception {\n\t\treturn train(trainingEpochs, learningRate, model, data, reportEveryNthEpoch, false, false, null, rng);\n\t}\n\t\n\tpublic static double train(int trainingEpochs, double learningRate, Model model, DataSet data, int reportEveryNthEpoch, boolean initFromSaved, boolean overwriteSaved, String savePath, Random rng) throws Exception {\n\t\tSystem.out.println(\"--------------------------------------------------------------\");\n\t\tif (initFromSaved) {\n\t\t\tSystem.out.println(\"initializing model from saved state...\");\n\t\t\ttry {\n\t\t\t\tmodel = (Model)FileIO.deserialize(savePath);\n\t\t\t\tdata.DisplayReport(model, rng);\n\t\t\t}\n\t\t\tcatch (Exception e) {\n\t\t\t\tSystem.out.println(\"Oops. Unable to load from a saved state.\");\n\t\t\t\tSystem.out.println(\"WARNING: \" + e.getMessage());\n\t\t\t\tSystem.out.println(\"Continuing from freshly initialized model instead.\");\n\t\t\t}\n\t\t}\n\t\tdouble result = 1.0;\n\t\tfor (int epoch = 0; epoch < trainingEpochs; epoch++) {\n\t\t\t\n\t\t\tString show = \"epoch[\"+(epoch+1)+\"/\"+trainingEpochs+\"]\";\n\t\t\t\n\t\t\tdouble reportedLossTrain = pass(learningRate, model, data.training, true, data.lossTraining, data.lossReporting);\n\t\t\tresult = reportedLossTrain;\n\t\t\tif (Double.isNaN(reportedLossTrain) || Double.isInfinite(reportedLossTrain)) {\n\t\t\t\tthrow new Exception(\"WARNING: invalid value for training loss. Try lowering learning rate.\");\n\t\t\t}\n\t\t\tdouble reportedLossValidation = 0;\n\t\t\tdouble reportedLossTesting = 0;\n\t\t\tif (data.validation != null) {\n\t\t\t\treportedLossValidation = pass(learningRate, model, data.validation, false, data.lossTraining, data.lossReporting);\n\t\t\t\tresult = reportedLossValidation;\n\t\t\t}\n\t\t\tif (data.testing != null) {\n\t\t\t\treportedLossTesting = pass(learningRate, model, data.testing, false, data.lossTraining, data.lossReporting);\n\t\t\t\tresult = reportedLossTesting;\n\t\t\t}\n\t\t\tshow += \"\\ttrain loss = \"+String.format(\"%.5f\", reportedLossTrain);\n\t\t\tif (data.validation != null) {\n\t\t\t\tshow += \"\\tvalid loss = \"+String.format(\"%.5f\", reportedLossValidation);\n\t\t\t}\n\t\t\tif (data.testing != null) {\n\t\t\t\tshow += \"\\ttest loss = \"+String.format(\"%.5f\", reportedLossTesting);\n\t\t\t}\n\t\t\tSystem.out.println(show);\n\t\t\t\n\t\t\tif (epoch % reportEveryNthEpoch == reportEveryNthEpoch - 1) {\n\t\t\t\tdata.DisplayReport(model, rng);\n\t\t\t}\n\t\t\t\n\t\t\tif (overwriteSaved) {\n\t\t\t\tFileIO.serialize(savePath, model);\n\t\t\t}\n\t\t\t\n\t\t\tif (reportedLossTrain == 0 && reportedLossValidation == 0) {\n\t\t\t\tSystem.out.println(\"--------------------------------------------------------------\");\n\t\t\t\tSystem.out.println(\"\\nDONE.\");\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\t\n\tpublic static double pass(double learningRate, Model model, List<DataSequence> sequences, boolean applyTraining, Loss lossTraining, Loss lossReporting) throws Exception {\n\t\t\n\t\tdouble numerLoss = 0;\n\t\tdouble denomLoss = 0;\n\t\t\n\t\tfor (DataSequence seq : sequences) {\n\t\t\tmodel.resetState();\n\t\t\tGraph g = new Graph(applyTraining);\n\t\t\tfor (DataStep step : seq.steps) {\n\t\t\t\tMatrix output = model.forward(step.input, g);\t\t\t\t\n\t\t\t\tif (step.targetOutput != null) {\n\t\t\t\t\tdouble loss = lossReporting.measure(output, step.targetOutput);\n\t\t\t\t\tif (Double.isNaN(loss) || Double.isInfinite(loss)) {\n\t\t\t\t\t\treturn loss;\n\t\t\t\t\t}\n\t\t\t\t\tnumerLoss += loss;\n\t\t\t\t\tdenomLoss++;\t\t\t\n\t\t\t\t\tif (applyTraining) {\n\t\t\t\t\t\tlossTraining.backward(output, step.targetOutput);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tList<DataSequence> thisSequence = new ArrayList<>();\n\t\t\tthisSequence.add(seq);\n\t\t\tif (applyTraining) {\n\t\t\t\tg.backward(); //backprop dw values\n\t\t\t\tupdateModelParams(model, learningRate); //update params\n\t\t\t}\t\n\t\t}\n\t\treturn numerLoss/denomLoss;\n\t}\n\t\n\tpublic static void updateModelParams(Model model, double stepSize) throws Exception {\n\t\tfor (Matrix m : model.getParameters()) {\n\t\t\tfor (int i = 0; i < m.w.length; i++) {\n\t\t\t\t\n\t\t\t\t// rmsprop adaptive learning rate\n\t\t\t\tdouble mdwi = m.dw[i];\n\t\t\t\tm.stepCache[i] = m.stepCache[i] * decayRate + (1 - decayRate) * mdwi * mdwi;\n\t\t\t\t\n\t\t\t\t// gradient clip\n\t\t\t\tif (mdwi > gradientClipValue) {\n\t\t\t\t\tmdwi = gradientClipValue;\n\t\t\t\t}\n\t\t\t\tif (mdwi < -gradientClipValue) {\n\t\t\t\t\tmdwi = -gradientClipValue;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\t// update (and regularize)\n\t\t\t\tm.w[i] += - stepSize * mdwi / Math.sqrt(m.stepCache[i] + smoothEpsilon) - regularization * m.w[i];\n\t\t\t\tm.dw[i] = 0;\n\t\t\t}\n\t\t}\n\t}\n}",
"public class NeuralNetworkHelper {\n\t\n\tpublic static NeuralNetwork makeLstm(int inputDimension, int hiddenDimension, int hiddenLayers, int outputDimension, Nonlinearity decoderUnit, double initParamsStdDev, Random rng) {\n\t\tList<Model> layers = new ArrayList<>();\n\t\tfor (int h = 0; h < hiddenLayers; h++) {\n\t\t\tif (h == 0) {\n\t\t\t\tlayers.add(new LstmLayer(inputDimension, hiddenDimension, initParamsStdDev, rng));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlayers.add(new LstmLayer(hiddenDimension, hiddenDimension, initParamsStdDev, rng));\n\t\t\t}\n\t\t}\n\t\tlayers.add(new FeedForwardLayer(hiddenDimension, outputDimension, decoderUnit, initParamsStdDev, rng));\n\t\treturn new NeuralNetwork(layers);\n\t}\n\t\n\tpublic static NeuralNetwork makeLstmWithInputBottleneck(int inputDimension, int bottleneckDimension, int hiddenDimension, int hiddenLayers, int outputDimension, Nonlinearity decoderUnit, double initParamsStdDev, Random rng) {\n\t\tList<Model> layers = new ArrayList<>();\n\t\tlayers.add(new LinearLayer(inputDimension, bottleneckDimension, initParamsStdDev, rng));\n\t\tfor (int h = 0; h < hiddenLayers; h++) {\n\t\t\tif (h == 0) {\n\t\t\t\tlayers.add(new LstmLayer(bottleneckDimension, hiddenDimension, initParamsStdDev, rng));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlayers.add(new LstmLayer(hiddenDimension, hiddenDimension, initParamsStdDev, rng));\n\t\t\t}\n\t\t}\n\t\tlayers.add(new FeedForwardLayer(hiddenDimension, outputDimension, decoderUnit, initParamsStdDev, rng));\n\t\treturn new NeuralNetwork(layers);\n\t}\n\t\n\tpublic static NeuralNetwork makeFeedForward(int inputDimension, int hiddenDimension, int hiddenLayers, int outputDimension, Nonlinearity hiddenUnit, Nonlinearity decoderUnit, double initParamsStdDev, Random rng) {\n\t\tList<Model> layers = new ArrayList<>();\n\t\tif (hiddenLayers == 0) {\n\t\t\tlayers.add(new FeedForwardLayer(inputDimension, outputDimension, decoderUnit, initParamsStdDev, rng));\n\t\t\treturn new NeuralNetwork(layers);\n\t\t}\n\t\telse {\n\t\t\tfor (int h = 0; h < hiddenLayers; h++) {\n\t\t\t\tif (h == 0) {\n\t\t\t\t\tlayers.add(new FeedForwardLayer(inputDimension, hiddenDimension, hiddenUnit, initParamsStdDev, rng));\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tlayers.add(new FeedForwardLayer(hiddenDimension, hiddenDimension, hiddenUnit, initParamsStdDev, rng));\n\t\t\t\t}\n\t\t\t}\n\t\t\tlayers.add(new FeedForwardLayer(hiddenDimension, outputDimension, decoderUnit, initParamsStdDev, rng));\n\t\t\treturn new NeuralNetwork(layers);\n\t\t}\n\t}\n\t\n\tpublic static NeuralNetwork makeGru(int inputDimension, int hiddenDimension, int hiddenLayers, int outputDimension, Nonlinearity decoderUnit, double initParamsStdDev, Random rng) {\n\t\tList<Model> layers = new ArrayList<>();\n\t\tfor (int h = 0; h < hiddenLayers; h++) {\n\t\t\tif (h == 0) {\n\t\t\t\tlayers.add(new GruLayer(inputDimension, hiddenDimension, initParamsStdDev, rng));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlayers.add(new GruLayer(hiddenDimension, hiddenDimension, initParamsStdDev, rng));\n\t\t\t}\n\t\t}\n\t\tlayers.add(new FeedForwardLayer(hiddenDimension, outputDimension, decoderUnit, initParamsStdDev, rng));\n\t\treturn new NeuralNetwork(layers);\n\t}\n\t\n\tpublic static NeuralNetwork makeRnn(int inputDimension, int hiddenDimension, int hiddenLayers, int outputDimension, Nonlinearity hiddenUnit, Nonlinearity decoderUnit, double initParamsStdDev, Random rng) {\n\t\tList<Model> layers = new ArrayList<>();\n\t\tfor (int h = 0; h < hiddenLayers; h++) {\n\t\t\tif (h == 0) {\n\t\t\t\tlayers.add(new RnnLayer(inputDimension, hiddenDimension, hiddenUnit, initParamsStdDev, rng));\n\t\t\t}\n\t\t\telse {\n\t\t\t\tlayers.add(new RnnLayer(hiddenDimension, hiddenDimension, hiddenUnit, initParamsStdDev, rng));\n\t\t\t}\n\t\t}\n\t\tlayers.add(new FeedForwardLayer(hiddenDimension, outputDimension, decoderUnit, initParamsStdDev, rng));\n\t\treturn new NeuralNetwork(layers);\n\t}\n}",
"public class EmbeddedReberGrammar extends DataSet {\n\t\n\tstatic public class State {\n\t\tpublic State(Transition[] transitions) {\n\t\t\tthis.transitions = transitions;\n\t\t}\n\t\tpublic Transition[] transitions;\n\t}\n\t\n\tstatic public class Transition {\n\t\tpublic Transition(int next_state_id, int token) {\n\t\t\tthis.next_state_id = next_state_id;\n\t\t\tthis.token = token;\n\t\t}\n\t\tpublic int next_state_id;\n\t\tpublic int token;\n\t}\n\t\n\tpublic EmbeddedReberGrammar(Random r) throws Exception {\n\t\tint total_sequences = 1000;\n\t\tinputDimension = 7;\n\t\toutputDimension = 7;\n\t\tlossTraining = new LossSumOfSquares();\n\t\tlossReporting = new LossMultiDimensionalBinary();\n\t\ttraining = generateSequences(r, total_sequences);\n\t\tvalidation = generateSequences(r, total_sequences);\n\t\ttesting = generateSequences(r, total_sequences);\n\t}\n\t\n\tpublic static List<DataSequence> generateSequences(Random r, int sequences) {\n\t\t\n\t\tList<DataSequence> result = new ArrayList<>();\n\t\t\n\t\tfinal int B = 0;\n\t\tfinal int T = 1;\n\t\tfinal int P = 2;\n\t\tfinal int S = 3;\n\t\tfinal int X = 4;\n\t\tfinal int V = 5;\n\t\tfinal int E = 6;\n\t\t\n\t\tState[] states = new State[19];\n\t\tstates[0] = new State(new Transition[] {new Transition(1,B)});\n\t\tstates[1] = new State(new Transition[] {new Transition(2,T), new Transition(11,P)});\n\t\tstates[2] = new State(new Transition[] {new Transition(3,B)});\n\t\tstates[3] = new State(new Transition[] {new Transition(4,T), new Transition(9,P)});\n\t\tstates[4] = new State(new Transition[] {new Transition(4,S), new Transition(5,X)});\n\t\tstates[5] = new State(new Transition[] {new Transition(6,S), new Transition(9,X)});\n\t\tstates[6] = new State(new Transition[] {new Transition(7,E)});\n\t\tstates[7] = new State(new Transition[] {new Transition(8,T)});\n\t\tstates[8] = new State(new Transition[] {new Transition(0,E)});\n\t\tstates[9] = new State(new Transition[] {new Transition(9,T), new Transition(10,V)});\n\t\tstates[10] = new State(new Transition[] {new Transition(5,P), new Transition(6,V)});\n\t\tstates[11] = new State(new Transition[] {new Transition(12,B)});\n\t\tstates[12] = new State(new Transition[] {new Transition(13,T), new Transition(17,P)});\n\t\tstates[13] = new State(new Transition[] {new Transition(13,S), new Transition(14,X)});\n\t\tstates[14] = new State(new Transition[] {new Transition(15,S), new Transition(17,X)});\n\t\tstates[15] = new State(new Transition[] {new Transition(16,E)});\n\t\tstates[16] = new State(new Transition[] {new Transition(8,P)});\n\t\tstates[17] = new State(new Transition[] {new Transition(17,T), new Transition(18,V)});\n\t\tstates[18] = new State(new Transition[] {new Transition(14,P), new Transition(15,V)});\n\t\t\n\t\tfor (int sequence = 0; sequence < sequences; sequence++) {\n\t\t\tList<DataStep> steps = new ArrayList<>();;\t\t\n\t\t\tint state_id = 0;\n\t\t\twhile (true) {\n\t\t\t\tint transition = -1;\n\t\t\t\tif (states[state_id].transitions.length == 1) {\n\t\t\t\t\ttransition = 0;\n\t\t\t\t}\n\t\t\t\telse if (states[state_id].transitions.length == 2) {\n\t\t\t\t\ttransition = r.nextInt(2);\n\t\t\t\t}\n\t\t\t\tdouble[] observation = null;\n\t\t\t\t\n\t\t\t\tobservation = new double[7];\n\t\t\t\tobservation[states[state_id].transitions[transition].token] = 1.0;\n\t\t\t\t\n\t\t\t\tstate_id = states[state_id].transitions[transition].next_state_id;\n\t\t\t\tif (state_id == 0) { //exit at end of sequence\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tdouble[] target_output = new double[7];\n\t\t\t\tfor (int i = 0; i < states[state_id].transitions.length; i++) {\n\t\t\t\t\ttarget_output[states[state_id].transitions[i].token] = 1.0;\n\t\t\t\t}\n\t\t\t\tsteps.add(new DataStep(observation, target_output));\n\t\t\t}\n\t\t\tresult.add(new DataSequence(steps));\n\t\t}\n\t\treturn result;\n\t}\n\n\t@Override\n\tpublic void DisplayReport(Model model, Random rng) throws Exception {\n\t\t// TODO Auto-generated method stub\n\t\t\n\t}\n\n\t@Override\n\tpublic Nonlinearity getModelOutputUnitToUse() {\n\t\treturn new SigmoidUnit();\n\t}\n}",
"public abstract class DataSet implements Serializable {\n\tpublic int inputDimension;\n\tpublic int outputDimension;\n\tpublic Loss lossTraining;\n\tpublic Loss lossReporting;\n\tpublic List<DataSequence> training;\n\tpublic List<DataSequence> validation;\n\tpublic List<DataSequence> testing;\n\tpublic abstract void DisplayReport(Model model, Random rng) throws Exception;\n\tpublic abstract Nonlinearity getModelOutputUnitToUse();\n}"
] | import java.util.Random;
import model.Model;
import trainer.Trainer;
import util.NeuralNetworkHelper;
import datasets.EmbeddedReberGrammar;
import datastructs.DataSet; |
public class ExampleEmbeddedReberGrammar {
public static void main(String[] args) throws Exception {
Random rng = new Random();
| DataSet data = new EmbeddedReberGrammar(rng); | 3 |
Nanopublication/nanopub-java | src/main/java/org/nanopub/op/Topic.java | [
"public class MalformedNanopubException extends Exception {\n\n\tprivate static final long serialVersionUID = -1022546557206977739L;\n\n\tpublic MalformedNanopubException(String message) {\n\t\tsuper(message);\n\t}\n\n}",
"public class MultiNanopubRdfHandler extends AbstractRDFHandler {\n\n\tpublic static void process(RDFFormat format, InputStream in, NanopubHandler npHandler)\n\t\t\tthrows IOException, RDFParseException, RDFHandlerException, MalformedNanopubException {\n\t\tprocess(format, in, null, npHandler);\n\t}\n\n\tpublic static void process(RDFFormat format, File file, NanopubHandler npHandler)\n\t\t\tthrows IOException, RDFParseException, RDFHandlerException, MalformedNanopubException {\n\t\tInputStream in;\n\t\tif (file.getName().matches(\".*\\\\.(gz|gzip)\")) {\n\t\t\tin = new GZIPInputStream(new BufferedInputStream(new FileInputStream(file)));\n\t\t} else {\n\t\t\tin = new BufferedInputStream(new FileInputStream(file));\n\t\t}\n\t\tprocess(format, in, file, npHandler);\n\t}\n\n\tpublic static void process(File file, NanopubHandler npHandler)\n\t\t\tthrows IOException, RDFParseException, RDFHandlerException, MalformedNanopubException {\n\t\tRDFFormat format = Rio.getParserFormatForFileName(file.getName()).orElse(RDFFormat.TRIG);\n\t\tprocess(format, file, npHandler);\n\t}\n\n\tprivate static void process(RDFFormat format, InputStream in, File file, NanopubHandler npHandler)\n\t\t\tthrows IOException, RDFParseException, RDFHandlerException, MalformedNanopubException {\n\t\tRDFParser p = NanopubUtils.getParser(format);\n\t\tp.setRDFHandler(new MultiNanopubRdfHandler(npHandler));\n\t\ttry {\n\t\t\tp.parse(new InputStreamReader(in, Charset.forName(\"UTF-8\")), \"\");\n\t\t} catch (RuntimeException ex) {\n\t\t\tif (\"wrapped MalformedNanopubException\".equals(ex.getMessage()) &&\n\t\t\t\t\tex.getCause() instanceof MalformedNanopubException) {\n\t\t\t\tthrow (MalformedNanopubException) ex.getCause();\n\t\t\t} else {\n\t\t\t\tthrow ex;\n\t\t\t}\n\t\t} finally {\n\t\t\tin.close();\n\t\t}\n\t}\n\n\tprivate NanopubHandler npHandler;\n\n\tprivate Map<IRI,Boolean> graphs = new HashMap<>();\n\tprivate Map<IRI,Map<IRI,Boolean>> members = new HashMap<>();\n\tprivate Set<Statement> statements = new LinkedHashSet<>();\n\tprivate List<String> nsPrefixes = new ArrayList<>();\n\tprivate Map<String,String> ns = new HashMap<>();\n\n\tprivate List<String> newNsPrefixes = new ArrayList<>();\n\tprivate List<String> newNs = new ArrayList<>();\n\n\tpublic MultiNanopubRdfHandler(NanopubHandler npHandler) {\n\t\tthis.npHandler = npHandler;\n\t}\n\n\t@Override\n\tpublic void handleStatement(Statement st) throws RDFHandlerException {\n\t\tif (!graphs.containsKey(st.getContext())) {\n\t\t\tif (graphs.size() == 4) {\n\t\t\t\tfinishAndReset();\n\t\t\t\thandleStatement(st);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tgraphs.put((IRI) st.getContext(), true);\n\t\t}\n\t\taddNamespaces();\n\t\tstatements.add(st);\n\t}\n\n\t@Override\n\tpublic void handleNamespace(String prefix, String uri) throws RDFHandlerException {\n\t\tnewNs.add(uri);\n\t\tnewNsPrefixes.add(prefix);\n\t}\n\n\tpublic void addNamespaces() throws RDFHandlerException {\n\t\tfor (int i = 0 ; i < newNs.size() ; i++) {\n\t\t\tString prefix = newNsPrefixes.get(i);\n\t\t\tString nsUri = newNs.get(i);\n\t\t\tnsPrefixes.remove(prefix);\n\t\t\tnsPrefixes.add(prefix);\n\t\t\tns.put(prefix, nsUri);\n\t\t}\n\t\tnewNs.clear();\n\t\tnewNsPrefixes.clear();\n\t}\n\n\t@Override\n\tpublic void endRDF() throws RDFHandlerException {\n\t\tfinishAndReset();\n\t}\n\n\tprivate void finishAndReset() {\n\t\ttry {\n\t\t\tnpHandler.handleNanopub(new NanopubImpl(statements, nsPrefixes, ns));\n\t\t} catch (MalformedNanopubException ex) {\n\t\t\tif (ex.getMessage().equals(\"No content received for nanopub\")) { // TODO: Improve this check!\n\t\t\t\t// ignore (a stream of zero nanopubs is also a valid nanopub stream)\n\t\t\t} else {\n\t\t\t\tthrowMalformed(ex);\n\t\t\t}\n\t\t}\n\t\tclearAll();\n\t}\n\n\tprivate void clearAll() {\n\t\tgraphs.clear();\n\t\tmembers.clear();\n\t\tstatements.clear();\n\t}\n\n\tprivate void throwMalformed(MalformedNanopubException ex) {\n\t\tthrow new RuntimeException(\"wrapped MalformedNanopubException\", ex);\n\t}\n\n\t\n\tpublic interface NanopubHandler {\n\n\t\tpublic void handleNanopub(Nanopub np);\n\n\t}\n\n}",
"public interface NanopubHandler {\n\n\tpublic void handleNanopub(Nanopub np);\n\n}",
"public class DefaultTopics implements TopicHandler {\n\n\tprivate Map<String,Boolean> ignore = new HashMap<>();\n\n\tpublic DefaultTopics(String ignoreProperties) {\n\t\tif (ignoreProperties != null) {\n\t\t\tfor (String s : ignoreProperties.trim().split(\"\\\\|\")) {\n\t\t\t\tif (!s.isEmpty()) ignore.put(s, true);\n\t\t\t}\n\t\t}\n\t}\n\n\t@Override\n\tpublic String getTopic(Nanopub np) {\n\t\tMap<Resource,Integer> resourceCount = new HashMap<>();\n\t\tfor (Statement st : np.getAssertion()) {\n\t\t\tResource subj = st.getSubject();\n\t\t\tif (subj.equals(np.getUri())) continue;\n\t\t\tif (ignore.containsKey(st.getPredicate().stringValue())) continue;\n\t\t\tif (!resourceCount.containsKey(subj)) resourceCount.put(subj, 0);\n\t\t\tresourceCount.put(subj, resourceCount.get(subj) + 1);\n\t\t}\n\t\tint max = 0;\n\t\tResource topic = null;\n\t\tfor (Resource r : resourceCount.keySet()) {\n\t\t\tint c = resourceCount.get(r);\n\t\t\tif (c > max) {\n\t\t\t\ttopic = r;\n\t\t\t\tmax = c;\n\t\t\t} else if (c == max) {\n\t\t\t\ttopic = null;\n\t\t\t}\n\t\t}\n\t\treturn topic + \"\";\n\t}\n\n}",
"public interface Nanopub {\n\n\t// URIs in the nanopub namespace:\n\tpublic static final IRI NANOPUB_TYPE_URI = SimpleValueFactory.getInstance().createIRI(\"http://www.nanopub.org/nschema#Nanopublication\");\n\tpublic static final IRI HAS_ASSERTION_URI = SimpleValueFactory.getInstance().createIRI(\"http://www.nanopub.org/nschema#hasAssertion\");\n\tpublic static final IRI HAS_PROVENANCE_URI = SimpleValueFactory.getInstance().createIRI(\"http://www.nanopub.org/nschema#hasProvenance\");\n\tpublic static final IRI HAS_PUBINFO_URI = SimpleValueFactory.getInstance().createIRI(\"http://www.nanopub.org/nschema#hasPublicationInfo\");\n\n\t// URIs that link nanopublications:\n\tpublic static final IRI SUPERSEDES = SimpleValueFactory.getInstance().createIRI(\"http://purl.org/nanopub/x/supersedes\");\n\n\tpublic IRI getUri();\n\n\tpublic IRI getHeadUri();\n\n\tpublic Set<Statement> getHead();\n\n\tpublic IRI getAssertionUri();\n\n\tpublic Set<Statement> getAssertion();\n\n\tpublic IRI getProvenanceUri();\n\n\tpublic Set<Statement> getProvenance();\n\n\tpublic IRI getPubinfoUri();\n\n\tpublic Set<Statement> getPubinfo();\n\n\tpublic Set<IRI> getGraphUris();\n\n\t// TODO: Now that we have SimpleCreatorPattern and SimpleTimestampPattern,\n\t// we might not need the following three methods anymore...\n\n\tpublic Calendar getCreationTime();\n\n\tpublic Set<IRI> getAuthors();\n\n\tpublic Set<IRI> getCreators();\n\n\tpublic int getTripleCount();\n\n\tpublic long getByteCount();\n\n}",
"public class NanopubImpl implements NanopubWithNs, Serializable {\n\n\tprivate static final long serialVersionUID = -1514452524339132128L;\n\n\tstatic {\n\t\ttryToLoadParserFactory(\"org.eclipse.rdf4j.rio.trig.TriGParserFactory\");\n\t\tRDFWriterRegistry.getInstance().add(new CustomTrigWriterFactory());\n\t\ttryToLoadParserFactory(\"org.eclipse.rdf4j.rio.nquads.NQuadsParserFactory\");\n\t\ttryToLoadWriterFactory(\"org.eclipse.rdf4j.rio.nquads.NQuadsWriterFactory\");\n\t\ttryToLoadParserFactory(\"org.eclipse.rdf4j.rio.trix.TriXParserFactory\");\n\t\ttryToLoadWriterFactory(\"org.eclipse.rdf4j.rio.trix.TriXWriterFactory\");\n\t\ttryToLoadParserFactory(\"org.eclipse.rdf4j.rio.jsonld.JSONLDParserFactory\");\n\t\ttryToLoadWriterFactory(\"org.eclipse.rdf4j.rio.jsonld.JSONLDWriterFactory\");\n\t}\n\n\tprivate static void tryToLoadParserFactory(String className) {\n\t\ttry {\n\t\t\tRDFParserFactory pf = (RDFParserFactory) Class.forName(className).newInstance();\n\t\t\tRDFParserRegistry.getInstance().add(pf);\n\t\t} catch (ClassNotFoundException | IllegalAccessException | InstantiationException ex) {\n\t\t\tthrow new RuntimeException(ex);\n\t\t};\n\t}\n\n\tprivate static void tryToLoadWriterFactory(String className) {\n\t\ttry {\n\t\t\tRDFWriterFactory wf = (RDFWriterFactory) Class.forName(className).newInstance();\n\t\t\tRDFWriterRegistry.getInstance().add(wf);\n\t\t} catch (ClassNotFoundException | IllegalAccessException | InstantiationException ex) {\n\t\t\tthrow new RuntimeException(ex);\n\t\t};\n\t}\n\n\tpublic static void ensureLoaded() {\n\t\t// ensure class is loaded; nothing left to be done\n\t}\n\n\tprivate static final MimetypesFileTypeMap mimeMap = new MimetypesFileTypeMap();\n\n\tprivate IRI nanopubUri;\n\tprivate IRI headUri, assertionUri, provenanceUri, pubinfoUri;\n\tprivate Set<IRI> graphUris;\n\tprivate Set<Statement> head, assertion, provenance, pubinfo;\n\n\tprivate List<Statement> statements = new ArrayList<>();\n\tprivate List<String> nsPrefixes = new ArrayList<>();\n\tprivate Map<String,String> ns = new HashMap<>();\n\tprivate boolean unusedPrefixesRemoved = false;\n\n\tprivate int tripleCount;\n\tprivate long byteCount;\n\n\tpublic NanopubImpl(Collection<Statement> statements, List<String> nsPrefixes, Map<String,String> ns) throws MalformedNanopubException {\n\t\tthis.statements.addAll(statements);\n\t\tthis.nsPrefixes.addAll(nsPrefixes);\n\t\tthis.ns.putAll(ns);\n\t\tinit();\n\t}\n\n\tpublic NanopubImpl(Collection<Statement> statements, List<Pair<String,String>> namespaces) throws MalformedNanopubException {\n\t\tthis.statements.addAll(statements);\n\t\tfor (Pair<String,String> p : namespaces) {\n\t\t\tnsPrefixes.add(p.getLeft());\n\t\t\tns.put(p.getLeft(), p.getRight());\n\t\t}\n\t\tinit();\n\t}\n\n\tpublic NanopubImpl(Collection<Statement> statements) throws MalformedNanopubException {\n\t\tthis.statements.addAll(statements);\n\t\tinit();\n\t}\n\n\tprivate static final String nanopubViaSPARQLQuery =\n\t\t\t\"prefix np: <http://www.nanopub.org/nschema#> \" +\n\t\t\t\"prefix rdfg: <http://www.w3.org/2004/03/trix/rdfg-1/> \" +\n\t\t\t\"prefix this: <@> \" +\n\t\t\t\"select ?G ?S ?P ?O where { \" +\n\t\t\t\" { \" +\n\t\t\t\" graph ?G { this: a np:Nanopublication } \" +\n\t\t\t\" } union { \" +\n\t\t\t\" graph ?H { this: a np:Nanopublication } . \" +\n\t\t\t\" graph ?H { { this: np:hasAssertion ?G } union { this: np:hasProvenance ?G } \" +\n\t\t\t\" union { this: np:hasPublicationInfo ?G } } \" +\n\t\t\t\" } \" +\n\t\t\t\" graph ?G { ?S ?P ?O } \" +\n\t\t\t\"}\";\n\n\tpublic NanopubImpl(Repository repo, IRI nanopubUri, List<String> nsPrefixes, Map<String,String> ns)\n\t\t\tthrows MalformedNanopubException, RepositoryException {\n\t\tif (nsPrefixes != null) this.nsPrefixes.addAll(nsPrefixes);\n\t\tif (ns != null) this.ns.putAll(ns);\n\t\ttry {\n\t\t\tRepositoryConnection connection = repo.getConnection();\n\t\t\ttry {\n\t\t\t\tString q = nanopubViaSPARQLQuery.replaceAll(\"@\", nanopubUri.toString());\n\t\t\t\tTupleQuery tupleQuery = connection.prepareTupleQuery(QueryLanguage.SPARQL, q);\n\t\t\t\tTupleQueryResult result = tupleQuery.evaluate();\n\t\t\t\ttry {\n\t\t\t\t\twhile (result.hasNext()) {\n\t\t\t\t\t\tBindingSet bs = result.next();\n\t\t\t\t\t\tResource g = (Resource) bs.getBinding(\"G\").getValue();\n\t\t\t\t\t\tResource s = (Resource) bs.getBinding(\"S\").getValue();\n\t\t\t\t\t\tIRI p = (IRI) bs.getBinding(\"P\").getValue();\n\t\t\t\t\t\tValue o = bs.getBinding(\"O\").getValue();\n\t\t\t\t\t\tStatement st = SimpleValueFactory.getInstance().createStatement(s, p, o, g);\n\t\t\t\t\t\tstatements.add(st);\n\t\t\t\t\t}\n\t\t\t\t} finally {\n\t\t\t\t\tresult.close();\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tconnection.close();\n\t\t\t}\n\t\t} catch (MalformedQueryException ex) {\n\t\t\tex.printStackTrace();\n\t\t} catch (QueryEvaluationException ex) {\n\t\t\tex.printStackTrace();\n\t\t}\n\t\tinit();\n\t}\n\n\tpublic NanopubImpl(Repository repo, IRI nanopubUri)\n\t\t\tthrows MalformedNanopubException, RepositoryException {\n\t\tthis(repo, nanopubUri, null, null);\n\t}\n\n\tpublic NanopubImpl(File file, RDFFormat format)\n\t\t\tthrows MalformedNanopubException, RDF4JException, IOException {\n\t\treadStatements(new FileInputStream(file), format, \"\");\n\t\tinit();\n\t}\n\n\tpublic NanopubImpl(File file) throws MalformedNanopubException, RDF4JException, IOException {\n\t\tString n = file.getName();\n\t\tOptional<RDFFormat> format = Rio.getParserFormatForMIMEType(mimeMap.getContentType(n));\n\t\tif (!format.isPresent() || !format.get().supportsContexts()) {\n\t\t\tformat = Rio.getParserFormatForFileName(n);\n\t\t}\n\t\tRDFFormat f = format.get();\n\t\tif (!f.supportsContexts()) {\n\t\t\tf = RDFFormat.TRIG;\n\t\t}\n\t\treadStatements(new FileInputStream(file), f, \"\");\n\t\tinit();\n\t}\n\n\tpublic NanopubImpl(URL url, RDFFormat format) throws MalformedNanopubException, RDF4JException, IOException {\n\t\tHttpResponse response = getNanopub(url);\n\t\treadStatements(response.getEntity().getContent(), format, \"\");\n\t\tinit();\n\t}\n\n\tpublic NanopubImpl(URL url) throws MalformedNanopubException, RDF4JException, IOException {\n\t\tHttpResponse response = getNanopub(url);\n\t\tHeader contentTypeHeader = response.getFirstHeader(\"Content-Type\");\n\t\tOptional<RDFFormat> format = null;\n\t\tif (contentTypeHeader != null) {\n\t\t\tformat = Rio.getParserFormatForMIMEType(contentTypeHeader.getValue());\n\t\t}\n\t\tif (format == null || !format.isPresent() || !format.get().supportsContexts()) {\n\t\t\tformat = Rio.getParserFormatForFileName(url.toString());\n\t\t}\n\t\tRDFFormat f = format.get();\n\t\tif (!f.supportsContexts()) {\n\t\t\tf = RDFFormat.TRIG;\n\t\t}\n\t\treadStatements(response.getEntity().getContent(), f, \"\");\n\t\tinit();\n\t}\n\n\tprivate HttpResponse getNanopub(URL url) throws IOException {\n\t\tHttpGet get = new HttpGet(url.toString());\n\t\tget.setHeader(\"Accept\", \"application/trig; q=1, application/x-trig; q=1, text/x-nquads; q=0.1, application/trix; q=0.1\");\n\t\tRequestConfig requestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build();\n\t\tHttpResponse response = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build().execute(get);\n\t\tint statusCode = response.getStatusLine().getStatusCode();\n\t\tif (statusCode == 404 || statusCode == 410) {\n\t\t\tthrow new FileNotFoundException(response.getStatusLine().getReasonPhrase());\n\t\t}\n\t\tif (statusCode < 200 || statusCode > 299) {\n\t\t\tthrow new IOException(\"HTTP error \" + statusCode + \": \" + response.getStatusLine().getReasonPhrase());\n\t\t}\n\t\treturn response;\n\t}\n\n\tpublic NanopubImpl(InputStream in, RDFFormat format, String baseUri)\n\t\t\tthrows MalformedNanopubException, RDF4JException, IOException {\n\t\treadStatements(in, format, baseUri);\n\t\tinit();\n\t}\n\n\tpublic NanopubImpl(InputStream in, RDFFormat format) throws MalformedNanopubException, RDF4JException, IOException {\n\t\tthis(in, format, \"\");\n\t}\n\n\tpublic NanopubImpl(String utf8, RDFFormat format, String baseUri) throws MalformedNanopubException, RDF4JException {\n\t\ttry {\n\t\t\treadStatements(new ByteArrayInputStream(utf8.getBytes(\"UTF-8\")), format, baseUri);\n\t\t} catch (IOException ex) {\n\t\t\t// We do not expect an IOException here (no file system IO taking place)\n\t\t\tthrow new RuntimeException(\"Unexptected IOException\", ex);\n\t\t}\n\t\tinit();\n\t}\n\n\tpublic NanopubImpl(String utf8, RDFFormat format) throws MalformedNanopubException, RDF4JException {\n\t\tthis(utf8, format, \"\");\n\t}\n\n\t// TODO Is the baseURI really needed? Shouldn't the input stream contain all needed data?\n\tprivate void readStatements(InputStream in, RDFFormat format, String baseUri)\n\t\t\tthrows MalformedNanopubException, RDF4JException, IOException {\n\t\ttry {\n\t\t\tRDFParser p = NanopubUtils.getParser(format);\n\t\t\tp.setRDFHandler(new AbstractRDFHandler() {\n\t\n\t\t\t\t@Override\n\t\t\t\tpublic void handleNamespace(String prefix, String uri) throws RDFHandlerException {\n\t\t\t\t\tnsPrefixes.add(prefix);\n\t\t\t\t\tns.put(prefix, uri);\n\t\t\t\t}\n\t\n\t\t\t\t@Override\n\t\t\t\tpublic void handleStatement(Statement st) throws RDFHandlerException {\n\t\t\t\t\tstatements.add(st);\n\t\t\t\t}\n\t\n\t\t\t});\n\t\t\tp.parse(new InputStreamReader(in, Charset.forName(\"UTF-8\")), baseUri);\n\t\t} finally {\n\t\t\tin.close();\n\t\t}\n\t}\n\n\tprivate void init() throws MalformedNanopubException {\n\t\tif (statements.isEmpty()) {\n\t\t\tthrow new MalformedNanopubException(\"No content received for nanopub\");\n\t\t}\n\t\tcollectNanopubUri(statements);\n\t\tif (nanopubUri == null || headUri == null) {\n\t\t\tthrow new MalformedNanopubException(\"No nanopub URI found\");\n\t\t}\n\t\tcollectGraphs(statements);\n\t\tcollectStatements(statements);\n\t\tcheckAssertion();\n\t\tcheckProvenance();\n\t\tcheckPubinfo();\n\t}\n\n\tprivate void collectNanopubUri(Collection<Statement> statements) throws MalformedNanopubException {\n\t\tfor (Statement st : statements) {\n\t\t\tif (st.getContext() == null) {\n\t\t\t\tthrow new MalformedNanopubException(\"Null value for context URI found.\");\n\t\t\t}\n\t\t\tif (st.getPredicate().equals(RDF.TYPE) && st.getObject().equals(Nanopub.NANOPUB_TYPE_URI)) {\n\t\t\t\tif (nanopubUri != null) {\n\t\t\t\t\tthrow new MalformedNanopubException(\"Two nanopub URIs found\");\n\t\t\t\t}\n\t\t\t\tnanopubUri = (IRI) st.getSubject();\n\t\t\t\theadUri = (IRI) st.getContext();\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate void collectGraphs(Collection<Statement> statements) throws MalformedNanopubException {\n\t\tfor (Statement st : statements) {\n\t\t\tif (st.getContext().equals(headUri)) {\n\t\t\t\tResource s = st.getSubject();\n\t\t\t\tIRI p = st.getPredicate();\n\t\t\t\tif (s.equals(nanopubUri) && p.equals(Nanopub.HAS_ASSERTION_URI)) {\n\t\t\t\t\tif (assertionUri != null) {\n\t\t\t\t\t\tthrow new MalformedNanopubException(\"Two assertion URIs found: \" +\n\t\t\t\t\t\t\t\tassertionUri + \" and \" + st.getObject());\n\t\t\t\t\t}\n\t\t\t\t\tassertionUri = (IRI) st.getObject();\n\t\t\t\t} else if (s.equals(nanopubUri) && p.equals(Nanopub.HAS_PROVENANCE_URI)) {\n\t\t\t\t\tif (provenanceUri != null) {\n\t\t\t\t\t\tthrow new MalformedNanopubException(\"Two provenance URIs found: \" +\n\t\t\t\t\t\t\t\tprovenanceUri + \" and \" + st.getObject());\n\t\t\t\t\t}\n\t\t\t\t\tprovenanceUri = (IRI) st.getObject();\n\t\t\t\t} else if (s.equals(nanopubUri) && p.equals(Nanopub.HAS_PUBINFO_URI)) {\n\t\t\t\t\tif (pubinfoUri != null) {\n\t\t\t\t\t\tthrow new MalformedNanopubException(\"Two publication info URIs found: \" +\n\t\t\t\t\t\t\t\tpubinfoUri + \" and \" + st.getObject());\n\t\t\t\t\t}\n\t\t\t\t\tpubinfoUri = (IRI) st.getObject();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (assertionUri == null) {\n\t\t\tthrow new MalformedNanopubException(\"No assertion URI found for \" + nanopubUri);\n\t\t}\n\t\tif (provenanceUri == null) {\n\t\t\tthrow new MalformedNanopubException(\"No provenance URI found for \" + nanopubUri);\n\t\t}\n\t\tif (pubinfoUri == null) {\n\t\t\tthrow new MalformedNanopubException(\"No publication info URI found for \" + nanopubUri);\n\t\t}\n\t\tgraphUris = new HashSet<>();\n\t\taddGraphUri(headUri);\n\t\taddGraphUri(assertionUri);\n\t\taddGraphUri(provenanceUri);\n\t\taddGraphUri(pubinfoUri);\n\t\tif (graphUris.contains(nanopubUri)) {\n\t\t\tthrow new MalformedNanopubException(\"Nanopub URI cannot be identical to one of the graph URIs: \" + nanopubUri);\n\t\t}\n\t\tthis.graphUris = ImmutableSet.copyOf(graphUris);\n\t}\n\n\tprivate void addGraphUri(IRI uri) throws MalformedNanopubException {\n\t\tif (graphUris.contains(uri)) {\n\t\t\tthrow new MalformedNanopubException(\"Each graph needs a unique URI: \" + uri);\n\t\t}\n\t\tgraphUris.add(uri);\n\t}\n\n\tprivate void collectStatements(Collection<Statement> statements) throws MalformedNanopubException {\n\t\ttripleCount = 0;\n\t\tbyteCount = 0;\n\t\tSet<Statement> head = new LinkedHashSet<>();\n\t\tSet<Statement> assertion = new LinkedHashSet<>();\n\t\tSet<Statement> provenance = new LinkedHashSet<>();\n\t\tSet<Statement> pubinfo = new LinkedHashSet<>();\n\t\tfor (Statement st : statements) {\n\t\t\tcheckStatement(st);\n\t\t\tResource g = st.getContext();\n\t\t\tif (g.equals(headUri)) {\n\t\t\t\thead.add(st);\n\t\t\t} else if (g.equals(assertionUri)) {\n\t\t\t\tassertion.add(st);\n\t\t\t} else if (g.equals(provenanceUri)) {\n\t\t\t\tprovenance.add(st);\n\t\t\t} else if (g.equals(pubinfoUri)) {\n\t\t\t\tpubinfo.add(st);\n\t\t\t} else {\n\t\t\t\tthrow new MalformedNanopubException(\"Disconnected graph: \" + g);\n\t\t\t}\n\t\t\ttripleCount++;\n\t\t\tbyteCount += st.getContext().stringValue().length();\n\t\t\tbyteCount += st.getSubject().stringValue().length();\n\t\t\tbyteCount += st.getPredicate().stringValue().length();\n\t\t\tbyteCount += st.getObject().stringValue().length();\n\t\t\tif (tripleCount < 0) tripleCount = Integer.MAX_VALUE;\n\t\t\tif (byteCount < 0) byteCount = Long.MAX_VALUE;\n\t\t}\n\t\tthis.head = ImmutableSet.copyOf(head);\n\t\tthis.assertion = ImmutableSet.copyOf(assertion);\n\t\tthis.provenance = ImmutableSet.copyOf(provenance);\n\t\tthis.pubinfo = ImmutableSet.copyOf(pubinfo);\n\t}\n\n\tprivate void checkStatement(Statement st) throws MalformedNanopubException {\n\t\tString uriString = null;\n\t\ttry {\n\t\t\t// Throw exceptions if not well-formed:\n\t\t\turiString = st.getContext().stringValue();\n\t\t\tnew java.net.URI(uriString);\n\t\t\turiString = st.getSubject().stringValue();\n\t\t\tnew java.net.URI(uriString);\n\t\t\turiString = st.getPredicate().stringValue();\n\t\t\tnew java.net.URI(uriString);\n\t\t\tif (st.getObject() instanceof IRI) {\n\t\t\t\turiString = st.getObject().stringValue();\n\t\t\t\tnew java.net.URI(uriString);\n\t\t\t}\n\t\t} catch (URISyntaxException ex) {\n\t\t\tthrow new MalformedNanopubException(\"Malformed URI: \" + uriString);\n\t\t}\n\t}\n\n\tprivate void checkAssertion() throws MalformedNanopubException {\n\t\tif (assertion.isEmpty()) {\n\t\t\tthrow new MalformedNanopubException(\"Empty assertion graph: \" + assertionUri);\n\t\t}\n\t}\n\n\tprivate void checkProvenance() throws MalformedNanopubException {\n\t\tif (provenance.isEmpty()) {\n\t\t\tthrow new MalformedNanopubException(\"Empty provenance graph: \" + provenanceUri);\n\t\t}\n\t\tfor (Statement st : provenance) {\n\t\t\tif (assertionUri.equals(st.getSubject())) return;\n\t\t\tif (assertionUri.equals(st.getObject())) return;\n\t\t}\n\t\tthrow new MalformedNanopubException(\"Provenance does not refer to assertion: \" + provenanceUri);\n\t}\n\n\tprivate void checkPubinfo() throws MalformedNanopubException {\n\t\tif (pubinfo.isEmpty()) {\n\t\t\tthrow new MalformedNanopubException(\"Empty publication info graph: \" + pubinfoUri);\n\t\t}\n\t\tfor (Statement st : pubinfo) {\n\t\t\tif (nanopubUri.equals(st.getSubject())) return;\n\t\t\tif (nanopubUri.equals(st.getObject())) return;\n\t\t}\n\t\tthrow new MalformedNanopubException(\"Publication info does not refer to nanopublication URI: \" + pubinfoUri);\n\t}\n\n\t@Override\n\tpublic IRI getUri() {\n\t\treturn nanopubUri;\n\t}\n\n\t@Override\n\tpublic IRI getHeadUri() {\n\t\treturn headUri;\n\t}\n\n\t@Override\n\tpublic Set<Statement> getHead() {\n\t\treturn head;\n\t}\n\n\t@Override\n\tpublic IRI getAssertionUri() {\n\t\treturn assertionUri;\n\t}\n\n\t@Override\n\tpublic Set<Statement> getAssertion() {\n\t\treturn assertion;\n\t}\n\n\t@Override\n\tpublic IRI getProvenanceUri() {\n\t\treturn provenanceUri;\n\t}\n\n\t@Override\n\tpublic Set<Statement> getProvenance() {\n\t\treturn provenance;\n\t}\n\n\t@Override\n\tpublic IRI getPubinfoUri() {\n\t\treturn pubinfoUri;\n\t}\n\n\t@Override\n\tpublic Set<Statement> getPubinfo() {\n\t\treturn pubinfo;\n\t}\n\n\t@Override\n\tpublic Set<IRI> getGraphUris() {\n\t\treturn graphUris;\n\t}\n\n\t@Override\n\tpublic Calendar getCreationTime() {\n\t\treturn SimpleTimestampPattern.getCreationTime(this);\n\t}\n\n\t@Override\n\tpublic Set<IRI> getAuthors() {\n\t\treturn SimpleCreatorPattern.getAuthors(this);\n\t}\n\n\t@Override\n\tpublic Set<IRI> getCreators() {\n\t\treturn SimpleCreatorPattern.getCreators(this);\n\t}\n\n\t@Override\n\tpublic List<String> getNsPrefixes() {\n\t\treturn new ArrayList<>(nsPrefixes);\n\t}\n\n\t@Override\n\tpublic String getNamespace(String prefix) {\n\t\treturn ns.get(prefix);\n\t}\n\n\t@Override\n\tpublic void removeUnusedPrefixes() {\n\t\tif (unusedPrefixesRemoved) return;\n\t\tSet<String> usedPrefixes = NanopubUtils.getUsedPrefixes(this);\n\t\tfor (String prefix : new ArrayList<>(nsPrefixes)) {\n\t\t\tif (!usedPrefixes.contains(prefix)) {\n\t\t\t\tnsPrefixes.remove(prefix);\n\t\t\t\tns.remove(prefix);\n\t\t\t}\n\t\t}\n\t\tunusedPrefixesRemoved = true;\n\t}\n\n\t@Override\n\tpublic int getTripleCount() {\n\t\treturn tripleCount;\n\t}\n\n\t@Override\n\tpublic long getByteCount() {\n\t\treturn byteCount;\n\t}\n\n}"
] | import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.GZIPOutputStream;
import net.trustyuri.TrustyUriException;
import org.nanopub.MalformedNanopubException;
import org.nanopub.MultiNanopubRdfHandler;
import org.nanopub.MultiNanopubRdfHandler.NanopubHandler;
import org.nanopub.op.topic.DefaultTopics;
import org.nanopub.Nanopub;
import org.nanopub.NanopubImpl;
import org.eclipse.rdf4j.rio.RDFFormat;
import org.eclipse.rdf4j.rio.RDFHandlerException;
import org.eclipse.rdf4j.rio.RDFParseException;
import org.eclipse.rdf4j.rio.Rio;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.ParameterException; | package org.nanopub.op;
public class Topic {
@com.beust.jcommander.Parameter(description = "input-nanopubs")
private List<File> inputNanopubs = new ArrayList<File>();
@com.beust.jcommander.Parameter(names = "-o", description = "Output file")
private File outputFile;
@com.beust.jcommander.Parameter(names = "--in-format", description = "Format of the input nanopubs: trig, nq, trix, trig.gz, ...")
private String inFormat;
@com.beust.jcommander.Parameter(names = "-i", description = "Property URIs to ignore, separated by '|' (has no effect if -d is set)")
private String ignoreProperties;
@com.beust.jcommander.Parameter(names = "-h", description = "Topic handler class")
private String handlerClass;
public static void main(String[] args) {
NanopubImpl.ensureLoaded();
Topic obj = new Topic();
JCommander jc = new JCommander(obj);
try {
jc.parse(args);
} catch (ParameterException ex) {
jc.usage();
System.exit(1);
}
obj.init();
try {
obj.run();
} catch (Exception ex) {
ex.printStackTrace();
System.exit(1);
}
}
public static Topic getInstance(String args) throws ParameterException {
NanopubImpl.ensureLoaded();
if (args == null) args = "";
Topic obj = new Topic();
JCommander jc = new JCommander(obj);
jc.parse(args.trim().split(" "));
obj.init();
return obj;
}
private RDFFormat rdfInFormat;
private OutputStream outputStream = System.out;
private BufferedWriter writer;
private TopicHandler topicHandler;
private void init() {
if (handlerClass != null && !handlerClass.isEmpty()) {
String detectorClassName = handlerClass;
if (!handlerClass.contains(".")) {
detectorClassName = "org.nanopub.op.topic." + handlerClass;
}
try {
topicHandler = (TopicHandler) Class.forName(detectorClassName).getConstructor().newInstance();
} catch (ReflectiveOperationException ex) {
throw new RuntimeException(ex);
}
} else {
topicHandler = new DefaultTopics(ignoreProperties);
}
}
public void run() throws IOException, RDFParseException, RDFHandlerException,
MalformedNanopubException, TrustyUriException {
if (inputNanopubs == null || inputNanopubs.isEmpty()) {
throw new ParameterException("No input files given");
}
for (File inputFile : inputNanopubs) {
if (inFormat != null) {
rdfInFormat = Rio.getParserFormatForFileName("file." + inFormat).orElse(null);
} else {
rdfInFormat = Rio.getParserFormatForFileName(inputFile.toString()).orElse(null);
}
if (outputFile != null) {
if (outputFile.getName().endsWith(".gz")) {
outputStream = new GZIPOutputStream(new FileOutputStream(outputFile));
} else {
outputStream = new FileOutputStream(outputFile);
}
}
writer = new BufferedWriter(new OutputStreamWriter(outputStream));
| MultiNanopubRdfHandler.process(rdfInFormat, inputFile, new NanopubHandler() { | 2 |
zerg000000/mario-ai | src/main/java/ch/idsia/scenarios/test/EvolveSingle.java | [
"public class SimpleMLPAgent implements Agent, Evolvable\n{\n\nprivate MLP mlp;\nprivate String name = \"SimpleMLPAgent\";\nfinal int numberOfOutputs = 6;\nfinal int numberOfInputs = 10;\nprivate Environment environment;\n\n/*final*/\nprotected byte[][] levelScene;\n/*final */\nprotected byte[][] enemies;\nprotected byte[][] mergedObservation;\n\nprotected float[] marioFloatPos = null;\nprotected float[] enemiesFloatPos = null;\n\nprotected int[] marioState = null;\n\nprotected int marioStatus;\nprotected int marioMode;\nprotected boolean isMarioOnGround;\nprotected boolean isMarioAbleToJump;\nprotected boolean isMarioAbleToShoot;\nprotected boolean isMarioCarrying;\nprotected int getKillsTotal;\nprotected int getKillsByFire;\nprotected int getKillsByStomp;\nprotected int getKillsByShell;\n\n// values of these variables could be changed during the Agent-Environment interaction.\n// Use them to get more detailed or less detailed description of the level.\n// for information see documentation for the benchmark <link: marioai.org/marioaibenchmark/zLevels\nint zLevelScene = 1;\nint zLevelEnemies = 0;\n\n\npublic SimpleMLPAgent()\n{\n mlp = new MLP(numberOfInputs, 10, numberOfOutputs);\n}\n\nprivate SimpleMLPAgent(MLP mlp)\n{\n this.mlp = mlp;\n}\n\npublic Evolvable getNewInstance()\n{\n return new SimpleMLPAgent(mlp.getNewInstance());\n}\n\npublic Evolvable copy()\n{\n return new SimpleMLPAgent(mlp.copy());\n}\n\npublic void integrateObservation(Environment environment)\n{\n this.environment = environment;\n levelScene = environment.getLevelSceneObservationZ(zLevelScene);\n enemies = environment.getEnemiesObservationZ(zLevelEnemies);\n mergedObservation = environment.getMergedObservationZZ(1, 0);\n\n this.marioFloatPos = environment.getMarioFloatPos();\n this.enemiesFloatPos = environment.getEnemiesFloatPos();\n this.marioState = environment.getMarioState();\n\n // It also possible to use direct methods from Environment interface.\n //\n marioStatus = marioState[0];\n marioMode = marioState[1];\n isMarioOnGround = marioState[2] == 1;\n isMarioAbleToJump = marioState[3] == 1;\n isMarioAbleToShoot = marioState[4] == 1;\n isMarioCarrying = marioState[5] == 1;\n getKillsTotal = marioState[6];\n getKillsByFire = marioState[7];\n getKillsByStomp = marioState[8];\n getKillsByShell = marioState[9];\n}\n\npublic void giveIntermediateReward(float intermediateReward)\n{\n\n}\n\npublic void reset()\n{ mlp.reset(); }\n\npublic void setObservationDetails(final int rfWidth, final int rfHeight, final int egoRow, final int egoCol)\n{}\n\npublic void mutate()\n{ mlp.mutate(); }\n\npublic boolean[] getAction()\n{\n// double[] inputs = new double[]{probe(-1, -1, levelScene), probe(0, -1, levelScene), probe(1, -1, levelScene),\n// probe(-1, 0, levelScene), probe(0, 0, levelScene), probe(1, 0, levelScene),\n// probe(-1, 1, levelScene), probe(0, 1, levelScene), probe(1, 1, levelScene),\n// 1};\n double[] inputs = new double[]{probe(-1, -1, mergedObservation), probe(0, -1, mergedObservation), probe(1, -1, mergedObservation),\n probe(-1, 0, mergedObservation), probe(0, 0, mergedObservation), probe(1, 0, mergedObservation),\n probe(-1, 1, mergedObservation), probe(0, 1, mergedObservation), probe(1, 1, mergedObservation),\n 1};\n double[] outputs = mlp.propagate(inputs);\n boolean[] action = new boolean[numberOfOutputs];\n for (int i = 0; i < action.length; i++)\n action[i] = outputs[i] > 0;\n return action;\n}\n\npublic String getName()\n{\n return name;\n}\n\npublic void setName(String name)\n{\n this.name = name;\n}\n\nprivate double probe(int x, int y, byte[][] scene)\n{\n int realX = x + 11;\n int realY = y + 11;\n return (scene[realX][realY] != 0) ? 1 : 0;\n}\n}",
"public abstract class GlobalOptions\n{\npublic static final int primaryVerionUID = 0;\npublic static final int minorVerionUID = 1;\npublic static final int minorSubVerionID = 9;\n\npublic static boolean areLabels = false;\npublic static boolean isCameraCenteredOnMario = false;\npublic static Integer FPS = 24;\npublic static int MaxFPS = 100;\npublic static boolean areFrozenCreatures = false;\n\npublic static boolean isVisualization = true;\npublic static boolean isGameplayStopped = false;\npublic static boolean isFly = false;\n\nprivate static GameViewer GameViewer = null;\n// public static boolean isTimer = true;\n\npublic static int mariosecondMultiplier = 15;\n\npublic static boolean isPowerRestoration;\n\n// required for rendering grid in ch/idsia/benchmark/mario/engine/sprites/Sprite.java\npublic static int receptiveFieldWidth = 19;\npublic static int receptiveFieldHeight = 19;\npublic static int marioEgoCol = 9;\npublic static int marioEgoRow = 9;\n\nprivate static MarioVisualComponent marioVisualComponent;\npublic static int VISUAL_COMPONENT_WIDTH = 320;\npublic static int VISUAL_COMPONENT_HEIGHT = 240;\n\npublic static boolean isShowReceptiveField = false;\npublic static boolean isScale2x = false;\npublic static boolean isRecording = false;\npublic static boolean isReplaying = false;\n\npublic static int getPrimaryVersionUID()\n{\n return primaryVerionUID;\n}\n\npublic static int getMinorVersionUID()\n{\n return minorVerionUID;\n}\n\npublic static int getMinorSubVersionID()\n{\n return minorSubVerionID;\n}\n\npublic static String getBenchmarkName()\n{\n return \"[~ Mario AI Benchmark ~\" + GlobalOptions.getVersionUID() + \"]\";\n}\n\npublic static String getVersionUID()\n{\n return \" \" + getPrimaryVersionUID() + \".\" + getMinorVersionUID() + \".\" + getMinorSubVersionID();\n}\n\npublic static void registerMarioVisualComponent(MarioVisualComponent mc)\n{\n marioVisualComponent = mc;\n}\n\npublic static void registerGameViewer(GameViewer gv)\n{\n GameViewer = gv;\n}\n\npublic static void AdjustMarioVisualComponentFPS()\n{\n if (marioVisualComponent != null)\n marioVisualComponent.adjustFPS();\n}\n\npublic static void gameViewerTick()\n{\n if (GameViewer != null)\n GameViewer.tick();\n}\n\npublic static String getDateTime(Long d)\n{\n final DateFormat dateFormat = (d == null) ? new SimpleDateFormat(\"yyyy/MM/dd HH:mm:ss:ms\") :\n new SimpleDateFormat(\"HH:mm:ss:ms\");\n if (d != null)\n dateFormat.setTimeZone(TimeZone.getTimeZone(\"GMT\"));\n final Date date = (d == null) ? new Date() : new Date(d);\n return dateFormat.format(date);\n}\n\nfinal static private DateFormat dateFormat = new SimpleDateFormat(\"yyyy-MM-dd_HH-mm-ss\");\n\npublic static String getTimeStamp()\n{\n return dateFormat.format(new Date());\n}\n\npublic static void changeScale2x()\n{\n if (marioVisualComponent == null)\n return;\n\n isScale2x = !isScale2x;\n marioVisualComponent.width *= isScale2x ? 2 : 0.5;\n marioVisualComponent.height *= isScale2x ? 2 : 0.5;\n marioVisualComponent.changeScale2x();\n}\n}",
"public final class ProgressTask extends BasicTask implements Task, Cloneable\n{\nprivate int uniqueSeed;\nprivate int fitnessEvaluations = 0;\npublic int uid;\nprivate String fileTimeStamp = \"-uid-\" + uid + \"-\" + GlobalOptions.getTimeStamp();\n\n// private int startingSeed;\n\npublic ProgressTask(MarioAIOptions evaluationOptions)\n{\n super(evaluationOptions);\n System.out.println(\"evaluationOptions = \" + evaluationOptions);\n setOptionsAndReset(evaluationOptions);\n}\n\npublic int totalEpisodes = 0;\n\nprivate float evaluateSingleLevel(int ld, int tl, int ls, boolean vis, Agent controller)\n{\n this.totalEpisodes++;\n\n float distanceTravelled = 0;\n options.setAgent(controller);\n// options.setLevelDifficulty(ld);\n// options.setTimeLimit(tl);\n// options.setLevelRandSeed(ls);\n// options.setVisualization(vis);\n// options.setFPS(vis ? 42 : 100);\n// this.setAgent(controller);\n this.setOptionsAndReset(options);\n this.runSingleEpisode(1);\n distanceTravelled += this.getEnvironment().getEvaluationInfo().computeDistancePassed();\n return distanceTravelled;\n}\n\npublic int evaluate(Agent controller)\n{\n// controller.reset();\n// options.setLevelRandSeed(startingSeed++);\n// System.out.println(\"controller = \" + controller);\n int fitn = (int) this.evaluateSingleLevel(0, 40, this.uniqueSeed, false, controller);\n// System.out.println(\"fitn = \" + fitn);\n// if (fitn > 1000)\n// fitn = this.evaluateSingleLevel(0, 150, this.uniqueSeed, false, controller);\n//// System.out.println(\"fitn2 = \" + fitn);\n// if (fitn > 4000)\n// fitn = 10000 + this.evaluateSingleLevel(1, 150, this.uniqueSeed, false, controller);\n//// System.out.println(\"fitn3 = \" + fitn);\n// if (fitn > 14000)\n// fitn = 20000 + this.evaluateSingleLevel(3, 150, this.uniqueSeed, false, controller);\n// if (fitn > 24000)\n// {\n//// this.evaluateSingleLevel(3, 150, this.uniqueSeed, true, controller);\n// fitn = 40000 + this.evaluateSingleLevel(5, 160, this.uniqueSeed, false, controller);\n// }\n//// if (fitn > 34000)\n//// fitn = 40000 + this.evaluateSingleLevel(5, 160, this.uniqueSeed, false, controller);\n// if (fitn > 44000)\n// fitn = 50000 + this.evaluateSingleLevel(7, 160, this.uniqueSeed, false, controller);\n\n this.uniqueSeed += 1;\n this.fitnessEvaluations++;\n this.dumpFitnessEvaluation(fitn, \"fitnesses-\");\n return fitn;\n}\n\npublic void dumpFitnessEvaluation(float fitness, String fileName)\n{\n try\n {\n BufferedWriter out = new BufferedWriter(new FileWriter(fileName + fileTimeStamp + \".txt\", true));\n out.write(this.fitnessEvaluations + \" \" + fitness + \"\\n\");\n out.close();\n } catch (IOException e)\n {\n e.printStackTrace();\n }\n}\n\npublic void doEpisodes(int amount, boolean verbose, final int repetitionsOfSingleEpisode)\n{\n System.out.println(\"amount = \" + amount);\n}\n\npublic boolean isFinished()\n{\n System.out.println(\"options = \" + options);\n return false;\n}\n\n}",
"public interface Evolvable\n{\n\n/**\n * Produces a new instance of the same <code>Evolvable</code>, all the parameters\n * (e.g. mutation rate, limits etc.) must be copied to the new object.\n * <p/>\n * The <code>EA</code> will produce the initial population adding to this first\n * <code>Evolvable</code> as many others as needed, generated by this method.<br>\n * Any random initialization should therefore be placed here.\n *\n * @return the <code>new Evolvable</code>.\n */\npublic Evolvable getNewInstance();\n\n/**\n * Returns a deep copy (i.e. as deep as possible) of the <code>Evolvable</code>.\n *\n * @return the copy.\n */\npublic Evolvable copy();\n\n/**\n * Resets the <code>Evolvable</code> to its default state (e.g. reset a recurrent network).\n */\npublic void reset();\n\n/**\n * Applies the predefined mutation to the <code>Evolvable</code>.\n */\npublic void mutate();\n\n/**\n * Produces a suitable <code>String</code> representation of the <code>Evolvable</code>.\n *\n * @return the info.\n */\npublic String toString();\n}",
"public class Stats\n{\nfinal static int numberOfTrials = 100;\n\npublic static void main(String[] args)\n{\n Agent controller = AgentsPool.loadAgent(args[0], false);\n final int startingSeed = Integer.parseInt(args[1]);\n doStats(controller, startingSeed);\n //System.exit(0);\n}\n\npublic static void doStats(Agent agent, int startingSeed)\n{\n TimingAgent controller = new TimingAgent(agent);\n// RegisterableAgent.registerAgent (controller);\n SimulationOptions options = new MarioAIOptions(new String[0]);\n\n// options.setEvaluationQuota(1);\n options.setVisualization(false);\n options.setFPS(GlobalOptions.MaxFPS);\n System.out.println(\"Testing controller \" + controller + \" with starting seed \" + startingSeed);\n\n double competitionScore = 0;\n\n competitionScore += testConfig(controller, options, startingSeed, 0, true);\n competitionScore += testConfig(controller, options, startingSeed, 0, false);\n competitionScore += testConfig(controller, options, startingSeed, 3, true);\n competitionScore += testConfig(controller, options, startingSeed, 3, false);\n competitionScore += testConfig(controller, options, startingSeed, 5, true);\n competitionScore += testConfig(controller, options, startingSeed, 5, false);\n //testConfig (controller, options, startingSeed, 8, true);\n //testConfig (controller, options, startingSeed, 8, false);\n competitionScore += testConfig(controller, options, startingSeed, 10, true);\n competitionScore += testConfig(controller, options, startingSeed, 10, false);\n //testConfig (controller, options, startingSeed, 15, true);\n //testConfig (controller, options, startingSeed, 15, false);\n //testConfig (controller, options, startingSeed, 20, true);\n //testConfig (controller, options, startingSeed, 20, false);\n System.out.println(\"Stats sum: \" + competitionScore);\n}\n\npublic static double testConfig(TimingAgent controller, SimulationOptions options, int seed, int level, boolean paused)\n{\n options.setLevelDifficulty(level);\n StatisticalSummary ss = test(controller, options, seed);\n System.out.printf(\"Level %d %s %.4f (%.4f) (min %.4f max %.4f) (avg time %.4f)\\n\",\n level, paused ? \"paused\" : \"unpaused\",\n ss.mean(), ss.sd(), ss.min(), ss.max(), controller.averageTimeTaken());\n return ss.mean();\n}\n\n\npublic static StatisticalSummary test(Agent controller, SimulationOptions options, int seed)\n{\n StatisticalSummary ss = new StatisticalSummary();\n for (int i = 0; i < numberOfTrials; i++)\n {\n options.setLevelRandSeed(seed + i);\n controller.reset();\n options.setAgent(controller);\n// Evaluator evaluator = new Evaluator (options);\n// EvaluationInfo result = evaluator.evaluate().get(0);\n// ss.add (result.computeDistancePassed());\n }\n return ss;\n}\n\n\n}",
"public final class MarioAIOptions extends SimulationOptions\n{\nprivate static final HashMap<String, MarioAIOptions> CmdLineOptionsMapString = new HashMap<String, MarioAIOptions>();\nprivate String optionsAsString = \"\";\n\nfinal private Point marioInitialPos = new Point();\n\npublic MarioAIOptions(String[] args)\n{\n super();\n this.setArgs(args);\n}\n\n// @Deprecated\n\npublic MarioAIOptions(String args)\n{\n //USE MarioAIOptions.getCmdLineOptionsClassByString(String args) method\n super();\n this.setArgs(args);\n}\n\npublic MarioAIOptions()\n{\n super();\n this.setArgs(\"\");\n}\n\npublic void setArgs(String argString)\n{\n if (!\"\".equals(argString))\n this.setArgs(argString.trim().split(\"\\\\s+\"));\n else\n this.setArgs((String[]) null);\n}\n\npublic String asString()\n{\n return optionsAsString;\n}\n\npublic void setArgs(String[] args)\n{\n// if (args.length > 0 && !args[0].startsWith(\"-\") /*starts with a path to agent then*/)\n// {\n// this.setAgent(args[0]);\n//\n// String[] shiftedargs = new String[args.length - 1];\n// System.arraycopy(args, 1, shiftedargs, 0, args.length - 1);\n// this.setUpOptions(shiftedargs);\n// }\n// else\n if (args != null)\n for (String s : args)\n optionsAsString += s + \" \";\n\n this.setUpOptions(args);\n\n if (isEcho())\n {\n this.printOptions(false);\n }\n GlobalOptions.receptiveFieldWidth = getReceptiveFieldWidth();\n GlobalOptions.receptiveFieldHeight = getReceptiveFieldHeight();\n if (getMarioEgoPosCol() == 9 && GlobalOptions.receptiveFieldWidth != 19)\n GlobalOptions.marioEgoCol = GlobalOptions.receptiveFieldWidth / 2;\n else\n GlobalOptions.marioEgoCol = getMarioEgoPosCol();\n if (getMarioEgoPosRow() == 9 && GlobalOptions.receptiveFieldHeight != 19)\n GlobalOptions.marioEgoRow = GlobalOptions.receptiveFieldHeight / 2;\n else\n GlobalOptions.marioEgoRow = getMarioEgoPosRow();\n\n GlobalOptions.VISUAL_COMPONENT_HEIGHT = getViewHeight();\n GlobalOptions.VISUAL_COMPONENT_WIDTH = getViewWidth();\n// Environment.ObsWidth = GlobalOptions.receptiveFieldWidth/2;\n// Environment.ObsHeight = GlobalOptions.receptiveFieldHeight/2;\n GlobalOptions.isShowReceptiveField = isReceptiveFieldVisualized();\n GlobalOptions.isGameplayStopped = isStopGamePlay();\n}\n\npublic float getMarioGravity()\n{\n // TODO: getMarioGravity, doublecheck if unit test is present and remove if fixed\n return f(getParameterValue(\"-mgr\"));\n}\n\npublic void setMarioGravity(float mgr)\n{\n setParameterValue(\"-mgr\", s(mgr));\n}\n\npublic float getWind()\n{\n return f(getParameterValue(\"-w\"));\n}\n\npublic void setWind(float wind)\n{\n setParameterValue(\"-w\", s(wind));\n}\n\npublic float getIce()\n{\n return f(getParameterValue(\"-ice\"));\n}\n\npublic void setIce(float ice)\n{\n setParameterValue(\"-ice\", s(ice));\n}\n\npublic float getCreaturesGravity()\n{\n // TODO: getCreaturesGravity, same as for mgr\n return f(getParameterValue(\"-cgr\"));\n}\n\npublic int getViewWidth()\n{\n return i(getParameterValue(\"-vw\"));\n}\n\npublic void setViewWidth(int width)\n{\n setParameterValue(\"-vw\", s(width));\n}\n\npublic int getViewHeight()\n{\n return i(getParameterValue(\"-vh\"));\n}\n\npublic void setViewHeight(int height)\n{\n setParameterValue(\"-vh\", s(height));\n}\n\npublic void printOptions(boolean singleLine)\n{\n System.out.println(\"\\n[MarioAI] : Options have been set to:\");\n for (Map.Entry<String, String> el : optionsHashMap.entrySet())\n if (singleLine)\n System.out.print(el.getKey() + \" \" + el.getValue() + \" \");\n else\n System.out.println(el.getKey() + \" \" + el.getValue() + \" \");\n}\n\npublic static MarioAIOptions getOptionsByString(String argString)\n{\n // TODO: verify validity of this method, add unit tests\n if (CmdLineOptionsMapString.get(argString) == null)\n {\n final MarioAIOptions value = new MarioAIOptions(argString.trim().split(\"\\\\s+\"));\n CmdLineOptionsMapString.put(argString, value);\n return value;\n }\n return CmdLineOptionsMapString.get(argString);\n}\n\npublic static MarioAIOptions getDefaultOptions()\n{\n return getOptionsByString(\"\");\n}\n\npublic boolean isToolsConfigurator()\n{\n return b(getParameterValue(\"-tc\"));\n}\n\npublic boolean isGameViewer()\n{\n return b(getParameterValue(\"-gv\"));\n}\n\npublic void setGameViewer(boolean gv)\n{\n setParameterValue(\"-gv\", s(gv));\n}\n\npublic boolean isGameViewerContinuousUpdates()\n{\n return b(getParameterValue(\"-gvc\"));\n}\n\npublic void setGameViewerContinuousUpdates(boolean gvc)\n{\n setParameterValue(\"-gvc\", s(gvc));\n}\n\npublic boolean isEcho()\n{\n return b(getParameterValue(\"-echo\"));\n}\n\npublic void setEcho(boolean echo)\n{\n setParameterValue(\"-echo\", s(echo));\n}\n\npublic boolean isStopGamePlay()\n{\n return b(getParameterValue(\"-stop\"));\n}\n\npublic void setStopGamePlay(boolean stop)\n{\n setParameterValue(\"-stop\", s(stop));\n}\n\npublic float getJumpPower()\n{\n return f(getParameterValue(\"-jp\"));\n}\n\npublic void setJumpPower(float jp)\n{\n setParameterValue(\"-jp\", s(jp));\n}\n\npublic int getReceptiveFieldWidth()\n{\n int ret = i(getParameterValue(\"-rfw\"));\n//\n// if (ret % 2 == 0)\n// {\n// System.err.println(\"\\n[MarioAI WARNING] : Wrong value for receptive field width: \" + ret++ +\n// \" ; receptive field width set to \" + ret);\n// setParameterValue(\"-rfw\", s(ret));\n// }\n return ret;\n}\n\npublic void setReceptiveFieldWidth(int rfw)\n{\n setParameterValue(\"-rfw\", s(rfw));\n}\n\npublic int getReceptiveFieldHeight()\n{\n int ret = i(getParameterValue(\"-rfh\"));\n// if (ret % 2 == 0)\n// {\n// System.err.println(\"\\n[MarioAI WARNING] : Wrong value for receptive field height: \" + ret++ +\n// \" ; receptive field height set to \" + ret);\n// setParameterValue(\"-rfh\", s(ret));\n// }\n return ret;\n}\n\npublic void setReceptiveFieldHeight(int rfh)\n{\n setParameterValue(\"-rfh\", s(rfh));\n}\n\npublic boolean isReceptiveFieldVisualized()\n{\n return b(getParameterValue(\"-srf\"));\n}\n\npublic void setReceptiveFieldVisualized(boolean srf)\n{\n setParameterValue(\"-srf\", s(srf));\n}\n\npublic Point getMarioInitialPos()\n{\n marioInitialPos.x = i(getParameterValue(\"-mix\"));\n marioInitialPos.y = i(getParameterValue(\"-miy\"));\n return marioInitialPos;\n}\n\npublic void reset()\n{\n optionsHashMap.clear();\n}\n\npublic int getMarioEgoPosRow()\n{\n return i(getParameterValue(\"-mer\"));\n}\n\npublic int getMarioEgoPosCol()\n{\n return i(getParameterValue(\"-mec\"));\n}\n\npublic int getExitX()\n{\n return i(getParameterValue(\"-ex\"));\n}\n\npublic int getExitY()\n{\n return i(getParameterValue(\"-ey\"));\n}\n\npublic void setExitX(int x)\n{\n setParameterValue(\"-ex\", s(x));\n}\n\npublic void setExitY(int y)\n{\n setParameterValue(\"-ey\", s(y));\n}\n}"
] | import ch.idsia.evolution.Evolvable;
import ch.idsia.evolution.ea.ES;
import ch.idsia.scenarios.oldscenarios.Stats;
import ch.idsia.tools.MarioAIOptions;
import ch.idsia.utils.wox.serial.Easy;
import ch.idsia.agents.learning.SimpleMLPAgent;
import ch.idsia.benchmark.mario.engine.GlobalOptions;
import ch.idsia.benchmark.tasks.ProgressTask; | /*
* Copyright (c) 2009-2010, Sergey Karakovskiy and Julian Togelius
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* Neither the name of the Mario AI nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package ch.idsia.scenarios.test;
/**
* Created by IntelliJ IDEA.
* User: julian
* Date: Jun 14, 2009
* Time: 2:15:51 PM
*/
public class EvolveSingle
{
final static int generations = 100;
final static int populationSize = 100;
public static void main(String[] args)
{ | MarioAIOptions options = new MarioAIOptions(new String[0]); | 5 |
sourcepole/jasperreports-wms-component | jasperreports-wms-component/src/main/java/com/sourcepole/jasperreports/wmsmap/fill/WmsMapFillComponent.java | [
"public static Renderable getImageRenderable(\n JasperReportsContext jasperReportsContext, JRGenericPrintElement element)\n throws MalformedURLException, IOException, JRException {\n WmsRequestBuilder requestBuilder = mapRequestBuilder(element);\n return getImageRenderable(jasperReportsContext, element.getKey(),\n requestBuilder);\n}",
"public static WmsRequestBuilder createGetMapRequest(String serviceUrl) {\n WmsRequestBuilder builder = new WmsRequestBuilder();\n builder.parameters.put(WmsRequestParameter.WMS_URL, serviceUrl);\n builder.parameters.put(WmsRequestParameter.REQUEST,\n WmsRequestType.GET_MAP.getType());\n return builder;\n}",
"public interface WmsMapComponent extends Component, JRCloneable {\n\n JRExpression getBBoxExpression();\n\n JRExpression getLayersExpression();\n\n JRExpression getStylesExpression();\n\n JRExpression getUrlParametersExpression();\n\n EvaluationTimeEnum getEvaluationTime();\n\n String getEvaluationGroup();\n\n String getWmsServiceUrl();\n\n String getWmsVersion();\n\n String getSrs();\n\n String getImageType();\n\n Boolean getTransparent();\n\n}",
"public final class WmsMapPrintElement {\n /**\n * The name of WMS map generic elements.\n */\n public static final String WMS_MAP_ELEMENT_NAME = \"wmsmap\";\n\n /**\n * The qualified type of WMS map generic elements.\n */\n public static final JRGenericElementType WMS_MAP_ELEMENT_TYPE =\n new JRGenericElementType(\n ComponentsExtensionsRegistryFactory.NAMESPACE,\n WMS_MAP_ELEMENT_NAME);\n\n /** Parameter {@code wmsServiceUrl}. */\n public static final String PARAMETER_WMS_SERVICE_URL = \"wmsServiceUrl\";\n\n /** Parameter {@code wmsVersion}. */\n public static final String PARAMETER_WMS_VERSION = \"wmsVersion\";\n\n /** Parameter {@code srs}. */\n public static final String PARAMETER_SRS = \"srs\";\n\n /** Parameter {@code transparent}. */\n public static final String PARAMETER_TRANSPARENT = \"transparent\";\n\n /** Parameter {@code BBox}. */\n public static final String PARAMETER_BBOX = \"bbox\";\n\n /** Parameter {@code layers}. */\n public static final String PARAMETER_LAYERS = \"layers\";\n\n /** Parameter {@code styles}. */\n public static final String PARAMETER_STYLES = \"styles\";\n\n public static final String PARAMETER_URL_PARAMETERS = \"urlParameters\";\n\n /** Parameter {@code imageType}. */\n public static final String PARAMETER_IMAGE_TYPE = \"imageType\";\n\n /** Parameter {@code cacheRenderer}. */\n public static final String PARAMETER_CACHE_RENDERER = \"cacheRenderer\";\n\n public static final String DEFAULT_BBOX = \"\";\n\n private WmsMapPrintElement()\n {\n }\n}",
"public class WmsRequestBuilder {\n\n private static final String UTF_8 = \"UTF-8\";\n\n private final Map<WmsRequestParameter, String> parameters =\n new HashMap<WmsRequestParameter, String>();\n\n public static WmsRequestBuilder createGetMapRequest(String serviceUrl) {\n WmsRequestBuilder builder = new WmsRequestBuilder();\n builder.parameters.put(WmsRequestParameter.WMS_URL, serviceUrl);\n builder.parameters.put(WmsRequestParameter.REQUEST,\n WmsRequestType.GET_MAP.getType());\n return builder;\n }\n\n public static WmsRequestBuilder createGetMapRequest(\n Map<WmsRequestParameter, String> params) {\n WmsRequestBuilder builder = new WmsRequestBuilder();\n builder.parameters.putAll(params);\n return builder;\n }\n\n public WmsRequestBuilder layers(String layers) {\n parameters.put(WmsRequestParameter.LAYERS, layers);\n return this;\n }\n\n public WmsRequestBuilder styles(String styles) {\n parameters.put(WmsRequestParameter.STYLE, styles);\n return this;\n }\n\n public WmsRequestBuilder format(String format) {\n parameters.put(WmsRequestParameter.FORMAT, format);\n return this;\n }\n\n public WmsRequestBuilder boundingBox(String boundingBox) {\n parameters.put(WmsRequestParameter.BBOX, boundingBox);\n return this;\n }\n\n public WmsRequestBuilder transparent(boolean transparent) {\n parameters.put(WmsRequestParameter.TRANSPARENT, Boolean\n .valueOf(transparent)\n .toString());\n return this;\n }\n\n public WmsRequestBuilder version(String version) {\n parameters.put(WmsRequestParameter.VERSION, version);\n return this;\n }\n\n public WmsRequestBuilder srsCrs(String srsCrs) {\n parameters.put(WmsRequestParameter.SRS_CRS, srsCrs);\n return this;\n }\n\n public WmsRequestBuilder urlParameters(String urlParameters) {\n parameters.put(WmsRequestParameter.URL_PARAMETERS, urlParameters);\n return this;\n }\n\n public WmsRequestBuilder width(int width) {\n parameters\n .put(WmsRequestParameter.WIDTH, Integer.valueOf(width).toString());\n return this;\n }\n\n public WmsRequestBuilder height(int height) {\n parameters.put(WmsRequestParameter.HEIGHT, Integer.valueOf(height)\n .toString());\n return this;\n }\n\n public URL toMapUrl() throws MalformedURLException {\n StringBuilder url = new StringBuilder();\n Map<WmsRequestParameter, String> params =\n new LinkedHashMap<WmsRequestParameter, String>(this.parameters);\n String wmsUrl = params.remove(WmsRequestParameter.WMS_URL).toString();\n url.append(wmsUrl);\n if (wmsUrl.indexOf(\"?\") == -1) {\n url.append(\"?\");\n }\n java.util.List<String> paramList = new ArrayList<String>();\n\n for (WmsRequestParameter parameter : WmsRequestParameter.parameterValues()) {\n if (parameter == WmsRequestParameter.URL_PARAMETERS) {\n continue;\n }\n Object defaultValue = parameter.defaultValue(params);\n if (params.containsKey(parameter) || parameter.isRequired(params)\n || defaultValue != null) {\n String parameterName = parameter.parameterName(params);\n Object value = parameter.extract(params);\n paramList.add(encodeParameter(parameterName, value.toString()));\n }\n }\n Iterator<String> iterator = paramList.iterator();\n while (iterator.hasNext()) {\n String param = iterator.next();\n url.append(param);\n if (iterator.hasNext()) {\n url.append(\"&\");\n }\n }\n Object urlParams = params.remove(WmsRequestParameter.URL_PARAMETERS);\n if (urlParams != null) {\n String extraUrlParams = urlParams.toString();\n if (!extraUrlParams.startsWith(\"&\")) {\n url.append(\"&\");\n }\n url.append(extraUrlParams);\n }\n return new URL(url.toString());\n }\n\n private static String encodeParameter(String key, Object value) {\n try {\n String encName = encode(key, UTF_8);\n String encValue = encode(value.toString(), UTF_8);\n String encodedParameter = String.format(\"%s=%s\", encName, encValue);\n return encodedParameter;\n } catch (UnsupportedEncodingException e) {\n throw new RuntimeException(\"Encoding UTF-8 not supported on runtime\");\n }\n }\n}",
"public enum WmsRequestParameter {\n\n /** Parameter for the WMS service base URL. */\n WMS_URL(true, null),\n\n /** Parameter {@code SERVICE}. */\n SERVICE(false, \"WMS\"),\n\n /** Parameter {@code REQUEST} type. */\n REQUEST(false, WmsRequestType.GET_MAP),\n\n /** Parameter {@code LAYERS}. */\n LAYERS(true, null),\n\n /** Parameter {@code STYLE}. */\n STYLE(false, null) {\n @Override\n Object defaultValue(Map<WmsRequestParameter, String> input) {\n String layers = input.get(LAYERS);\n if (layers == null) {\n return \"\";\n }\n return layers.replaceAll(\"[^,]\", \"\");\n }\n },\n\n /** Parameter {@code FORMAT}. */\n FORMAT(false, \"image/png\"),\n\n /** Parameter {@code BBOX}. */\n BBOX(true, null),\n\n /** Parameter {@code VERSION}. */\n VERSION(false, new WmsVersion(1, 1, 1)) {\n @Override\n Object extract(Map<WmsRequestParameter, String> input) {\n if (!input.containsKey(this)) {\n return defaultValue(input);\n }\n String version = input.get(WmsRequestParameter.VERSION);\n return new WmsVersion(version);\n }\n },\n\n /**\n * Parameter {@code SRS} or {@code CRS}. SRS is used if version is < 1.3;\n * CRS for version >= 1.3.\n */\n SRS_CRS(true, null) {\n @Override\n String parameterName(Map<WmsRequestParameter, String> input) {\n WmsVersion version = (WmsVersion) WmsRequestParameter.VERSION\n .extract(input);\n if (version.compareTo(wmsVersion13) == -1) {\n return \"SRS\";\n }\n return \"CRS\";\n }\n },\n\n /** Parameter {@code WIDTH}. */\n WIDTH(true, null),\n\n /** Parameter {@code HEIGHT}. */\n HEIGHT(true, null),\n\n /** Parameter {@code TRANSPARENT}. */\n TRANSPARENT(false, Boolean.FALSE) {\n @Override\n Object extract(Map<WmsRequestParameter, String> input) {\n return super.extract(input).toString().toUpperCase(Locale.US);\n }\n },\n\n /** Extra URL parameters to append to a constructed URL. */\n URL_PARAMETERS(false, null);\n\n private static final WmsVersion wmsVersion13 = new WmsVersion(1, 3, 0);\n\n private boolean required = false;\n private final Object defaultValue;\n\n private WmsRequestParameter(boolean required, Object defaultValue) {\n this.required = required;\n this.defaultValue = defaultValue;\n }\n\n /**\n * Extracts an input parameter and returns it's value or a default value.\n */\n Object extract(Map<WmsRequestParameter, String> input) {\n Object value = input.get(this);\n if (value == null) {\n if (isRequired(input)) {\n throw new IllegalStateException(\n String.format(\"Missing required parameter: %s\", this.name()));\n }\n return defaultValue(input);\n }\n return value;\n }\n\n /**\n * Returns the default value for the parameter.\n */\n Object defaultValue(Map<WmsRequestParameter, String> input) {\n return defaultValue;\n }\n\n /**\n * Returns the actual HTTP parameter name.\n */\n String parameterName(Map<WmsRequestParameter, String> input) {\n return this.name();\n }\n\n /** Returns if the parameter is required. */\n boolean isRequired(Map<WmsRequestParameter, String> input) {\n return this.required;\n }\n\n public static WmsRequestParameter[] parameterValues() {\n return new WmsRequestParameter[] {\n SERVICE,\n REQUEST,\n VERSION,\n BBOX,\n LAYERS,\n STYLE,\n SRS_CRS,\n FORMAT,\n HEIGHT,\n WIDTH,\n TRANSPARENT\n };\n }\n\n}"
] | import static com.sourcepole.jasperreports.wmsmap.WmsMapElementImageProvider.getImageRenderable;
import static com.sourcepole.jasperreports.wmsmap.WmsRequestBuilder.createGetMapRequest;
import java.io.IOException;
import java.net.MalformedURLException;
import net.sf.jasperreports.engine.JRComponentElement;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRGenericPrintElement;
import net.sf.jasperreports.engine.JRPrintElement;
import net.sf.jasperreports.engine.Renderable;
import net.sf.jasperreports.engine.component.BaseFillComponent;
import net.sf.jasperreports.engine.component.FillPrepareResult;
import net.sf.jasperreports.engine.fill.JRFillObjectFactory;
import net.sf.jasperreports.engine.fill.JRTemplateGenericElement;
import net.sf.jasperreports.engine.fill.JRTemplateGenericPrintElement;
import net.sf.jasperreports.engine.type.EvaluationTimeEnum;
import com.sourcepole.jasperreports.wmsmap.WmsMapComponent;
import com.sourcepole.jasperreports.wmsmap.WmsMapPrintElement;
import com.sourcepole.jasperreports.wmsmap.WmsRequestBuilder;
import com.sourcepole.jasperreports.wmsmap.WmsRequestParameter; | /*
* JasperReports/iReport WMS Component
*
* Copyright (C) 2013 Sourcepole AG
*
* JasperReports/iReport WMS Component is free software: you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* JasperReports/iReport WMS Component 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with JasperReports/iReport WMS Component.
* If not, see <http://www.gnu.org/licenses/>.
*/
package com.sourcepole.jasperreports.wmsmap.fill;
public class WmsMapFillComponent extends BaseFillComponent {
JRFillObjectFactory factory;
| private final WmsMapComponent mapComponent; | 2 |
ZerothAngel/ToHPluginUtils | src/main/java/org/tyrannyofheaven/bukkit/util/uuid/CommandUuidResolver.java | [
"public static String colorize(String text) {\n if (text == null) return null;\n\n // Works best with interned strings\n String cacheResult = colorizeCache.get(text);\n if (cacheResult != null) return cacheResult;\n\n StringBuilder out = new StringBuilder();\n\n ColorizeState state = ColorizeState.TEXT;\n StringBuilder color = null;\n\n for (int i = 0; i < text.length(); i++) {\n char c = text.charAt(i);\n\n if (state == ColorizeState.TEXT) {\n if (c == '{') {\n state = ColorizeState.COLOR_OPEN;\n }\n else if (c == '}') {\n state = ColorizeState.COLOR_CLOSE;\n }\n else if (c == '`') {\n state = ColorizeState.COLOR_ESCAPE;\n }\n else {\n out.append(c);\n }\n }\n else if (state == ColorizeState.COLOR_OPEN) {\n if (c == '{') { // Escaped bracket\n out.append('{');\n state = ColorizeState.TEXT;\n }\n else if (Character.isUpperCase(c)) {\n // First character of color name\n color = new StringBuilder();\n color.append(c);\n state = ColorizeState.COLOR_NAME;\n }\n else {\n // Invalid\n throw new IllegalArgumentException(\"Invalid color name\");\n }\n }\n else if (state == ColorizeState.COLOR_NAME) {\n if (Character.isUpperCase(c) || c == '_') {\n color.append(c);\n }\n else if (c == '}') {\n ChatColor chatColor = ChatColor.valueOf(color.toString());\n out.append(chatColor);\n state = ColorizeState.TEXT;\n }\n else {\n // Invalid\n throw new IllegalArgumentException(\"Invalid color name\");\n }\n }\n else if (state == ColorizeState.COLOR_CLOSE) {\n // Optional, but for sanity's sake, to keep brackets matched\n if (c == '}') {\n out.append('}'); // Collapse to single bracket\n }\n else {\n out.append('}');\n out.append(c);\n }\n state = ColorizeState.TEXT;\n }\n else if (state == ColorizeState.COLOR_ESCAPE) {\n out.append(decodeColor(c));\n state = ColorizeState.TEXT;\n }\n else\n throw new AssertionError(\"Unknown ColorizeState\");\n }\n \n // End of string\n if (state == ColorizeState.COLOR_CLOSE) {\n out.append('}');\n }\n else if (state != ColorizeState.TEXT) {\n // Was in the middle of color name\n throw new IllegalArgumentException(\"Invalid color name\");\n }\n\n cacheResult = out.toString();\n colorizeCache.putIfAbsent(text, cacheResult);\n\n return cacheResult;\n}",
"public static void sendMessage(CommandSender sender, String format, Object... args) {\n String message = String.format(format, args);\n for (String line : message.split(\"\\n\")) {\n sender.sendMessage(line);\n }\n}",
"public static boolean hasText(String text) {\n return text != null && text.trim().length() > 0;\n}",
"public static void abortBatchProcessing() {\n if (isBatchProcessing())\n abortFlags.set(Boolean.TRUE);\n}",
"public static boolean isBatchProcessing() {\n return abortFlags.get() != null;\n}",
"public static UuidDisplayName parseUuidDisplayName(String name) {\n Matcher m = UUID_NAME_RE.matcher(name);\n if (m.matches()) {\n String uuidString = m.group(1);\n String displayName = m.group(2);\n \n if (uuidString.length() == 32)\n uuidString = shortUuidToLong(uuidString);\n UUID uuid;\n try {\n uuid = UUID.fromString(uuidString);\n }\n catch (IllegalArgumentException e) {\n return null;\n }\n return new UuidDisplayName(uuid, displayName);\n }\n return null;\n}"
] | import static org.tyrannyofheaven.bukkit.util.ToHMessageUtils.colorize;
import static org.tyrannyofheaven.bukkit.util.ToHMessageUtils.sendMessage;
import static org.tyrannyofheaven.bukkit.util.ToHStringUtils.hasText;
import static org.tyrannyofheaven.bukkit.util.command.reader.CommandReader.abortBatchProcessing;
import static org.tyrannyofheaven.bukkit.util.command.reader.CommandReader.isBatchProcessing;
import static org.tyrannyofheaven.bukkit.util.uuid.UuidUtils.parseUuidDisplayName;
import java.util.UUID;
import java.util.concurrent.Executor;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin; | /*
* Copyright 2014 ZerothAngel <[email protected]>
*
* 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 org.tyrannyofheaven.bukkit.util.uuid;
public class CommandUuidResolver {
private final Plugin plugin;
private final UuidResolver uuidResolver;
private final Executor executor;
private final boolean abortInline;
public CommandUuidResolver(Plugin plugin, UuidResolver uuidResolver, Executor executor, boolean abortInline) {
this.plugin = plugin;
this.uuidResolver = uuidResolver;
this.executor = executor;
this.abortInline = abortInline;
}
public void resolveUsername(CommandSender sender, String name, boolean skip, boolean forceInline, CommandUuidResolverHandler handler) {
if (sender == null)
throw new IllegalArgumentException("sender cannot be null");
if (handler == null)
throw new IllegalArgumentException("handler cannot be null");
if (skip || name == null) {
// Simple case: no need to resolve because skip is true or name is null, run inline
handler.process(sender, name, null, skip);
}
else {
// See if it's UUID or UUID/DisplayName
UuidDisplayName udn = parseUuidDisplayName(name);
if (udn != null) {
String displayName;
OfflinePlayer player = Bukkit.getOfflinePlayer(udn.getUuid());
if (player != null && player.getName() != null) {
// Use last known name
displayName = player.getName();
}
else {
// Default display name (either what was passed in or the UUID in string form) | displayName = hasText(udn.getDisplayName()) ? udn.getDisplayName() : udn.getUuid().toString(); | 2 |
trivago/Mail-Pigeon | pigeon-web/src/main/java/com/trivago/mail/pigeon/web/data/process/TemplateProcessor.java | [
"public class Campaign extends AbstractBean\r\n{\r\n\tpublic static final String ID = \"campaign_id\";\r\n\tpublic static final String DATE = \"send_date\";\r\n\tpublic static final String TITLE = \"title\";\r\n\tpublic static final String URL_PARAM = \"url_param\";\r\n\r\n\tpublic Campaign(final Node underlayingNode)\r\n\t{\r\n\t\tthis.dataNode = underlayingNode;\r\n\t}\r\n\r\n\tpublic Campaign(final long campaignId)\r\n\t{\r\n\t\tdataNode = ConnectionFactory.getCampaignIndex().get(IndexTypes.CAMPAIGN_ID, campaignId).getSingle();\r\n\t}\r\n\r\n\tpublic Campaign(final long campaignId, final String urlParams, final Date creationDate, final String campaignTitle)\r\n\t{\r\n\t\tTransaction tx = ConnectionFactory.getDatabase().beginTx();\r\n\t\ttry\r\n\t\t{\r\n\t\t\tdataNode = ConnectionFactory.getDatabase().createNode();\r\n\t\t\twriteProperty(ID, campaignId);\r\n\t\t\twriteProperty(\"type\", getClass().getName());\r\n\t\t\twriteProperty(DATE, creationDate.getTime());\r\n\t\t\twriteProperty(TITLE, campaignTitle);\r\n\t\t\twriteProperty(URL_PARAM, urlParams);\r\n\t\t\tConnectionFactory.getNewsletterIndex().add(this.dataNode, IndexTypes.CAMPAIGN_ID, campaignId);\r\n\t\t\tConnectionFactory.getNewsletterIndex().add(this.dataNode, IndexTypes.TYPE, getClass().getName());\r\n\t\t\tConnectionFactory.getDatabase().getReferenceNode().createRelationshipTo(dataNode, RelationTypes.CAMPAIGN_REFERENCE);\r\n\t\t\ttx.success();\r\n\t\t}\r\n\t\tcatch (Exception e)\r\n\t\t{\r\n\t\t\ttx.failure();\r\n\t\t}\r\n\t\tfinally\r\n\t\t{\r\n\t\t\ttx.finish();\r\n\t\t}\r\n\t}\r\n\r\n\tpublic long getId()\r\n\t{\r\n\t\treturn (Long) dataNode.getProperty(ID);\r\n\t}\r\n\r\n\tpublic Date getCreationDate()\r\n\t{\r\n\t\treturn getWrappedProperty(Date.class, Long.class, DATE);\r\n\t}\r\n\r\n\tpublic void setCreationDate(final Date creationDate)\r\n\t{\r\n\t\twriteProperty(DATE, creationDate.getTime());\r\n\t}\r\n\r\n\tpublic String getTitle()\r\n\t{\r\n\t\treturn getProperty(String.class, TITLE);\r\n\t}\r\n\r\n\tpublic void setTitle(final String title)\r\n\t{\r\n\t\twriteProperty(TITLE, title);\r\n\t}\r\n\r\n\tpublic Node getDataNode()\r\n\t{\r\n\t\treturn this.dataNode;\r\n\t}\r\n\r\n\tpublic String getUrlParams()\r\n\t{\r\n\t\treturn getProperty(String.class, URL_PARAM);\r\n\t}\r\n\r\n\tpublic void setUrlParams(final String urlParams)\r\n\t{\r\n\t\twriteProperty(URL_PARAM, urlParams);\r\n\t}\r\n\r\n\tpublic static IndexHits<Node> getAll()\r\n\t{\r\n\t\treturn ConnectionFactory.getCampaignIndex().get(\"type\", Campaign.class.getName());\r\n\t}\r\n}\r",
"public class Mail extends AbstractBean\r\n{\r\n\tpublic static final String ID = \"newsletter_id\";\r\n\tpublic static final String DATE = \"send_date\";\r\n\tpublic static final String SUBJECT = \"subject\";\r\n\tpublic static final String TEXT = \"text_content\";\r\n\tpublic static final String HTML = \"html_content\";\r\n\tpublic static final String DONE = \"done\";\r\n\tpublic static final String SENT = \"sent\";\r\n\r\n\tpublic Mail(final Node underlayingNode)\r\n\t{\r\n\t\tthis.dataNode = underlayingNode;\r\n\t}\r\n\r\n\tpublic Mail(final long mailId)\r\n\t{\r\n\t\tdataNode = ConnectionFactory.getNewsletterIndex().get(IndexTypes.NEWSLETTER_ID, mailId).getSingle();\r\n\t}\r\n\r\n\tpublic Mail(final long mailId, final MailTemplate template, final Date sendDate, final Sender sender)\r\n\t{\r\n\t\tthis(mailId, template.getText(), template.getHtml(), sendDate, template.getSubject(), sender);\r\n\t}\r\n\r\n\tpublic Mail(final long mailId, final String text, final String html, final Date sendDate, final String subject, final Sender sender)\r\n\t{\r\n\t\tTransaction tx = ConnectionFactory.getDatabase().beginTx();\r\n\t\ttry\r\n\t\t{\r\n\t\t\tdataNode = ConnectionFactory.getDatabase().createNode();\r\n\t\t\twriteProperty(ID, mailId);\r\n\t\t\twriteProperty(\"type\", getClass().getName());\r\n\t\t\twriteProperty(DATE, sendDate.getTime());\r\n\t\t\twriteProperty(SUBJECT, subject);\r\n\t\t\twriteProperty(TEXT, text);\r\n\t\t\twriteProperty(HTML, html);\r\n\t\t\twriteProperty(DONE, false);\r\n\t\t\twriteProperty(SENT, false);\r\n\t\t\tConnectionFactory.getNewsletterIndex().add(this.dataNode, IndexTypes.NEWSLETTER_ID, mailId);\r\n\t\t\tConnectionFactory.getNewsletterIndex().add(this.dataNode, IndexTypes.TYPE, getClass().getName());\r\n\t\t\tConnectionFactory.getDatabase().getReferenceNode().createRelationshipTo(dataNode, RelationTypes.NEWSLETTER_REFERENCE);\r\n\t\t\ttx.success();\r\n\t\t\tsender.addSentMail(this);\r\n\t\t}\r\n\t\tcatch (Exception e)\r\n\t\t{\r\n\t\t\ttx.failure();\r\n\t\t}\r\n\t\tfinally\r\n\t\t{\r\n\t\t\ttx.finish();\r\n\t\t}\r\n\t}\r\n\r\n\tpublic long getId()\r\n\t{\r\n\t\treturn getProperty(Long.class, ID, false);\r\n\t}\r\n\r\n\tpublic Date getSendDate()\r\n\t{\r\n\t\treturn getWrappedProperty(Date.class, Long.class, DATE);\r\n\t}\r\n\r\n\tpublic String getSubject()\r\n\t{\r\n\t\treturn getProperty(String.class, SUBJECT);\r\n\t}\r\n\r\n\tpublic Node getDataNode()\r\n\t{\r\n\t\treturn this.dataNode;\r\n\t}\r\n\r\n\tpublic String getText()\r\n\t{\r\n\t\treturn getProperty(String.class, TEXT);\r\n\t}\r\n\r\n\tpublic String getHtml()\r\n\t{\r\n\t\treturn getProperty(String.class, HTML);\r\n\t}\r\n\r\n\tpublic boolean isDone()\r\n\t{\r\n\t\treturn getProperty(Boolean.class, DONE);\r\n\t}\r\n\r\n\tpublic void setDone()\r\n\t{\r\n\t\twriteProperty(DONE, true);\r\n\t}\r\n\r\n\tpublic boolean isSent()\r\n\t{\r\n\t\treturn getProperty(Boolean.class, SENT);\r\n\t}\r\n\r\n\tpublic void setSent()\r\n\t{\r\n\t\twriteProperty(SENT, true);\r\n\t}\r\n\r\n /**\r\n * Adds a recipient to the mail.\r\n * @param recipient the recipient to add\r\n * @return the created relationship for further use.\r\n */\r\n\tpublic Relationship addRecipient(Recipient recipient)\r\n\t{\r\n\t\tTransaction tx = ConnectionFactory.getDatabase().beginTx();\r\n\t\tRelationship relation = null;\r\n\t\ttry\r\n\t\t{\r\n\t\t\tNode recipientNode = recipient.getDataNode();\r\n\t\t\trelation = dataNode.createRelationshipTo(recipientNode, RelationTypes.DELIVERED_TO);\r\n\t\t\trelation.setProperty(DATE, new Date().getTime());\r\n\t\t\ttx.success();\r\n\t\t}\r\n\t\tcatch (Exception e)\r\n\t\t{\r\n\t\t\ttx.failure();\r\n\t\t}\r\n\t\tfinally\r\n\t\t{\r\n\t\t\ttx.finish();\r\n\t\t}\r\n\t\treturn relation;\r\n\t}\r\n\r\n /**\r\n * Adds this mail to a campaign. The relations Mail(1) -> (n)Campaigns\r\n * @param campaign the campaign to create a relation to.\r\n * @return the created relation for further use.\r\n */\r\n\tpublic Relationship addToCampaign(Campaign campaign)\r\n\t{\r\n\t\tTransaction tx = ConnectionFactory.getDatabase().beginTx();\r\n\t\tRelationship relation = null;\r\n\t\ttry\r\n\t\t{\r\n\t\t\tNode campaignDataNode = campaign.getDataNode();\r\n\t\t\trelation = campaignDataNode.createRelationshipTo(dataNode, RelationTypes.PART_OF_CAMPAIGN);\r\n\t\t\trelation.setProperty(DATE, new Date().getTime());\r\n\t\t\ttx.success();\r\n\t\t}\r\n\t\tcatch (Exception e)\r\n\t\t{\r\n\t\t\ttx.failure();\r\n\t\t}\r\n\t\tfinally\r\n\t\t{\r\n\t\t\ttx.finish();\r\n\t\t}\r\n\t\treturn relation;\r\n\t}\r\n\r\n /**\r\n * @return all recipients of the mail.\r\n */\r\n\tpublic Iterable<Relationship> getRecipients()\r\n\t{\r\n\t\treturn dataNode.getRelationships(RelationTypes.DELIVERED_TO);\r\n\t}\r\n\r\n\tpublic Iterable<Relationship> getBouncedMails()\r\n\t{\r\n\t\treturn dataNode.getRelationships(RelationTypes.BOUNCED_MAIL);\r\n\t}\r\n\r\n\tpublic static IndexHits<Node> getAll()\r\n\t{\r\n\t\treturn ConnectionFactory.getNewsletterIndex().get(IndexTypes.TYPE, Mail.class.getName());\r\n\t}\r\n\r\n\tpublic Campaign getCampaign()\r\n\t{\r\n\t\tfinal Iterable<Relationship> relationships = dataNode.getRelationships(RelationTypes.PART_OF_CAMPAIGN);\r\n\r\n\t\tIterator<Relationship> iterator = relationships.iterator();\r\n\t\tif (iterator.hasNext())\r\n\t\t\treturn new Campaign(iterator.next().getStartNode());\r\n\t\telse\r\n\t\t\treturn null;\r\n\t}\r\n}\r",
"public class Recipient extends AbstractBean\r\n{\r\n\tpublic static final String ID = \"user_id\";\r\n\tpublic static final String FIRSTNAME = \"firstname\";\r\n\tpublic static final String LASTNAME = \"lastname\";\r\n\tpublic static final String GENDER = \"gender\";\r\n\tpublic static final String TITLE = \"title\";\r\n\tpublic static final String BIRTHDAY = \"birthday\";\r\n\tpublic static final String COUNTRY = \"country\";\r\n\tpublic static final String LANGUAGE = \"language\";\r\n\tpublic static final String CITY = \"city\";\r\n\tpublic static final String EXTERNAL_ID = \"external_id\";\r\n\tpublic static final String EMAIL = \"email\";\r\n\tpublic static final String DATE = \"date\";\r\n\tpublic static final String ACTIVE = \"active\";\r\n\r\n\tpublic Recipient(final Node underlayingNode)\r\n\t{\r\n\t\tthis.dataNode = underlayingNode;\r\n\t}\r\n\r\n\tpublic Recipient(final long userId)\r\n\t{\r\n\t\tdataNode = ConnectionFactory.getUserIndex().get(IndexTypes.USER_ID, userId).getSingle();\r\n\t}\r\n\r\n\tpublic Recipient(final long userId,\r\n\t\t\t\t\t final String firstname,\r\n\t\t\t\t\t final String lastname,\r\n\t\t\t\t\t final String email,\r\n\t\t\t\t\t final boolean active)\r\n\t{\r\n\t\tthis(userId, firstname, lastname, email, active, Gender.UNKNOWN, null, null, null, null, null, null);\r\n\t}\r\n\r\n\tpublic Recipient(final long userId,\r\n\t\t\t\t\t final String firstname,\r\n\t\t\t\t\t final String lastname,\r\n\t\t\t\t\t final String email,\r\n\t\t\t\t\t final boolean active,\r\n\t\t\t\t\t final Gender gender,\r\n\t\t\t\t\t final Date birthday,\r\n\t\t\t\t\t final String title,\r\n\t\t\t\t\t final String city,\r\n\t\t\t\t\t final String country,\r\n\t\t\t\t\t final String language,\r\n\t\t\t\t\t final String externalId)\r\n\t{\r\n\t\tTransaction tx = ConnectionFactory.getDatabase().beginTx();\r\n\t\ttry\r\n\t\t{\r\n\t\t\tdataNode = ConnectionFactory.getDatabase().createNode();\r\n\t\t\twriteProperty(ID, userId);\r\n\t\t\twriteProperty(\"type\", getClass().getName());\r\n\t\t\twriteProperty(FIRSTNAME, firstname);\r\n\t\t\twriteProperty(LASTNAME, lastname);\r\n\t\t\twriteProperty(EMAIL, email);\r\n\t\t\twriteProperty(ACTIVE, active);\r\n\t\t\twriteProperty(GENDER, gender.toString());\r\n\t\t\twriteProperty(BIRTHDAY, birthday.getTime());\r\n\t\t\twriteProperty(TITLE, title);\r\n\t\t\twriteProperty(CITY, city);\r\n\t\t\twriteProperty(COUNTRY, country);\r\n\t\t\twriteProperty(LANGUAGE, language);\r\n\t\t\twriteProperty(EXTERNAL_ID, externalId);\r\n\r\n\t\t\tConnectionFactory.getUserIndex().add(this.dataNode, IndexTypes.USER_ID, userId);\r\n\t\t\tConnectionFactory.getUserIndex().add(this.dataNode, IndexTypes.TYPE, getClass().getName());\r\n\t\t\tConnectionFactory.getDatabase().getReferenceNode().createRelationshipTo(dataNode, RelationTypes.USER_REFERENCE);\r\n\t\t\ttx.success();\r\n\t\t}\r\n\t\tcatch (Exception e)\r\n\t\t{\r\n\t\t\tlog.error(\"Error while creating the recipient\", e);\r\n\t\t\ttx.failure();\r\n\t\t}\r\n\t\tfinally\r\n\t\t{\r\n\t\t\ttx.finish();\r\n\t\t}\r\n\t}\r\n\r\n\tpublic long getId()\r\n\t{\r\n\t\treturn getProperty(Long.class, ID, false);\r\n\t}\r\n\r\n\tpublic String getFirstname()\r\n\t{\r\n\t\treturn getProperty(String.class, FIRSTNAME);\r\n\t}\r\n\r\n\tpublic String getLastname()\r\n\t{\r\n\t\treturn getProperty(String.class, LASTNAME);\r\n\t}\r\n\r\n\tpublic String getEmail()\r\n\t{\r\n\t\treturn getProperty(String.class, EMAIL);\r\n\t}\r\n\r\n\tpublic void setFirstname(String name)\r\n\t{\r\n\t\twriteProperty(FIRSTNAME, name);\r\n\t}\r\n\r\n\tpublic void setEmail(String email)\r\n\t{\r\n\t\twriteProperty(EMAIL, email);\r\n\t}\r\n\r\n\tpublic Gender getGender()\r\n\t{\r\n\t\treturn Gender.fromString(getProperty(String.class, GENDER));\r\n\t}\r\n\r\n\tpublic void setGender(final Gender gender)\r\n\t{\r\n\t\twriteProperty(GENDER, gender);\r\n\t}\r\n\r\n\tpublic String getTitle()\r\n\t{\r\n\t\treturn getProperty(String.class, TITLE);\r\n\t}\r\n\r\n\tpublic void setTitle(final String title)\r\n\t{\r\n\t\twriteProperty(TITLE, title);\r\n\t}\r\n\r\n\tpublic String getCity()\r\n\t{\r\n\t\treturn getProperty(String.class, CITY);\r\n\t}\r\n\r\n\tpublic void setCity(final String city)\r\n\t{\r\n\t\twriteProperty(CITY, city);\r\n\t}\r\n\r\n\tpublic String getCountry()\r\n\t{\r\n\t\treturn getProperty(String.class, COUNTRY);\r\n\t}\r\n\r\n\tpublic void setCountry(final String country)\r\n\t{\r\n\t\twriteProperty(COUNTRY, country);\r\n\t}\r\n\r\n\tpublic Date getBirthday()\r\n\t{\r\n\t\treturn getWrappedProperty(Date.class, Long.class, BIRTHDAY);\r\n\t}\r\n\r\n\tpublic void setBirthday(final Date birthday)\r\n\t{\r\n\t\twriteProperty(BIRTHDAY, birthday.getTime());\r\n\t}\r\n\r\n\tpublic String getLanguage()\r\n\t{\r\n\t\treturn getProperty(String.class, LANGUAGE);\r\n\t}\r\n\r\n\tpublic void setLanguage(final String language)\r\n\t{\r\n\t\twriteProperty(LANGUAGE, language);\r\n\t}\r\n\r\n\tpublic String getExternalId()\r\n\t{\r\n\t\treturn getProperty(String.class, EXTERNAL_ID);\r\n\t}\r\n\r\n\tpublic void setExternalId(final String externalId)\r\n\t{\r\n\t\twriteProperty(EXTERNAL_ID, externalId);\r\n\t}\r\n\r\n\tpublic void setActive(final boolean active)\r\n\t{\r\n\t\twriteProperty(ACTIVE, active);\r\n\t}\r\n\r\n\tpublic boolean isActive()\r\n\t{\r\n\t\treturn getProperty(Boolean.class, ACTIVE);\r\n\t}\r\n\r\n\tpublic Relationship addRecievedNewsletter(Mail mail)\r\n\t{\r\n\t\tTransaction tx = ConnectionFactory.getDatabase().beginTx();\r\n\t\tRelationship relation = null;\r\n\t\ttry\r\n\t\t{\r\n\t\t\tNode newsletterNode = mail.getDataNode();\r\n\t\t\trelation = dataNode.createRelationshipTo(newsletterNode, RelationTypes.RECIEVED);\r\n\t\t\trelation.setProperty(DATE, new Date().getTime());\r\n\t\t\ttx.success();\r\n\t\t}\r\n\t\tcatch (Exception e)\r\n\t\t{\r\n\t\t\tlog.error(\"Error while creating node\", e);\r\n\t\t\ttx.failure();\r\n\t\t}\r\n\t\tfinally\r\n\t\t{\r\n\t\t\ttx.finish();\r\n\t\t}\r\n\t\treturn relation;\r\n\t}\r\n\r\n\t@JSONProperty(ignore = true)\r\n\tpublic Iterable<Relationship> getReceivedNewsletters()\r\n\t{\r\n\t\treturn dataNode.getRelationships(RelationTypes.RECIEVED);\r\n\t}\r\n\r\n\t@JSONProperty(ignore = true)\r\n\tpublic static IndexHits<Node> getAll()\r\n\t{\r\n\t\treturn ConnectionFactory.getUserIndex().get(\"type\", Recipient.class.getName());\r\n\t}\r\n}\r",
"public class Sender extends AbstractBean\r\n{\r\n\tpublic static final String ID = \"sender_id\";\r\n\r\n\tpublic static final String NAME = \"name\";\r\n\r\n\tpublic static final String FROM_MAIL = \"from_mail\";\r\n\r\n\tpublic static final String REPLYTO_MAIL = \"reply_to_mail\";\r\n\r\n\tpublic Sender(final Node underlayingNode)\r\n\t{\r\n\t\tthis.dataNode = underlayingNode;\r\n\t}\r\n\r\n\tpublic Sender(final long senderId)\r\n\t{\r\n\t\tdataNode = ConnectionFactory.getSenderIndex().get(IndexTypes.SENDER_ID, senderId).getSingle();\r\n\t}\r\n\r\n\tpublic Sender(final long senderId, final String fromMail, final String replytoMail, final String name)\r\n\t{\r\n\t\tdataNode = ConnectionFactory.getSenderIndex().get(IndexTypes.SENDER_ID, senderId).getSingle();\r\n\t\tif (dataNode != null)\r\n\t\t{\r\n\t\t\tthrow new RuntimeException(\"This sender does already exist\");\r\n\t\t}\r\n\r\n\t\tTransaction tx = ConnectionFactory.getDatabase().beginTx();\r\n\t\ttry\r\n\t\t{\r\n\t\t\tdataNode = ConnectionFactory.getDatabase().createNode();\r\n\t\t\twriteProperty(ID, senderId);\r\n\t\t\twriteProperty(\"type\", getClass().getName());\r\n\t\t\twriteProperty(NAME, name);\r\n\t\t\twriteProperty(FROM_MAIL, fromMail);\r\n\t\t\twriteProperty(REPLYTO_MAIL, replytoMail);\r\n\r\n\t\t\tConnectionFactory.getSenderIndex().add(this.dataNode, IndexTypes.SENDER_ID, senderId);\r\n\t\t\tConnectionFactory.getSenderIndex().add(this.dataNode, IndexTypes.TYPE, getClass().getName());\r\n\t\t\tConnectionFactory.getDatabase().getReferenceNode().createRelationshipTo(dataNode, RelationTypes.SENDER_REFERENCE);\r\n\t\t\ttx.success();\r\n\t\t}\r\n\t\tcatch (Exception e)\r\n\t\t{\r\n\t\t\ttx.failure();\r\n\t\t}\r\n\t\tfinally\r\n\t\t{\r\n\t\t\ttx.finish();\r\n\t\t}\r\n\t}\r\n\r\n\tpublic Node getDataNode()\r\n\t{\r\n\t\treturn dataNode;\r\n\t}\r\n\r\n\tpublic long getId()\r\n\t{\r\n\t\treturn getProperty(Long.class, ID, false);\r\n\t}\r\n\r\n\tpublic String getName()\r\n\t{\r\n\t\treturn getProperty(String.class, NAME);\r\n\t}\r\n\r\n\tpublic String getFromMail()\r\n\t{\r\n\t\treturn getProperty(String.class, FROM_MAIL);\r\n\t}\r\n\r\n\tpublic String getReplytoMail()\r\n\t{\r\n\t\treturn getProperty(String.class, REPLYTO_MAIL);\r\n\t}\r\n\r\n\tpublic void setName(String name)\r\n\t{\r\n\t\twriteProperty(NAME, name);\r\n\t}\r\n\r\n\tpublic void setFromMail(String fromMail)\r\n\t{\r\n\t\twriteProperty(FROM_MAIL, fromMail);\r\n\t}\r\n\r\n\tpublic void setReplytoMail(String replytoMail)\r\n\t{\r\n\t\twriteProperty(REPLYTO_MAIL, replytoMail);\r\n\t}\r\n\r\n\tpublic Relationship addSentMail(Mail mail)\r\n\t{\r\n\t\tTransaction tx = ConnectionFactory.getDatabase().beginTx();\r\n\t\tRelationship relation = null;\r\n\t\ttry\r\n\t\t{\r\n\t\t\tNode recipientNode = mail.getDataNode();\r\n\t\t\trelation = dataNode.createRelationshipTo(recipientNode, RelationTypes.SENT_EMAIL);\r\n\t\t\trelation.setProperty(\"date\", new Date().getTime());\r\n\t\t\ttx.success();\r\n\t\t}\r\n\t\tcatch (Exception e)\r\n\t\t{\r\n\t\t\ttx.failure();\r\n\t\t}\r\n\t\tfinally\r\n\t\t{\r\n\t\t\ttx.finish();\r\n\t\t}\r\n\t\treturn relation;\r\n\t}\r\n\r\n\tpublic Iterable<Relationship> getSentMails()\r\n\t{\r\n\t\treturn dataNode.getRelationships(RelationTypes.SENT_EMAIL);\r\n\t}\r\n\r\n\tpublic int getSentMailsCount()\r\n\t{\r\n\t\tint count = 0;\r\n\t\tfinal Iterable<Relationship> sentMails = getSentMails();\r\n\t\tfor (Relationship rel : sentMails)\r\n\t\t{\r\n\t\t\t++count;\r\n\t\t}\r\n\t\treturn count;\r\n\t}\r\n\r\n\r\n\tpublic static IndexHits<Node> getAll()\r\n\t{\r\n\t\treturn ConnectionFactory.getSenderIndex().get(\"type\", Sender.class.getName());\r\n\t}\r\n}\r",
"public class Settings\n{\n\tprivate static final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(Settings.class);\n\n\tprivate static Settings instance;\n\n\tprivate Configuration configuration;\n\n\tpublic static Settings create()\n\t{\n\t\treturn create(false);\n\t}\n\n\tpublic static Settings create(boolean nocache)\n\t{\n\t\treturn create(null, nocache);\n\t}\n\n\tpublic static Settings create(String fileName, boolean nocache)\n\t{\n\t\tlog.trace(\"Settings instance requested\");\n\t\tif (fileName == null && instance != null && !nocache)\n\t\t{\n\t\t\tlog.trace(\"Returning cached instance\");\n\t\t\treturn instance;\n\t\t}\n\t\telse if (fileName == null && instance == null)\n\t\t{\n\t\t\tlog.trace(\"Requesting ENV PIDGEON_CONFIG as path to properties as fileName was null\");\n\n\t\t\tString propertyFileName = System.getenv(\"PIDGEON_CONFIG\");\n\n\t\t\tif (propertyFileName == null || propertyFileName.equals(\"\"))\n\t\t\t{\n\t\t\t\tlog.warn(\"ENV is empty and no filename was given -> no config properties found! Using configuration.properties\");\n\t\t\t}\n\n\t\t\tURL resource = Thread.currentThread().getContextClassLoader().getResource(\"configuration.properties\");\n\t\t\tpropertyFileName = resource.toExternalForm();\n\t\t\tinstance = new Settings();\n\n\t\t\ttry\n\t\t\t{\n\t\t\t\tinstance.setConfiguration(new PropertiesConfiguration(propertyFileName));\n\t\t\t}\n\t\t\tcatch (ConfigurationException e)\n\t\t\t{\n\t\t\t\tlog.error(e);\n\t\t\t\tthrow new ConfigurationRuntimeException(e);\n\t\t\t}\n\t\t}\n\t\telse if (fileName != null && instance == null)\n\t\t{\n\t\t\tlog.trace(\"Requesting file properties from \" + fileName);\n\t\t\tinstance = new Settings();\n\n\t\t\ttry\n\t\t\t{\n\t\t\t\tinstance.setConfiguration(new PropertiesConfiguration(fileName));\n\t\t\t}\n\t\t\tcatch (ConfigurationException e)\n\t\t\t{\n\t\t\t\tlog.error(e);\n\t\t\t\tthrow new ConfigurationRuntimeException(e);\n\t\t\t}\n\t\t}\n\t\treturn instance;\n\t}\n\n\tpublic Configuration getConfiguration()\n\t{\n\t\treturn configuration;\n\t}\n\n\tpublic void setConfiguration(Configuration configuration)\n\t{\n\t\tthis.configuration = configuration;\n\t}\n}",
"public class MailTransport\r\n{\r\n\tprivate String from;\r\n\r\n\tprivate String to;\r\n\r\n\tprivate String replyTo;\r\n\r\n\tprivate String subject;\r\n\r\n\tprivate String html;\r\n\r\n\tprivate String text;\r\n\r\n\tprivate String mId;\r\n\r\n\tprivate String uId;\r\n\r\n\tprivate Date sendDate;\r\n\r\n\tprivate boolean enforceSending = false;\r\n\r\n\tprivate boolean abortSending = false;\r\n\r\n\tpublic void enforceSending()\r\n\t{\r\n\t\tenforceSending = true;\r\n\t}\r\n\r\n\tpublic void abortSending()\r\n\t{\r\n\t\tabortSending = true;\r\n\t}\r\n\r\n\tpublic boolean shouldAbortSending()\r\n\t{\r\n\t\treturn abortSending;\r\n\t}\r\n\r\n\tpublic boolean shouldEnforceSending()\r\n\t{\r\n\t\treturn enforceSending;\r\n\t}\r\n\r\n\tpublic String getFrom()\r\n\t{\r\n\t\treturn from;\r\n\t}\r\n\r\n\tpublic void setFrom(String from)\r\n\t{\r\n\t\tthis.from = from;\r\n\t}\r\n\r\n\tpublic String getTo()\r\n\t{\r\n\t\treturn to;\r\n\t}\r\n\r\n\tpublic void setTo(String to)\r\n\t{\r\n\t\tthis.to = to;\r\n\t}\r\n\r\n\tpublic String getReplyTo()\r\n\t{\r\n\t\treturn replyTo;\r\n\t}\r\n\r\n\tpublic void setReplyTo(String replyTo)\r\n\t{\r\n\t\tthis.replyTo = replyTo;\r\n\t}\r\n\r\n\tpublic String getSubject()\r\n\t{\r\n\t\treturn subject;\r\n\t}\r\n\r\n\tpublic void setSubject(String subject)\r\n\t{\r\n\t\tthis.subject = subject;\r\n\t}\r\n\r\n\tpublic String getHtml()\r\n\t{\r\n\t\treturn html;\r\n\t}\r\n\r\n\tpublic void setHtml(String html)\r\n\t{\r\n\t\tthis.html = html;\r\n\t}\r\n\r\n\tpublic String getText()\r\n\t{\r\n\t\treturn text;\r\n\t}\r\n\r\n\tpublic void setText(String text)\r\n\t{\r\n\t\tthis.text = text;\r\n\t}\r\n\r\n\tpublic String getmId()\r\n\t{\r\n\t\treturn mId;\r\n\t}\r\n\r\n\tpublic void setmId(String mId)\r\n\t{\r\n\t\tthis.mId = mId;\r\n\t}\r\n\r\n\tpublic String getuId()\r\n\t{\r\n\t\treturn uId;\r\n\t}\r\n\r\n\tpublic void setuId(String uId)\r\n\t{\r\n\t\tthis.uId = uId;\r\n\t}\r\n\r\n\tpublic Date getSendDate()\r\n\t{\r\n\t\treturn sendDate;\r\n\t}\r\n\r\n\tpublic void setSendDate(Date sendDate)\r\n\t{\r\n\t\tthis.sendDate = sendDate;\r\n\t}\r\n}\r",
"@SuppressWarnings(\"serial\")\r\npublic class MainApp extends Application\r\n{\r\n\tprivate Window window;\r\n\tprivate MenuBar menu;\r\n \r\n\t@Override\r\n\tpublic void init()\r\n\t{\r\n\t\t//DOMConfigurator.configure(Thread.currentThread().getContextClassLoader().getResource(\"log4j.xml\"));\r\n// BasicConfigurator.configure();\r\n\t\twindow = new Window(\"Mail Pigeon\");\r\n\t\tsetMainWindow(window);\r\n\r\n\t\tint senderSize;\r\n\t\ttry\r\n\t\t{\r\n\t\t\tsenderSize = Sender.getAll().size();\r\n\t\t} catch (NoSuchElementException e)\r\n\t\t{\r\n\t\t\tsenderSize = 0;\r\n\t\t}\r\n\r\n\t\tint recipientGroupSize;\r\n\t\ttry\r\n\t\t{\r\n\t\t\trecipientGroupSize = RecipientGroup.getAll().size();\r\n\t\t} catch (NoSuchElementException e)\r\n\t\t{\r\n\t\t\trecipientGroupSize = 0;\r\n\t\t}\r\n\r\n\t\tif (senderSize == 0 && recipientGroupSize == 0)\r\n\t\t{\r\n\t\t\tstartWizard();\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tmenu = new MenuBar(this);\r\n\t\t\twindow.addComponent(menu);\r\n\t\t\tsetDashBoard();\r\n\t\t}\r\n\r\n\t}\r\n\r\n\tpublic void initMenu()\r\n\t{\r\n\t\tmenu = new MenuBar(this);\r\n\t\twindow.addComponent(menu);\r\n\t}\r\n\r\n\tpublic void clearWindow()\r\n\t{\r\n\t\twindow.removeAllComponents();\r\n\t\tinitMenu();\r\n\t}\r\n\r\n\tpublic void setDashBoard()\r\n\t{\r\n\t\tVerticalLayout dbLayout = new VerticalLayout();\r\n\t\tdbLayout.addComponent(new Label(\"Can I haz Dashboard?\"));\r\n\t\twindow.addComponent(dbLayout);\r\n\r\n\t}\r\n\r\n\tpublic void setNewsletterList()\r\n\t{\r\n\t\tNewsletterList newsletterList = new NewsletterList();\r\n\t\tVerticalLayout nlLayout = new VerticalLayout();\r\n\t\tnlLayout.addComponent(newsletterList);\r\n\t\tnlLayout.setMargin(true);\r\n\t\tclearWindow();\r\n\t\twindow.addComponent(nlLayout);\r\n\t}\r\n\r\n\tpublic void setSenderList()\r\n\t{\r\n\t\tSenderList senderList = new SenderList();\r\n\t\tVerticalLayout slLayout = new VerticalLayout();\r\n\t\tslLayout.addComponent(senderList);\r\n\t\tslLayout.setMargin(true);\r\n\t\tclearWindow();\r\n\t\twindow.addComponent(slLayout);\r\n\t}\r\n\r\n\tpublic void setRecipientGroupList()\r\n\t{\r\n\t\tGroupList groupList = new GroupList();\r\n\t\tVerticalLayout rgLayout = new VerticalLayout();\r\n\t\trgLayout.addComponent(groupList);\r\n\t\trgLayout.setMargin(true);\r\n\t\tclearWindow();\r\n\t\twindow.addComponent(rgLayout);\r\n\t}\r\n\r\n\tpublic void setRecipientList()\r\n\t{\r\n\t\tRecipientList recipientList = new RecipientList();\r\n\t\tVerticalLayout rLayout = new VerticalLayout();\r\n\t\trLayout.addComponent(recipientList);\r\n\t\trLayout.setMargin(true);\r\n\t\tclearWindow();\r\n\t\twindow.addComponent(rLayout);\r\n\t}\r\n\r\n\tpublic void setTemplateList()\r\n\t{\r\n\t\tTemplateList templateList = new TemplateList();\r\n\t\tVerticalLayout tlLayout = new VerticalLayout();\r\n\t\ttlLayout.addComponent(templateList);\r\n\t\ttlLayout.setMargin(true);\r\n\t\tclearWindow();\r\n\t\twindow.addComponent(tlLayout);\r\n\t}\r\n\r\n\tpublic void startWizard()\r\n\t{\r\n\t\tSetupWizardComponent wb = new SetupWizardComponent();\r\n\t\twindow.addComponent(wb);\r\n\t}\r\n\r\n\tpublic MenuBar getMenu()\r\n\t{\r\n\t\treturn menu;\r\n\t}\r\n\r\n\tpublic void setMenu(MenuBar menu)\r\n\t{\r\n\t\tthis.menu = menu;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void close()\r\n\t{\r\n\t\tsuper.close();\r\n\t\t// Registers a shutdown hook for the Neo4j and index service instances\r\n\t\t// so that it shuts down nicely when the VM exits (even if you\r\n\t\t// \"Ctrl-C\" the running example before it's completed)\r\n\t\tRuntime.getRuntime().addShutdownHook(new Thread()\r\n\t\t{\r\n\t\t\t@Override\r\n\t\t\tpublic void run()\r\n\t\t\t{\r\n\t\t\t\tLogger.getLogger(MainApp.class).info(\"Shutdown hook called\");\r\n\t\t\t\tConnectionFactory.getDatabase().shutdown();\r\n\t\t\t}\r\n\t\t});\r\n\r\n\t}\r\n}"
] | import java.util.Set;
import com.trivago.mail.pigeon.bean.Campaign;
import com.trivago.mail.pigeon.bean.Mail;
import com.trivago.mail.pigeon.bean.Recipient;
import com.trivago.mail.pigeon.bean.Sender;
import com.trivago.mail.pigeon.configuration.Settings;
import com.trivago.mail.pigeon.json.MailTransport;
import com.trivago.mail.pigeon.web.MainApp;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.context.Context;
import javax.servlet.ServletContext;
import java.io.StringWriter;
import java.net.URL;
| /**
* Copyright (C) 2011-2012 trivago GmbH <[email protected]>, <[email protected]>
*
* 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.trivago.mail.pigeon.web.data.process;
public class TemplateProcessor
{
private VelocityEngine velocity;
public TemplateProcessor()
{
velocity = new VelocityEngine();
}
| public MailTransport processMail(Mail mail, Recipient recipient, Sender sender, Campaign campaign)
| 0 |
BennSandoval/Woodmin | app/src/main/java/app/bennsandoval/com/woodmin/activities/OrderAddProduct.java | [
"public class Woodmin extends Application {\n\n public final String LOG_TAG = Woodmin.class.getSimpleName();\n\n @Override\n public void onCreate() {\n super.onCreate();\n Fabric.with(this, new Crashlytics());\n\n Picasso.Builder picassoBuilder = new Picasso.Builder(getApplicationContext());\n Picasso picasso = picassoBuilder.build();\n //picasso.setIndicatorsEnabled(true);\n try {\n Picasso.setSingletonInstance(picasso);\n } catch (IllegalStateException ignored) {\n Log.e(LOG_TAG, \"Picasso instance already used\");\n }\n }\n\n public Woocommerce getWoocommerceApiHandler() {\n\n String server = Utility.getPreferredServer(getApplicationContext());\n final String key = Utility.getPreferredUser(getApplicationContext());\n final String secret = Utility.getPreferredSecret(getApplicationContext());\n\n OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder()\n .connectTimeout(60000, TimeUnit.MILLISECONDS)\n .readTimeout(60000, TimeUnit.MILLISECONDS)\n .cache(null);\n\n //TODO Remove this if you don't have a self cert\n if(!server.contains(\"https\")) {\n if(Utility.getSSLSocketFactory() != null){\n clientBuilder\n .sslSocketFactory(Utility.getSSLSocketFactory())\n .hostnameVerifier(Utility.getHostnameVerifier());\n }\n }\n\n Interceptor basicAuthenticatorInterceptor = new Interceptor() {\n @Override\n public Response intercept(Chain chain) throws IOException {\n Request request = chain.request();\n String authenticationHeader = \"Basic \" + Base64.encodeToString(\n (key + \":\" + secret).getBytes(),\n Base64.NO_WRAP);\n\n Request authenticateRequest = request.newBuilder()\n .addHeader(\"Authorization\", authenticationHeader)\n .addHeader(\"Accept\", \"application/json\")\n .addHeader(\"Content-Type\", \"application/json\")\n .build();\n return chain.proceed(authenticateRequest);\n }\n };\n\n\n //OkHttpOAuthConsumer consumer = new OkHttpOAuthConsumer(key, secret);\n //consumer.setSigningStrategy(new QueryStringSigningStrategy());\n //clientBuilder.addInterceptor(new SigningInterceptor(consumer));\n clientBuilder.addInterceptor(basicAuthenticatorInterceptor);\n\n Gson gson = new GsonBuilder()\n .registerTypeAdapter(Date.class, new DateDeserializer())\n .create();\n\n Retrofit retrofit = new Retrofit.Builder()\n .baseUrl(server)\n .client(clientBuilder.build())\n .addConverterFactory(GsonConverterFactory.create(gson))\n .build();\n\n return retrofit.create(Woocommerce.class);\n }\n\n}",
"public class WoodminContract {\n\n // Match <string name=\"content_authority\" translatable=\"false\">com.woodmin.app</string>\n public static final String CONTENT_AUTHORITY = \"com.woodmin.app\";\n public static final Uri BASE_CONTENT_URI = Uri.parse(\"content://\" + CONTENT_AUTHORITY);\n\n // For instance, content://com.woodmin.app/shop/\n public static final String PATH_SHOP = \"shop\";\n // For instance, content://com.woodmin.app/order/\n public static final String PATH_ORDER = \"order\";\n // For instance, content://com.woodmin.app/product/\n public static final String PATH_PRODUCT = \"product\";\n // For instance, content://com.woodmin.app/customer/\n public static final String PATH_CUSTOMER = \"customer\";\n\n public static final String DATE_FORMAT = \"yyyy-MM-dd'T'HH:mm:ss\";\n\n public static String getDbDateString(Date date){\n SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT, Locale.getDefault());\n return sdf.format(date);\n }\n\n public static final class ShopEntry implements BaseColumns {\n\n public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_SHOP).build();\n public static final String CONTENT_TYPE = \"vnd.android.cursor.dir/\" + CONTENT_AUTHORITY + \"/\" + PATH_SHOP;\n public static final String CONTENT_ITEM_TYPE = \"vnd.android.cursor.item/\" + CONTENT_AUTHORITY + \"/\" + PATH_SHOP;\n\n // Table name\n public static final String TABLE_NAME = \"shop\";\n\n //Fields\n public static final String COLUMN_NAME = \"name\";\n public static final String COLUMN_DESCRIPTION = \"description\";\n public static final String COLUMN_URL = \"URL\";\n public static final String COLUMN_WC_VERSION = \"wc_version\";\n public static final String COLUMN_META_TIMEZONE = \"timezone\";\n public static final String COLUMN_META_CURRENCY = \"currency\";\n public static final String COLUMN_META_CURRENCY_FORMAT = \"currency_format\";\n public static final String COLUMN_META_TAXI_INCLUDE = \"tax_included\";\n public static final String COLUMN_META_WEIGHT_UNIT = \"weight_unit\";\n public static final String COLUMN_META_DIMENSION_UNIT = \"dimension_unit\";\n\n public static Uri buildShopUri(long id) {\n return ContentUris.withAppendedId(CONTENT_URI, id);\n }\n\n }\n\n public static final class OrdersEntry implements BaseColumns {\n\n public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_ORDER).build();\n public static final String CONTENT_TYPE = \"vnd.android.cursor.dir/\" + CONTENT_AUTHORITY + \"/\" + PATH_ORDER;\n public static final String CONTENT_ITEM_TYPE = \"vnd.android.cursor.item/\" + CONTENT_AUTHORITY + \"/\" + PATH_ORDER;\n\n // Table name\n public static final String TABLE_NAME = \"orders\";\n\n //Fields\n public static final String COLUMN_ID = \"woocommerce_id\";\n public static final String COLUMN_ORDER_NUMBER = \"order_number\";\n\n public static final String COLUMN_CREATED_AT = \"created_at\";\n public static final String COLUMN_UPDATED_AT = \"updated_at\";\n public static final String COLUMN_COMPLETED_AT = \"completed_at\";\n\n public static final String COLUMN_STATUS = \"status\";\n public static final String COLUMN_CURRENCY = \"currency\";\n public static final String COLUMN_TOTAL = \"total\";\n public static final String COLUMN_SUBTOTAL = \"subtotal\";\n public static final String COLUMN_TOTAL_LINE_ITEMS_QUANTITY = \"total_line_items_quantity\";\n public static final String COLUMN_TOTAL_TAX = \"total_tax\";\n public static final String COLUMN_TOTAL_SHIPPING = \"total_shipping\";\n public static final String COLUMN_CART_TAX = \"cart_tax\";\n public static final String COLUMN_SHIPPING_TAX = \"shipping_tax\";\n public static final String COLUMN_TOTAL_DISCOUNT = \"total_discount\";\n public static final String COLUMN_CART_DISCOUNT = \"cart_discount\";\n public static final String COLUMN_ORDER_DISCOUNT = \"order_discount\";\n public static final String COLUMN_SHIPPING_METHODS = \"shipping_methods\";\n\n public static final String COLUMN_NOTE = \"note\";\n public static final String COLUMN_VIEW_ORDER_URL = \"view_order_url\";\n\n public static final String COLUMN_PAYMENT_DETAILS_METHOD_ID = \"method_id\";\n public static final String COLUMN_PAYMENT_DETAILS_METHOD_TITLE = \"method_title\";\n public static final String COLUMN_PAYMENT_DETAILS_PAID = \"paid\";\n\n public static final String COLUMN_BILLING_FIRST_NAME = \"billing_first_name\";\n public static final String COLUMN_BILLING_LAST_NAME = \"billing_last_name\";\n public static final String COLUMN_BILLING_COMPANY = \"billing_company\";\n public static final String COLUMN_BILLING_ADDRESS_1 = \"billing_address_1\";\n public static final String COLUMN_BILLING_ADDRESS_2 = \"billing_address_2\";\n public static final String COLUMN_BILLING_CITY = \"billing_city\";\n public static final String COLUMN_BILLING_STATE = \"billing_state\";\n public static final String COLUMN_BILLING_POSTCODE = \"billing_postcode\";\n public static final String COLUMN_BILLING_COUNTRY = \"billing_country\";\n public static final String COLUMN_BILLING_EMAIL = \"billing_email\";\n public static final String COLUMN_BILLING_PHONE = \"billing_phone\";\n\n public static final String COLUMN_SHIPPING_FIRST_NAME = \"shipping_first_name\";\n public static final String COLUMN_SHIPPING_LAST_NAME = \"shipping_last_name\";\n public static final String COLUMN_SHIPPING_COMPANY = \"shipping_company\";\n public static final String COLUMN_SHIPPING_ADDRESS_1 = \"shipping_address_1\";\n public static final String COLUMN_SHIPPING_ADDRESS_2 = \"shipping_address_2\";\n public static final String COLUMN_SHIPPING_CITY = \"shipping_city\";\n public static final String COLUMN_SHIPPING_STATE = \"shipping_state\";\n public static final String COLUMN_SHIPPING_POSTCODE = \"shipping_postcode\";\n public static final String COLUMN_SHIPPING_COUNTRY = \"shipping_country\";\n\n public static final String COLUMN_CUSTOMER_ID = \"customer_id\";\n\n public static final String COLUMN_CUSTOMER_EMAIL = \"customer_email\";\n public static final String COLUMN_CUSTOMER_FIRST_NAME = \"customer_first_name\";\n public static final String COLUMN_CUSTOMER_LAST_NAME = \"customer_last_name\";\n public static final String COLUMN_CUSTOMER_USERNAME = \"customer_username\";\n public static final String COLUMN_CUSTOMER_LAST_ORDER_ID = \"customer_last_order_id\";\n public static final String COLUMN_CUSTOMER_LAST_ORDER_DATE = \"customer_last_order_date\";\n public static final String COLUMN_CUSTOMER_ORDERS_COUNT = \"customer_orders_count\";\n public static final String COLUMN_CUSTOMER_TOTAL_SPEND = \"customer_total_spent\";\n public static final String COLUMN_CUSTOMER_AVATAR_URL = \"customer_avatar_url\";\n\n public static final String COLUMN_CUSTOMER_BILLING_FIRST_NAME = \"customer_billing_first_name\";\n public static final String COLUMN_CUSTOMER_BILLING_LAST_NAME = \"customer_billing_last_name\";\n public static final String COLUMN_CUSTOMER_BILLING_COMPANY = \"customer_billing_company\";\n public static final String COLUMN_CUSTOMER_BILLING_ADDRESS_1 = \"customer_billing_address_1\";\n public static final String COLUMN_CUSTOMER_BILLING_ADDRESS_2 = \"customer_billing_address_2\";\n public static final String COLUMN_CUSTOMER_BILLING_CITY = \"customer_billing_city\";\n public static final String COLUMN_CUSTOMER_BILLING_STATE = \"customer_billing_state\";\n public static final String COLUMN_CUSTOMER_BILLING_POSTCODE = \"customer_billing_postcode\";\n public static final String COLUMN_CUSTOMER_BILLING_COUNTRY = \"customer_billing_country\";\n public static final String COLUMN_CUSTOMER_BILLING_EMAIL = \"customer_billing_email\";\n public static final String COLUMN_CUSTOMER_BILLING_PHONE = \"customer_billing_phone\";\n\n public static final String COLUMN_CUSTOMER_SHIPPING_FIRST_NAME = \"customer_shipping_first_name\";\n public static final String COLUMN_CUSTOMER_SHIPPING_LAST_NAME = \"customer_shipping_last_name\";\n public static final String COLUMN_CUSTOMER_SHIPPING_COMPANY = \"customer_shipping_company\";\n public static final String COLUMN_CUSTOMER_SHIPPING_ADDRESS_1 = \"customer_shipping_address_1\";\n public static final String COLUMN_CUSTOMER_SHIPPING_ADDRESS_2 = \"customer_shipping_address_2\";\n public static final String COLUMN_CUSTOMER_SHIPPING_CITY = \"customer_shipping_city\";\n public static final String COLUMN_CUSTOMER_SHIPPING_STATE = \"customer_shipping_state\";\n public static final String COLUMN_CUSTOMER_SHIPPING_POSTCODE = \"customer_shipping_postcode\";\n public static final String COLUMN_CUSTOMER_SHIPPING_COUNTRY = \"customer_shipping_country\";\n\n public static final String COLUMN_JSON = \"json\";\n public static final String COLUMN_ENABLE = \"enable\";\n\n public static Uri buildOrderUri(long id) {\n return ContentUris.withAppendedId(CONTENT_URI, id);\n }\n\n }\n\n public static final class ProductEntry implements BaseColumns {\n\n public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_PRODUCT).build();\n public static final String CONTENT_TYPE = \"vnd.android.cursor.dir/\" + CONTENT_AUTHORITY + \"/\" + PATH_PRODUCT;\n public static final String CONTENT_ITEM_TYPE = \"vnd.android.cursor.item/\" + CONTENT_AUTHORITY + \"/\" + PATH_PRODUCT;\n\n // Table name\n public static final String TABLE_NAME = \"product\";\n\n //Fields\n public static final String COLUMN_ID = \"id\";\n public static final String COLUMN_TITLE = \"title\";\n public static final String COLUMN_SKU = \"sku\";\n public static final String COLUMN_PRICE = \"price\";\n public static final String COLUMN_STOCK = \"stock\";\n\n public static final String COLUMN_JSON = \"json\";\n public static final String COLUMN_ENABLE = \"enable\";\n\n public static Uri buildOrderUri(long id) {\n return ContentUris.withAppendedId(CONTENT_URI, id);\n }\n\n }\n\n public static final class CustomerEntry implements BaseColumns {\n\n public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_CUSTOMER).build();\n public static final String CONTENT_TYPE = \"vnd.android.cursor.dir/\" + CONTENT_AUTHORITY + \"/\" + PATH_CUSTOMER;\n public static final String CONTENT_ITEM_TYPE = \"vnd.android.cursor.item/\" + CONTENT_AUTHORITY + \"/\" + PATH_CUSTOMER;\n\n // Table name\n public static final String TABLE_NAME = \"customer\";\n\n //Fields\n public static final String COLUMN_ID = \"id\";\n public static final String COLUMN_EMAIL = \"email\";\n public static final String COLUMN_FIRST_NAME = \"first_name\";\n public static final String COLUMN_LAST_NAME = \"last_name\";\n public static final String COLUMN_USERNAME = \"username\";\n public static final String COLUMN_LAST_ORDER_ID = \"last_order_id\";\n\n public static final String COLUMN_SHIPPING_FIRST_NAME = \"shipping_first_name\";\n public static final String COLUMN_SHIPPING_LAST_NAME = \"shipping_last_name\";\n public static final String COLUMN_SHIPPING_PHONE = \"shipping_phone\";\n\n public static final String COLUMN_BILLING_FIRST_NAME = \"billing_first_name\";\n public static final String COLUMN_BILLING_LAST_NAME = \"billing_last_name\";\n public static final String COLUMN_BILLING_PHONE = \"billing_phone\";\n\n public static final String COLUMN_JSON = \"json\";\n public static final String COLUMN_ENABLE = \"enable\";\n\n public static Uri buildOrderUri(long id) {\n return ContentUris.withAppendedId(CONTENT_URI, id);\n }\n\n }\n\n}",
"public class BillingAddress {\n\n @SerializedName(\"first_name\")\n private String firstName;\n @SerializedName(\"last_name\")\n private String lastName;\n private String company;\n @SerializedName(\"address_1\")\n private String addressOne;\n @SerializedName(\"address_2\")\n private String addressTwo;\n private String city;\n private String state;\n private String postcode;\n private String country;\n private String email;\n private String phone;\n\n public String getFirstName() {\n return firstName;\n }\n\n public void setFirstName(String firstName) {\n this.firstName = firstName;\n }\n\n public String getLastName() {\n return lastName;\n }\n\n public void setLastName(String lastName) {\n this.lastName = lastName;\n }\n\n public String getCompany() {\n return company;\n }\n\n public void setCompany(String company) {\n this.company = company;\n }\n\n public String getAddressOne() {\n return addressOne;\n }\n\n public void setAddressOne(String addressOne) {\n this.addressOne = addressOne;\n }\n\n public String getAddressTwo() {\n return addressTwo;\n }\n\n public void setAddressTwo(String addressTwo) {\n this.addressTwo = addressTwo;\n }\n\n public String getCity() {\n return city;\n }\n\n public void setCity(String city) {\n this.city = city;\n }\n\n public String getState() {\n return state;\n }\n\n public void setState(String state) {\n this.state = state;\n }\n\n public String getPostcode() {\n return postcode;\n }\n\n public void setPostcode(String postcode) {\n this.postcode = postcode;\n }\n\n public String getCountry() {\n return country;\n }\n\n public void setCountry(String country) {\n this.country = country;\n }\n\n public String getEmail() {\n return email;\n }\n\n public void setEmail(String email) {\n this.email = email;\n }\n\n public String getPhone() {\n return phone;\n }\n\n public void setPhone(String phone) {\n this.phone = phone;\n }\n\n}",
"public class Item {\n\n private Integer id;\n private String name;\n private String sku;\n @SerializedName(\"product_id\")\n private Integer productId;\n @SerializedName(\"variation_id\")\n private Integer variationId;\n private Integer quantity;\n @SerializedName(\"tax_class\")\n private String taxClass;\n private String price;\n private String subtotal;\n @SerializedName(\"subtotal_tax\")\n private String subtotalTax;\n private String total;\n @SerializedName(\"total_tax\")\n private String totalTax;\n\n private List<MetaItem> meta = new ArrayList<>();\n @SerializedName(\"cogs_cost\")\n private String cogsCost;\n @SerializedName(\"cogs_total_cost\")\n private String cogsTotalCost;\n\n public Integer getId() {\n return id;\n }\n\n public void setId(Integer id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getSku() {\n return sku;\n }\n\n public void setSku(String sku) {\n this.sku = sku;\n }\n\n public Integer getProductId() {\n return productId;\n }\n\n public void setProductId(Integer productId) {\n this.productId = productId;\n }\n\n public Integer getVariationId() {\n return variationId;\n }\n\n public void setVariationId(Integer variationId) {\n this.variationId = variationId;\n }\n\n public Integer getQuantity() {\n return quantity;\n }\n\n public void setQuantity(Integer quantity) {\n this.quantity = quantity;\n }\n\n public String getTaxClass() {\n return taxClass;\n }\n\n public void setTaxClass(String taxClass) {\n this.taxClass = taxClass;\n }\n\n public String getPrice() {\n return price;\n }\n\n public void setPrice(String price) {\n this.price = price;\n }\n\n public String getSubtotal() {\n return subtotal;\n }\n\n public void setSubtotal(String subtotal) {\n this.subtotal = subtotal;\n }\n\n public String getSubtotalTax() {\n return subtotalTax;\n }\n\n public void setSubtotalTax(String subtotalTax) {\n this.subtotalTax = subtotalTax;\n }\n\n public String getTotal() {\n return total;\n }\n\n public void setTotal(String total) {\n this.total = total;\n }\n\n public String getTotalTax() {\n return totalTax;\n }\n\n public void setTotalTax(String totalTax) {\n this.totalTax = totalTax;\n }\n\n public List<MetaItem> getMeta() {\n return meta;\n }\n\n public void setMeta(List<MetaItem> meta) {\n this.meta = meta;\n }\n\n public String getCogsCost() {\n return cogsCost;\n }\n\n public void setCogsCost(String cogsCost) {\n this.cogsCost = cogsCost;\n }\n\n public String getCogsTotalCost() {\n return cogsTotalCost;\n }\n\n public void setCogsTotalCost(String cogsTotalCost) {\n this.cogsTotalCost = cogsTotalCost;\n }\n}",
"public class Order {\n\n private int id;\n @SerializedName(\"order_number\")\n private String orderNumber;\n @SerializedName(\"created_at\")\n private Date createdAt;\n @SerializedName(\"updated_at\")\n private Date updatedAt;\n @SerializedName(\"completed_at\")\n private Date completedAt;\n private String status;\n private String currency;\n private String total;\n private String subtotal;\n @SerializedName(\"total_line_items_quantity\")\n private int totalLineItemsQuantity;\n @SerializedName(\"total_tax\")\n private String totalTax;\n @SerializedName(\"total_shipping\")\n private String totalShipping;\n @SerializedName(\"cart_tax\")\n private String cartTax;\n @SerializedName(\"shipping_tax\")\n private String shippingTax;\n @SerializedName(\"total_discount\")\n private String totalDiscount;\n @SerializedName(\"cart_discount\")\n private String cartDiscount;\n @SerializedName(\"order_discount\")\n private String orderDiscount;\n @SerializedName(\"shipping_methods\")\n private String shippingMethods;\n\n @SerializedName(\"payment_details\")\n private PaymentDetails paymentDetails;\n @SerializedName(\"billing_address\")\n private BillingAddress billingAddress;\n @SerializedName(\"shipping_address\")\n private ShippingAddress shippingAddress;\n @SerializedName(\"shipping_lines\")\n private List<ShippingLine> shippingLines = new ArrayList<>();\n\n\n private String note;\n @SerializedName(\"customer_ip\")\n private String customerIp;\n @SerializedName(\"customer_user_agent\")\n private String customerUserAgent;\n @SerializedName(\"customer_id\")\n private String customerId;\n @SerializedName(\"view_order_url\")\n private String viewOrderUrl;\n\n @SerializedName(\"line_items\")\n private List<Item> items = new ArrayList<>();\n\n @SerializedName(\"coupon_lines\")\n private List<CouponLine> couponLines = new ArrayList<>();\n\n private Customer customer;\n\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public String getOrderNumber() {\n return orderNumber;\n }\n\n public void setOrderNumber(String orderNumber) {\n this.orderNumber = orderNumber;\n }\n\n public Date getCreatedAt() {\n return createdAt;\n }\n\n public void setCreatedAt(Date createdAt) {\n this.createdAt = createdAt;\n }\n\n public Date getUpdatedAt() {\n return updatedAt;\n }\n\n public void setUpdatedAt(Date updatedAt) {\n this.updatedAt = updatedAt;\n }\n\n public Date getCompletedAt() {\n return completedAt;\n }\n\n public void setCompletedAt(Date completedAt) {\n this.completedAt = completedAt;\n }\n\n public String getStatus() {\n return status;\n }\n\n public void setStatus(String status) {\n this.status = status;\n }\n\n public String getCurrency() {\n return currency;\n }\n\n public void setCurrency(String currency) {\n this.currency = currency;\n }\n\n public String getTotal() {\n return total;\n }\n\n public void setTotal(String total) {\n this.total = total;\n }\n\n public String getSubtotal() {\n return subtotal;\n }\n\n public void setSubtotal(String subtotal) {\n this.subtotal = subtotal;\n }\n\n public int getTotalLineItemsQuantity() {\n return totalLineItemsQuantity;\n }\n\n public void setTotalLineItemsQuantity(int totalLineItemsQuantity) {\n this.totalLineItemsQuantity = totalLineItemsQuantity;\n }\n\n public String getTotalTax() {\n return totalTax;\n }\n\n public void setTotalTax(String totalTax) {\n this.totalTax = totalTax;\n }\n\n public String getTotalShipping() {\n return totalShipping;\n }\n\n public void setTotalShipping(String totalShipping) {\n this.totalShipping = totalShipping;\n }\n\n public String getCartTax() {\n return cartTax;\n }\n\n public void setCartTax(String cartTax) {\n this.cartTax = cartTax;\n }\n\n public String getShippingTax() {\n return shippingTax;\n }\n\n public void setShippingTax(String shippingTax) {\n this.shippingTax = shippingTax;\n }\n\n public String getTotalDiscount() {\n return totalDiscount;\n }\n\n public void setTotalDiscount(String totalDiscount) {\n this.totalDiscount = totalDiscount;\n }\n\n public String getCartDiscount() {\n return cartDiscount;\n }\n\n public void setCartDiscount(String cartDiscount) {\n this.cartDiscount = cartDiscount;\n }\n\n public String getOrderDiscount() {\n return orderDiscount;\n }\n\n public void setOrderDiscount(String orderDiscount) {\n this.orderDiscount = orderDiscount;\n }\n\n public String getShippingMethods() {\n return shippingMethods;\n }\n\n public void setShippingMethods(String shippingMethods) {\n this.shippingMethods = shippingMethods;\n }\n\n public PaymentDetails getPaymentDetails() {\n return paymentDetails;\n }\n\n public void setPaymentDetails(PaymentDetails paymentDetails) {\n this.paymentDetails = paymentDetails;\n }\n\n public BillingAddress getBillingAddress() {\n return billingAddress;\n }\n\n public void setBillingAddress(BillingAddress billingAddress) {\n this.billingAddress = billingAddress;\n }\n\n public ShippingAddress getShippingAddress() {\n return shippingAddress;\n }\n\n public void setShippingAddress(ShippingAddress shippingAddress) {\n this.shippingAddress = shippingAddress;\n }\n\n public List<ShippingLine> getShippingLines() {\n return shippingLines;\n }\n\n public void setShippingLines(List<ShippingLine> shippingLines) {\n this.shippingLines = shippingLines;\n }\n\n public String getNote() {\n return note;\n }\n\n public void setNote(String note) {\n this.note = note;\n }\n\n public String getCustomerIp() {\n return customerIp;\n }\n\n public void setCustomerIp(String customerIp) {\n this.customerIp = customerIp;\n }\n\n public String getCustomerUserAgent() {\n return customerUserAgent;\n }\n\n public void setCustomerUserAgent(String customerUserAgent) {\n this.customerUserAgent = customerUserAgent;\n }\n\n public String getCustomerId() {\n return customerId;\n }\n\n public void setCustomerId(String customerId) {\n this.customerId = customerId;\n }\n\n public String getViewOrderUrl() {\n return viewOrderUrl;\n }\n\n public void setViewOrderUrl(String viewOrderUrl) {\n this.viewOrderUrl = viewOrderUrl;\n }\n\n public List<Item> getItems() {\n return items;\n }\n\n public void setItems(List<Item> items) {\n this.items = items;\n }\n\n public Customer getCustomer() {\n return customer;\n }\n\n public void setCustomer(Customer customer) {\n this.customer = customer;\n }\n\n public List<CouponLine> getCouponLines() {\n return couponLines;\n }\n\n public void setCouponLines(List<CouponLine> couponLines) {\n this.couponLines = couponLines;\n }\n}",
"public class Product {\n\n private String title;\n private int id;\n @SerializedName(\"created_at\")\n private Date createdAt;\n @SerializedName(\"updated_at\")\n private Date updatedAt;\n private String type;\n private String status;\n private boolean downloadable;\n private boolean virtual;\n private String permalink;\n private String sku;\n private String price;\n @SerializedName(\"regular_price\")\n private String regularPrice;\n @SerializedName(\"sale_price\")\n private String salePrice;\n @SerializedName(\"price_html\")\n private String priceHtml;\n private boolean taxable;\n @SerializedName(\"tax_status\")\n private String taxStatus;\n @SerializedName(\"tax_class\")\n private String taxClass;\n @SerializedName(\"managing_stock\")\n private boolean managingStock;\n @SerializedName(\"stock_quantity\")\n private int stockQuantity;\n @SerializedName(\"in_stock\")\n private boolean inStock;\n @SerializedName(\"backorders_allowed\")\n private boolean backordersAllowed;\n private boolean backordered;\n @SerializedName(\"sold_individually\")\n private boolean soldIndividually;\n private boolean purchaseable;\n private boolean featured;\n private boolean visible;\n @SerializedName(\"catalog_visibility\")\n private String catalogVisibility;\n @SerializedName(\"on_sale\")\n private boolean onSale;\n private String weight;\n private Dimensions dimensions;\n @SerializedName(\"shipping_required\")\n private boolean shippingRequired;\n @SerializedName(\"shipping_taxable\")\n private boolean shippingTaxable;\n @SerializedName(\"shipping_class\")\n private String shippingClass;\n @SerializedName(\"shipping_class_id\")\n private int shippingClassId;\n private String description;\n @SerializedName(\"short_description\")\n private String shortDescription;\n @SerializedName(\"reviews_allowed\")\n private boolean reviewsAllowed;\n @SerializedName(\"average_rating\")\n private String averageRating;\n @SerializedName(\"rating_count\")\n private int ratingCount;\n @SerializedName(\"related_ids\")\n private List<Integer> relatedIds;\n @SerializedName(\"upsell_ids\")\n private List<Integer> upsellIds;\n @SerializedName(\"cross_sell_ids\")\n private List<Integer> crossSellIds;\n @SerializedName(\"parent_id\")\n private int parentId;\n private List<String> categories;\n private List<String> tags;\n private List<Images> images;\n @SerializedName(\"featured_src\")\n private String featuredSrc;\n private List<Attributes> attributes;\n //\"downloads\": [],\n @SerializedName(\"download_limit\")\n private int downloadLimit;\n @SerializedName(\"download_expiry\")\n private int downloadExpiry;\n @SerializedName(\"download_type\")\n private String downloadType;\n @SerializedName(\"purchase_note\")\n private String purchaseNote;\n @SerializedName(\"total_sales\")\n private int totalSales;\n private List<Variation> variations;\n //\"parent\": []\n @SerializedName(\"cogs_cost\")\n private String cogsCost;\n\n public String getTitle() {\n return title;\n }\n\n public void setTitle(String title) {\n this.title = title;\n }\n\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public Date getCreatedAt() {\n return createdAt;\n }\n\n public void setCreatedAt(Date createdAt) {\n this.createdAt = createdAt;\n }\n\n public Date getUpdatedAt() {\n return updatedAt;\n }\n\n public void setUpdatedAt(Date updatedAt) {\n this.updatedAt = updatedAt;\n }\n\n public String getType() {\n return type;\n }\n\n public void setType(String type) {\n this.type = type;\n }\n\n public String getStatus() {\n return status;\n }\n\n public void setStatus(String status) {\n this.status = status;\n }\n\n public boolean isDownloadable() {\n return downloadable;\n }\n\n public void setDownloadable(boolean downloadable) {\n this.downloadable = downloadable;\n }\n\n public boolean isVirtual() {\n return virtual;\n }\n\n public void setVirtual(boolean virtual) {\n this.virtual = virtual;\n }\n\n public String getPermalink() {\n return permalink;\n }\n\n public void setPermalink(String permalink) {\n this.permalink = permalink;\n }\n\n public String getSku() {\n return sku;\n }\n\n public void setSku(String sku) {\n this.sku = sku;\n }\n\n public String getPrice() {\n return price;\n }\n\n public void setPrice(String price) {\n this.price = price;\n }\n\n public String getRegularPrice() {\n return regularPrice;\n }\n\n public void setRegularPrice(String regularPrice) {\n this.regularPrice = regularPrice;\n }\n\n public String getSalePrice() {\n return salePrice;\n }\n\n public void setSalePrice(String salePrice) {\n this.salePrice = salePrice;\n }\n\n public String getPriceHtml() {\n return priceHtml;\n }\n\n public void setPriceHtml(String priceHtml) {\n this.priceHtml = priceHtml;\n }\n\n public boolean isTaxable() {\n return taxable;\n }\n\n public void setTaxable(boolean taxable) {\n this.taxable = taxable;\n }\n\n public String getTaxStatus() {\n return taxStatus;\n }\n\n public void setTaxStatus(String taxStatus) {\n this.taxStatus = taxStatus;\n }\n\n public String getTaxClass() {\n return taxClass;\n }\n\n public void setTaxClass(String taxClass) {\n this.taxClass = taxClass;\n }\n\n public boolean isManagingStock() {\n return managingStock;\n }\n\n public void setManagingStock(boolean managingStock) {\n this.managingStock = managingStock;\n }\n\n public int getStockQuantity() {\n return stockQuantity;\n }\n\n public void setStockQuantity(int stockQuantity) {\n this.stockQuantity = stockQuantity;\n }\n\n public boolean isInStock() {\n return inStock;\n }\n\n public void setInStock(boolean inStock) {\n this.inStock = inStock;\n }\n\n public boolean isBackordersAllowed() {\n return backordersAllowed;\n }\n\n public void setBackordersAllowed(boolean backordersAllowed) {\n this.backordersAllowed = backordersAllowed;\n }\n\n public boolean isBackordered() {\n return backordered;\n }\n\n public void setBackordered(boolean backordered) {\n this.backordered = backordered;\n }\n\n public boolean isSoldIndividually() {\n return soldIndividually;\n }\n\n public void setSoldIndividually(boolean soldIndividually) {\n this.soldIndividually = soldIndividually;\n }\n\n public boolean isPurchaseable() {\n return purchaseable;\n }\n\n public void setPurchaseable(boolean purchaseable) {\n this.purchaseable = purchaseable;\n }\n\n public boolean isFeatured() {\n return featured;\n }\n\n public void setFeatured(boolean featured) {\n this.featured = featured;\n }\n\n public boolean isVisible() {\n return visible;\n }\n\n public void setVisible(boolean visible) {\n this.visible = visible;\n }\n\n public String getCatalogVisibility() {\n return catalogVisibility;\n }\n\n public void setCatalogVisibility(String catalogVisibility) {\n this.catalogVisibility = catalogVisibility;\n }\n\n public boolean isOnSale() {\n return onSale;\n }\n\n public void setOnSale(boolean onSale) {\n this.onSale = onSale;\n }\n\n public String getWeight() {\n return weight;\n }\n\n public void setWeight(String weight) {\n this.weight = weight;\n }\n\n public Dimensions getDimensions() {\n return dimensions;\n }\n\n public void setDimensions(Dimensions dimensions) {\n this.dimensions = dimensions;\n }\n\n public boolean isShippingRequired() {\n return shippingRequired;\n }\n\n public void setShippingRequired(boolean shippingRequired) {\n this.shippingRequired = shippingRequired;\n }\n\n public boolean isShippingTaxable() {\n return shippingTaxable;\n }\n\n public void setShippingTaxable(boolean shippingTaxable) {\n this.shippingTaxable = shippingTaxable;\n }\n\n public String getShippingClass() {\n return shippingClass;\n }\n\n public void setShippingClass(String shippingClass) {\n this.shippingClass = shippingClass;\n }\n\n public int getShippingClassId() {\n return shippingClassId;\n }\n\n public void setShippingClassId(int shippingClassId) {\n this.shippingClassId = shippingClassId;\n }\n\n public String getDescription() {\n return description;\n }\n\n public void setDescription(String description) {\n this.description = description;\n }\n\n public String getShortDescription() {\n return shortDescription;\n }\n\n public void setShortDescription(String shortDescription) {\n this.shortDescription = shortDescription;\n }\n\n public boolean isReviewsAllowed() {\n return reviewsAllowed;\n }\n\n public void setReviewsAllowed(boolean reviewsAllowed) {\n this.reviewsAllowed = reviewsAllowed;\n }\n\n public String getAverageRating() {\n return averageRating;\n }\n\n public void setAverageRating(String averageRating) {\n this.averageRating = averageRating;\n }\n\n public int getRatingCount() {\n return ratingCount;\n }\n\n public void setRatingCount(int ratingCount) {\n this.ratingCount = ratingCount;\n }\n\n public List<Integer> getRelatedIds() {\n return relatedIds;\n }\n\n public void setRelatedIds(List<Integer> relatedIds) {\n this.relatedIds = relatedIds;\n }\n\n public List<Integer> getUpsellIds() {\n return upsellIds;\n }\n\n public void setUpsellIds(List<Integer> upsellIds) {\n this.upsellIds = upsellIds;\n }\n\n public List<Integer> getCrossSellIds() {\n return crossSellIds;\n }\n\n public void setCrossSellIds(List<Integer> crossSellIds) {\n this.crossSellIds = crossSellIds;\n }\n\n public int getParentId() {\n return parentId;\n }\n\n public void setParentId(int parentId) {\n this.parentId = parentId;\n }\n\n public List<String> getCategories() {\n return categories;\n }\n\n public void setCategories(List<String> categories) {\n this.categories = categories;\n }\n\n public List<String> getTags() {\n return tags;\n }\n\n public void setTags(List<String> tags) {\n this.tags = tags;\n }\n\n public List<Images> getImages() {\n return images;\n }\n\n public void setImages(List<Images> images) {\n this.images = images;\n }\n\n public String getFeaturedSrc() {\n return featuredSrc;\n }\n\n public void setFeaturedSrc(String featuredSrc) {\n this.featuredSrc = featuredSrc;\n }\n\n public List<Attributes> getAttributes() {\n return attributes;\n }\n\n public void setAttributes(List<Attributes> attributes) {\n this.attributes = attributes;\n }\n\n public int getDownloadLimit() {\n return downloadLimit;\n }\n\n public void setDownloadLimit(int downloadLimit) {\n this.downloadLimit = downloadLimit;\n }\n\n public int getDownloadExpiry() {\n return downloadExpiry;\n }\n\n public void setDownloadExpiry(int downloadExpiry) {\n this.downloadExpiry = downloadExpiry;\n }\n\n public String getDownloadType() {\n return downloadType;\n }\n\n public void setDownloadType(String downloadType) {\n this.downloadType = downloadType;\n }\n\n public String getPurchaseNote() {\n return purchaseNote;\n }\n\n public void setPurchaseNote(String purchaseNote) {\n this.purchaseNote = purchaseNote;\n }\n\n public int getTotalSales() {\n return totalSales;\n }\n\n public void setTotalSales(int totalSales) {\n this.totalSales = totalSales;\n }\n\n public List<Variation> getVariations() {\n return variations;\n }\n\n public void setVariations(List<Variation> variations) {\n this.variations = variations;\n }\n\n public String getCogsCost() {\n return cogsCost;\n }\n\n public void setCogsCost(String cogsCost) {\n this.cogsCost = cogsCost;\n }\n}",
"public class ProductResponse {\n\n private Product product;\n\n public Product getProduct() {\n return product;\n }\n\n public void setProduct(Product product) {\n this.product = product;\n }\n}",
"public class Variation {\n\n private int id;\n @SerializedName(\"created_at\")\n private Date createdAt;\n @SerializedName(\"updated_at\")\n private Date updatedAt;\n private boolean downloadable;\n private boolean virtual;\n private String permalink;\n private String sku;\n private String price;\n @SerializedName(\"regular_price\")\n private String regularPrice;\n @SerializedName(\"sale_price\")\n private String salePrice;\n private boolean taxable;\n @SerializedName(\"tax_status\")\n private String taxStatus;\n @SerializedName(\"tax_class\")\n private String taxClass;\n @SerializedName(\"managing_stock\")\n private boolean managingStock;\n @SerializedName(\"stock_quantity\")\n private int stockQuantity;\n @SerializedName(\"in_stock\")\n private boolean inStock;\n private boolean backordered;\n private boolean purchaseable;\n private boolean visible;\n @SerializedName(\"on_sale\")\n private boolean onSale;\n private String weight;\n private Dimensions dimensions;\n @SerializedName(\"shipping_class\")\n private String shippingClass;\n @SerializedName(\"shipping_class_id\")\n private int shippingClassId;\n //\"downloads\": [],\n private List<Images> image;\n private List<Attributes> attributes;\n @SerializedName(\"download_limit\")\n private int downloadLimit;\n @SerializedName(\"download_expiry\")\n private int downloadExpiry;\n\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public Date getCreatedAt() {\n return createdAt;\n }\n\n public void setCreatedAt(Date createdAt) {\n this.createdAt = createdAt;\n }\n\n public Date getUpdatedAt() {\n return updatedAt;\n }\n\n public void setUpdatedAt(Date updatedAt) {\n this.updatedAt = updatedAt;\n }\n\n public boolean isDownloadable() {\n return downloadable;\n }\n\n public void setDownloadable(boolean downloadable) {\n this.downloadable = downloadable;\n }\n\n public boolean isVirtual() {\n return virtual;\n }\n\n public void setVirtual(boolean virtual) {\n this.virtual = virtual;\n }\n\n public String getPermalink() {\n return permalink;\n }\n\n public void setPermalink(String permalink) {\n this.permalink = permalink;\n }\n\n public String getSku() {\n return sku;\n }\n\n public void setSku(String sku) {\n this.sku = sku;\n }\n\n public String getPrice() {\n return price;\n }\n\n public void setPrice(String price) {\n this.price = price;\n }\n\n public String getRegularPrice() {\n return regularPrice;\n }\n\n public void setRegularPrice(String regularPrice) {\n this.regularPrice = regularPrice;\n }\n\n public String getSalePrice() {\n return salePrice;\n }\n\n public void setSalePrice(String salePrice) {\n this.salePrice = salePrice;\n }\n\n public boolean isTaxable() {\n return taxable;\n }\n\n public void setTaxable(boolean taxable) {\n this.taxable = taxable;\n }\n\n public String getTaxStatus() {\n return taxStatus;\n }\n\n public void setTaxStatus(String taxStatus) {\n this.taxStatus = taxStatus;\n }\n\n public String getTaxClass() {\n return taxClass;\n }\n\n public void setTaxClass(String taxClass) {\n this.taxClass = taxClass;\n }\n\n public boolean isManagingStock() {\n return managingStock;\n }\n\n public void setManagingStock(boolean managingStock) {\n this.managingStock = managingStock;\n }\n\n public int getStockQuantity() {\n return stockQuantity;\n }\n\n public void setStockQuantity(int stockQuantity) {\n this.stockQuantity = stockQuantity;\n }\n\n public boolean isInStock() {\n return inStock;\n }\n\n public void setInStock(boolean inStock) {\n this.inStock = inStock;\n }\n\n public boolean isBackordered() {\n return backordered;\n }\n\n public void setBackordered(boolean backordered) {\n this.backordered = backordered;\n }\n\n public boolean isPurchaseable() {\n return purchaseable;\n }\n\n public void setPurchaseable(boolean purchaseable) {\n this.purchaseable = purchaseable;\n }\n\n public boolean isVisible() {\n return visible;\n }\n\n public void setVisible(boolean visible) {\n this.visible = visible;\n }\n\n public boolean isOnSale() {\n return onSale;\n }\n\n public void setOnSale(boolean onSale) {\n this.onSale = onSale;\n }\n\n public String getWeight() {\n return weight;\n }\n\n public void setWeight(String weight) {\n this.weight = weight;\n }\n\n public Dimensions getDimensions() {\n return dimensions;\n }\n\n public void setDimensions(Dimensions dimensions) {\n this.dimensions = dimensions;\n }\n\n public String getShippingClass() {\n return shippingClass;\n }\n\n public void setShippingClass(String shippingClass) {\n this.shippingClass = shippingClass;\n }\n\n public int getShippingClassId() {\n return shippingClassId;\n }\n\n public void setShippingClassId(int shippingClassId) {\n this.shippingClassId = shippingClassId;\n }\n\n public List<Images> getImage() {\n return image;\n }\n\n public void setImage(List<Images> image) {\n this.image = image;\n }\n\n public List<Attributes> getAttributes() {\n return attributes;\n }\n\n public void setAttributes(List<Attributes> attributes) {\n this.attributes = attributes;\n }\n\n public int getDownloadLimit() {\n return downloadLimit;\n }\n\n public void setDownloadLimit(int downloadLimit) {\n this.downloadLimit = downloadLimit;\n }\n\n public int getDownloadExpiry() {\n return downloadExpiry;\n }\n\n public void setDownloadExpiry(int downloadExpiry) {\n this.downloadExpiry = downloadExpiry;\n }\n}",
"public class Utility {\n\n public static final String LOG_TAG = Utility.class.getSimpleName();\n\n public static String getPreferredUser(Context context) {\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n return prefs.getString(context.getString(R.string.pref_user_key),null);\n }\n\n public static String getPreferredSecret(Context context) {\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n return prefs.getString(context.getString(R.string.pref_secret_key),null);\n }\n\n public static Long getPreferredLastSync(Context context) {\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n return prefs.getLong(context.getString(R.string.pref_last_update_key), 0);\n }\n\n public static String getPreferredServer(Context context) {\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n return prefs.getString(context.getString(R.string.pref_server), null);\n }\n\n public static Long setPreferredLastSync(Context context, Long time) {\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n SharedPreferences.Editor editor = prefs.edit();\n editor.putLong(context.getString(R.string.pref_last_update_key), time);\n editor.apply();\n return prefs.getLong(context.getString(R.string.pref_last_update_key), 0);\n }\n\n public static void setPreferredUserSecret(Context context, String user, String secret) {\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n SharedPreferences.Editor editor = prefs.edit();\n editor.putString(context.getString(R.string.pref_user_key), user);\n editor.putString(context.getString(R.string.pref_secret_key), secret);\n editor.apply();\n }\n\n public static String setPreferredServer(Context context, String server) {\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n SharedPreferences.Editor editor = prefs.edit();\n editor.putString(context.getString(R.string.pref_server), server);\n editor.apply();\n return prefs.getString(context.getString(R.string.pref_server),null);\n }\n\n public static String getPreferredShoppingCard(Context context) {\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n return prefs.getString(context.getString(R.string.pref_shopping_cart),null);\n }\n\n public static String setPreferredShoppingCard(Context context, String json) {\n SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);\n SharedPreferences.Editor editor = prefs.edit();\n editor.putString(context.getString(R.string.pref_shopping_cart), json);\n editor.apply();\n return prefs.getString(context.getString(R.string.pref_shopping_cart),null);\n }\n\n public static SSLSocketFactory getSSLSocketFactory(){\n //TODO USE THIS ONLY FOR TESTING\n try {\n // Create a trust manager that does not validate certificate chains\n TrustManager[] trustAllCerts = new TrustManager[]{\n new X509TrustManager() {\n public java.security.cert.X509Certificate[] getAcceptedIssuers() {\n return new X509Certificate[0];\n }\n\n public void checkClientTrusted(X509Certificate[] certs, String authType) {\n }\n\n public void checkServerTrusted(X509Certificate[] certs, String authType) {\n }\n }\n };\n // Install the all-trusting trust manager\n SSLContext sc = SSLContext.getInstance(\"SSL\");\n sc.init(null, trustAllCerts, new java.security.SecureRandom());\n return sc.getSocketFactory();\n }catch (Exception ex){\n\n }\n return null;\n }\n\n public static HostnameVerifier getHostnameVerifier(){\n //TODO USE THIS ONLY FOR TESTING\n // Create all-trusting host name verifier\n HostnameVerifier allHostsValid = new HostnameVerifier() {\n public boolean verify(String hostname, SSLSession session) {\n return true;\n }\n };\n return allHostsValid;\n }\n\n}"
] | import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import app.bennsandoval.com.woodmin.R;
import app.bennsandoval.com.woodmin.Woodmin;
import app.bennsandoval.com.woodmin.data.WoodminContract;
import app.bennsandoval.com.woodmin.models.v3.customers.BillingAddress;
import app.bennsandoval.com.woodmin.models.v3.orders.Item;
import app.bennsandoval.com.woodmin.models.v3.orders.Order;
import app.bennsandoval.com.woodmin.models.v3.products.Product;
import app.bennsandoval.com.woodmin.models.v3.products.ProductResponse;
import app.bennsandoval.com.woodmin.models.v3.products.Variation;
import app.bennsandoval.com.woodmin.utilities.Utility;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response; | if(mProductId < 0 ) {
mProductId = getIntent().getIntExtra("product", -1);
}
String query = WoodminContract.ProductEntry.COLUMN_ID + " == ?" ;
String[] parametersOrder = new String[]{ String.valueOf(mProductId) };
Cursor cursor = getContentResolver().query(WoodminContract.ProductEntry.CONTENT_URI,
PRODUCT_PROJECTION,
query,
parametersOrder,
null);
if(cursor != null) {
if (cursor.moveToFirst()) {
do {
String json = cursor.getString(COLUMN_PRODUCT_COLUMN_JSON);
if(json!=null){
mProductSelected = mGson.fromJson(json, Product.class);
}
} while (cursor.moveToNext());
}
cursor.close();
}
String json = Utility.getPreferredShoppingCard(getApplicationContext());
if(json != null) {
mOrder = mGson.fromJson(json, Order.class);
if(mOrder.getBillingAddress() == null) {
BillingAddress billingAddress = new BillingAddress();
billingAddress.setCompany(getString(R.string.default_company));
billingAddress.setFirstName(getString(R.string.default_first_name));
billingAddress.setLastName(getString(R.string.default_last_name));
billingAddress.setAddressOne(getString(R.string.default_line_one));
billingAddress.setAddressTwo(getString(R.string.default_line_two));
billingAddress.setCity(getString(R.string.default_city));
billingAddress.setState(getString(R.string.default_state));
billingAddress.setPostcode(getString(R.string.default_postal_code));
billingAddress.setCountry(getString(R.string.default_country));
billingAddress.setEmail(getString(R.string.default_email));
billingAddress.setPhone(getString(R.string.default_phone));
mOrder.setBillingAddress(billingAddress);
Utility.setPreferredShoppingCard(getApplicationContext(), mGson.toJson(mOrder));
}
} else {
mOrder = new Order();
BillingAddress billingAddress = new BillingAddress();
billingAddress.setCompany(getString(R.string.default_company));
billingAddress.setFirstName(getString(R.string.default_first_name));
billingAddress.setLastName(getString(R.string.default_last_name));
billingAddress.setAddressOne(getString(R.string.default_line_one));
billingAddress.setAddressTwo(getString(R.string.default_line_two));
billingAddress.setCity(getString(R.string.default_city));
billingAddress.setState(getString(R.string.default_state));
billingAddress.setPostcode(getString(R.string.default_postal_code));
billingAddress.setCountry(getString(R.string.default_country));
billingAddress.setEmail(getString(R.string.default_email));
billingAddress.setPhone(getString(R.string.default_phone));
mOrder.setBillingAddress(billingAddress);
Utility.setPreferredShoppingCard(getApplicationContext(), mGson.toJson(mOrder));
}
Button remove = (Button)findViewById(R.id.less);
Button add = (Button)findViewById(R.id.more);
Button cancel = (Button)findViewById(R.id.cancel);
Button ok = (Button)findViewById(R.id.ok);
remove.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), getString(R.string.product_updated_wip), Toast.LENGTH_LONG).show();
}
});
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), getString(R.string.product_updated_wip), Toast.LENGTH_LONG).show();
}
});
cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
ok.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), getString(R.string.product_updated_wip), Toast.LENGTH_LONG).show();
}
});
fillView(false);
getProduct();
}
private void updateProduct() {
mProductSelected.setStockQuantity(mProductSelected.getStockQuantity() - mQuantity);
ArrayList<ContentValues> productsValues = new ArrayList<>();
ContentValues productValues = new ContentValues();
productValues.put(WoodminContract.ProductEntry.COLUMN_ID, mProductSelected.getId());
productValues.put(WoodminContract.ProductEntry.COLUMN_TITLE, mProductSelected.getTitle());
productValues.put(WoodminContract.ProductEntry.COLUMN_SKU, mProductSelected.getSku());
productValues.put(WoodminContract.ProductEntry.COLUMN_PRICE, mProductSelected.getPrice());
productValues.put(WoodminContract.ProductEntry.COLUMN_STOCK, mProductSelected.getStockQuantity());
productValues.put(WoodminContract.ProductEntry.COLUMN_JSON, mGson.toJson(mProductSelected));
productValues.put(WoodminContract.ProductEntry.COLUMN_ENABLE, 1);
productsValues.add(productValues);
| for(Variation variation:mProductSelected.getVariations()) { | 7 |
jankroken/commandline | src/main/java/com/github/jankroken/commandline/CommandLineParser.java | [
"public abstract class CommandLineException extends RuntimeException {\n private static final long serialVersionUID = 1L;\n\n protected CommandLineException() {\n }\n\n protected CommandLineException(String message) {\n super(message);\n }\n\n protected CommandLineException(String message, Throwable cause) {\n super(message, cause);\n }\n\n protected CommandLineException(Throwable cause) {\n super(cause);\n }\n\n protected CommandLineException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {\n super(message, cause, enableSuppression, writableStackTrace);\n }\n}",
"public class LongOrCompactTokenizer implements Tokenizer {\n\n private static final Pattern SWITCH_PATTERN = Pattern.compile(\"-.*\");\n private static final Pattern LONG_STYLE_SWITCH_PATTERN = Pattern.compile(\"--..*\");\n private static final Pattern SHORT_STYLE_SWITCH_PATTERN = Pattern.compile(\"-[^-].*\");\n private final PeekIterator<String> stringIterator;\n private boolean argumentEscapeEncountered;\n private String argumentTerminator;\n private final LinkedList<SwitchToken> splitTokens = new LinkedList<>();\n\n public LongOrCompactTokenizer(final PeekIterator<String> stringIterator) {\n this.stringIterator = stringIterator;\n }\n\n public void setArgumentTerminator(String argumentTerminator) {\n this.argumentTerminator = argumentTerminator;\n }\n\n public boolean hasNext() {\n return stringIterator.hasNext();\n }\n\n // this is a mess - need to be cleaned up\n public Token peek() {\n if (!splitTokens.isEmpty()) {\n return splitTokens.peek();\n }\n final var value = stringIterator.peek();\n\n if (argumentEscapeEncountered) {\n return new ArgumentToken(value);\n }\n\n if (Objects.equals(value, argumentTerminator)) {\n return new ArgumentToken(value);\n }\n if (argumentTerminator != null) {\n return new ArgumentToken(value);\n }\n if (isArgumentEscape(value)) {\n argumentEscapeEncountered = true;\n return peek();\n }\n if (isSwitch(value)) {\n if (isShortSwitchList(value)) {\n var tokens = splitSwitchTokens(value);\n return tokens.get(0);\n } else {\n return new SwitchToken(value.substring(2), value);\n }\n } else {\n return new ArgumentToken(value);\n }\n }\n\n // this is a mess - needs to be cleaned up\n public Token next() {\n if (!splitTokens.isEmpty()) {\n return splitTokens.remove();\n }\n var value = stringIterator.next();\n\n if (argumentEscapeEncountered) {\n return new ArgumentToken(value);\n }\n\n if (Objects.equals(value, argumentTerminator)) {\n argumentTerminator = null;\n return new ArgumentToken(value);\n }\n if (argumentTerminator != null) {\n return new ArgumentToken(value);\n }\n if (isArgumentEscape(value)) {\n argumentEscapeEncountered = true;\n return next();\n }\n if (isSwitch(value)) {\n if (isShortSwitchList(value)) {\n splitTokens.addAll(splitSwitchTokens(value));\n return splitTokens.remove();\n } else {\n return new SwitchToken(value.substring(2), value);\n }\n } else {\n return new ArgumentToken(value);\n }\n }\n\n public void remove() {\n stringIterator.remove();\n }\n\n private static boolean isSwitch(final String argument) {\n return SWITCH_PATTERN.matcher(argument).matches();\n }\n\n private boolean isArgumentEscape(final String value) {\n return (\"--\".equals(value) && !argumentEscapeEncountered);\n }\n\n private boolean isLongSwitch(final String value) {\n return LONG_STYLE_SWITCH_PATTERN.matcher(value).matches();\n }\n\n private boolean isShortSwitchList(final String value) {\n return SHORT_STYLE_SWITCH_PATTERN.matcher(value).matches();\n }\n\n private List<SwitchToken> splitSwitchTokens(final String value) {\n final var tokens = new ArrayList<SwitchToken>();\n for (var i = 1; i < value.length(); i++) {\n tokens.add(new SwitchToken(String.valueOf(value.charAt(i)), value));\n }\n return tokens;\n }\n\n}",
"public class OptionSet {\n private final List<OptionSpecification> options;\n private final OptionSetLevel optionSetLevel;\n private final Object spec;\n\n public OptionSet(Object spec, OptionSetLevel optionSetLevel) {\n options = OptionSpecificationFactory.getOptionSpecifications(spec, spec.getClass());\n this.optionSetLevel = optionSetLevel;\n this.spec = spec;\n }\n\n public OptionSpecification getOptionSpecification(SwitchToken _switch) {\n for (final var optionSpecification : options) {\n if (optionSpecification.getSwitch().matches(_switch.getValue())) {\n return optionSpecification;\n }\n }\n return null;\n }\n\n public OptionSpecification getLooseArgsOptionSpecification() {\n for (final var optionSpecification : options) {\n if (optionSpecification.isLooseArgumentsSpecification()) {\n return optionSpecification;\n }\n }\n return null;\n }\n\n public void consumeOptions(Tokenizer args)\n throws IllegalAccessException, InvocationTargetException, InstantiationException {\n while (args.hasNext()) {\n if (args.peek() instanceof SwitchToken) {\n var optionSpecification = getOptionSpecification((SwitchToken) args.peek());\n if (optionSpecification == null) {\n switch (optionSetLevel) {\n case MAIN_OPTIONS:\n throw new UnrecognizedSwitchException(spec.getClass(), args.peek().getValue());\n case SUB_GROUP:\n validateAndConsolidate();\n return;\n }\n } else {\n args.next();\n optionSpecification.activateAndConsumeArguments(args);\n }\n } else {\n var looseArgsOptionSpecification = getLooseArgsOptionSpecification();\n if (looseArgsOptionSpecification != null) {\n looseArgsOptionSpecification.activateAndConsumeArguments(args);\n } else {\n switch (optionSetLevel) {\n case MAIN_OPTIONS:\n throw new InvalidCommandLineException(\"Invalid argument: \" + args.peek());\n case SUB_GROUP:\n validateAndConsolidate();\n return;\n }\n }\n }\n }\n flush();\n }\n\n private void flush()\n throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {\n for (final var option : options) {\n option.flush();\n }\n }\n\n public void validateAndConsolidate() {\n }\n}",
"public class SimpleTokenizer implements Tokenizer {\n\n private final PeekIterator<String> stringIterator;\n private boolean argumentEscapeEncountered;\n private String argumentTerminator;\n\n public SimpleTokenizer(PeekIterator<String> stringIterator) {\n this.stringIterator = stringIterator;\n }\n\n public void setArgumentTerminator(String argumentTerminator) {\n this.argumentTerminator = argumentTerminator;\n }\n\n public boolean hasNext() {\n return stringIterator.hasNext();\n }\n\n public Token peek() {\n final var value = stringIterator.peek();\n return makeToken(value);\n }\n\n public Token next() {\n final var value = stringIterator.next();\n return makeToken(value);\n }\n\n private Token makeToken(String value) {\n if (Objects.equals(value, argumentTerminator)) {\n argumentTerminator = null;\n return new ArgumentToken(value);\n }\n if (argumentTerminator != null) {\n return new ArgumentToken(value);\n }\n if (isArgumentEscape(value)) {\n argumentEscapeEncountered = true;\n return next();\n }\n if (!argumentEscapeEncountered && isSwitch(value)) {\n return new SwitchToken(value.substring(1), value);\n } else {\n return new ArgumentToken(value);\n }\n }\n\n public void remove() {\n stringIterator.remove();\n }\n\n\n private static boolean isSwitch(String argument) {\n return argument.matches(\"-.*\");\n }\n\n private boolean isArgumentEscape(String value) {\n return (\"--\".equals(value) && !argumentEscapeEncountered);\n }\n\n}",
"public interface Tokenizer extends Iterator<Token> {\n\n void setArgumentTerminator(String argumentTerminator);\n\n boolean hasNext();\n\n Token peek();\n\n Token next();\n\n void remove();\n}",
"public class ArrayIterator<T> implements Iterator<T> {\n\n private final T[] array;\n private int index = 0;\n\n public ArrayIterator(T[] array) {\n this.array = array;\n }\n\n public boolean hasNext() {\n return array.length > index;\n }\n\n public T next() {\n if (array.length > index) {\n return array[index++];\n } else {\n throw new NoSuchElementException();\n }\n }\n\n public T peek() {\n if (array.length > index) {\n return array[index];\n } else {\n throw new NoSuchElementException();\n }\n }\n\n public void remove() {\n throw new UnsupportedOperationException();\n }\n}",
"public class PeekIterator<T> implements Iterator<T> {\n\n private T nextValue;\n private final Iterator<T> iterator;\n\n public PeekIterator(Iterator<T> iterator) {\n this.iterator = iterator;\n }\n\n public boolean hasNext() {\n return nextValue != null || iterator.hasNext();\n }\n\n public T next() {\n if (nextValue != null) {\n var value = nextValue;\n nextValue = null;\n return value;\n } else {\n return iterator.next();\n }\n }\n\n public T peek() {\n if (nextValue == null) {\n nextValue = iterator.next();\n }\n return nextValue;\n }\n\n public void remove() {\n throw new UnsupportedOperationException();\n }\n\n}"
] | import com.github.jankroken.commandline.domain.CommandLineException;
import com.github.jankroken.commandline.domain.internal.LongOrCompactTokenizer;
import com.github.jankroken.commandline.domain.internal.OptionSet;
import com.github.jankroken.commandline.domain.internal.SimpleTokenizer;
import com.github.jankroken.commandline.domain.internal.Tokenizer;
import com.github.jankroken.commandline.util.ArrayIterator;
import com.github.jankroken.commandline.util.PeekIterator;
import java.lang.reflect.InvocationTargetException;
import static com.github.jankroken.commandline.OptionStyle.SIMPLE;
import static com.github.jankroken.commandline.domain.internal.OptionSetLevel.MAIN_OPTIONS; | package com.github.jankroken.commandline;
public class CommandLineParser {
/**
* A command line parser. It takes two arguments, a class and an argument list,
* and returns an instance of the class, populated from the argument list based
* on the annotations in the class. The class must have a no argument constructor.
*
* @param <T> The type of the provided class
* @param optionClass A class that contains annotated setters that options/arguments will be assigned to
* @param args The provided argument list, typically the argument from the static main method
* @return An instance of the provided class, populated with the options and arguments of the argument list
* @throws IllegalAccessException May be thrown when invoking the setters in the specified class
* @throws InstantiationException May be thrown when creating an instance of the specified class
* @throws InvocationTargetException May be thrown when invoking the setters in the specified class
* @throws com.github.jankroken.commandline.domain.InternalErrorException This indicates an internal error in the parser, and will not normally be thrown
* @throws com.github.jankroken.commandline.domain.InvalidCommandLineException This indicates that the command line specified does not match the annotations in the provided class
* @throws com.github.jankroken.commandline.domain.InvalidOptionConfigurationException This indicates that the annotations of setters in the provided class are not valid
* @throws com.github.jankroken.commandline.domain.UnrecognizedSwitchException This indicates that the argument list contains a switch which is not specified by the class annotations
*/
public static <T> T parse(Class<T> optionClass, String[] args, OptionStyle style)
throws IllegalAccessException, InstantiationException, InvocationTargetException {
T spec;
try {
spec = optionClass.getConstructor().newInstance();
} catch (NoSuchMethodException noSuchMethodException) {
throw new RuntimeException(noSuchMethodException);
}
var optionSet = new OptionSet(spec, MAIN_OPTIONS);
Tokenizer tokenizer;
if (style == SIMPLE) {
tokenizer = new SimpleTokenizer(new PeekIterator<>(new ArrayIterator<>(args)));
} else {
tokenizer = new LongOrCompactTokenizer(new PeekIterator<>(new ArrayIterator<>(args)));
}
optionSet.consumeOptions(tokenizer);
return spec;
}
public static <T> ParseResult<T> tryParse(Class<T> optionClass, String[] args, OptionStyle style) {
try {
return new ParseResult(parse(optionClass, args, style)); | } catch(CommandLineException | IllegalAccessException | InstantiationException | InvocationTargetException e) { | 0 |
jramoyo/quickfix-messenger | src/main/java/com/jramoyo/qfixmessenger/QFixMessenger.java | [
"public interface FixDictionaryParser\r\n{\r\n\t/**\r\n\t * Parses a QuickFIX dictionary XML file\r\n\t * \r\n\t * @param fileName\r\n\t * the name of the dictionary file\r\n\t * @return a FixDictionary representation of the dictionary\r\n\t * @throws FixParsingException\r\n\t */\r\n\t@Deprecated\r\n\tFixDictionary parse(String fileName) throws FixParsingException;\r\n\r\n\t/**\r\n\t * Parses a QuickFIX dictionary XML file\r\n\t * \r\n\t * @param inputStream\r\n\t * the dictionary file as <code>InputStream</code>\r\n\t * @return a FixDictionary representation of the dictionary\r\n\t * @throws FixParsingException\r\n\t */\r\n\tFixDictionary parse(InputStream inputStream) throws FixParsingException;\r\n}\r",
"public class QFixMessengerConfig\r\n{\r\n\tprivate static final String IS_INITIATOR_PROP = \"messenger.isInitiator\";\r\n\tprivate static final String PARSER_THREADS_PROP = \"messenger.parser.threads\";\r\n\tprivate static final String LICENSE_PROP = \"messenger.license\";\r\n\tprivate static final String ICONS_PROP = \"messenger.icons\";\r\n\tprivate static final String HOME_URL_PROP = \"messenger.home.url\";\r\n\tprivate static final String HELP_URL_PROP = \"messenger.help.url\";\r\n\tprivate static final String FIXWIKI_URL_PROP = \"messenger.fixwiki.url\";\r\n\r\n\tprivate static final String DICT_FIX40_PROP = \"messenger.dict.fix40\";\r\n\tprivate static final String DICT_FIX41_PROP = \"messenger.dict.fix41\";\r\n\tprivate static final String DICT_FIX42_PROP = \"messenger.dict.fix42\";\r\n\tprivate static final String DICT_FIX43_PROP = \"messenger.dict.fix43\";\r\n\tprivate static final String DICT_FIX44_PROP = \"messenger.dict.fix44\";\r\n\tprivate static final String DICT_FIX50_PROP = \"messenger.dict.fix50\";\r\n\tprivate static final String DICT_FIXT11_PROP = \"messenger.dict.fixt11\";\r\n\r\n\tprivate static final String LOG_PATH = \"logFilePath\";\r\n\r\n\tprivate final Properties properties;\r\n\r\n\tpublic QFixMessengerConfig(String configFileName) throws IOException\r\n\t{\r\n\t\tproperties = new Properties();\r\n\t\tproperties.load(new FileInputStream(configFileName));\r\n\t}\r\n\r\n\tpublic String getFix40DictionaryLocation()\r\n\t{\r\n\t\treturn properties.getProperty(DICT_FIX40_PROP, \"/FIX40.xml\");\r\n\t}\r\n\r\n\tpublic String getFix41DictionaryLocation()\r\n\t{\r\n\t\treturn properties.getProperty(DICT_FIX41_PROP, \"/FIX41.xml\");\r\n\t}\r\n\r\n\tpublic String getFix42DictionaryLocation()\r\n\t{\r\n\t\treturn properties.getProperty(DICT_FIX42_PROP, \"/FIX42.xml\");\r\n\t}\r\n\r\n\tpublic String getFix43DictionaryLocation()\r\n\t{\r\n\t\treturn properties.getProperty(DICT_FIX43_PROP, \"/FIX43.xml\");\r\n\t}\r\n\r\n\tpublic String getFix44DictionaryLocation()\r\n\t{\r\n\t\treturn properties.getProperty(DICT_FIX44_PROP, \"/FIX44.xml\");\r\n\t}\r\n\r\n\tpublic String getFix50DictionaryLocation()\r\n\t{\r\n\t\treturn properties.getProperty(DICT_FIX50_PROP, \"/FIX50.xml\");\r\n\t}\r\n\r\n\tpublic String getFixDictionaryLocation(String beginString)\r\n\t{\r\n\t\tif (beginString.equals(QFixMessengerConstants.BEGIN_STRING_FIX40))\r\n\t\t{\r\n\t\t\treturn getFix40DictionaryLocation();\r\n\t\t}\r\n\r\n\t\telse if (beginString.equals(QFixMessengerConstants.BEGIN_STRING_FIX41))\r\n\t\t{\r\n\t\t\treturn getFix41DictionaryLocation();\r\n\t\t}\r\n\r\n\t\telse if (beginString.equals(QFixMessengerConstants.BEGIN_STRING_FIX42))\r\n\t\t{\r\n\t\t\treturn getFix42DictionaryLocation();\r\n\t\t}\r\n\r\n\t\telse if (beginString.equals(QFixMessengerConstants.BEGIN_STRING_FIX43))\r\n\t\t{\r\n\t\t\treturn getFix43DictionaryLocation();\r\n\t\t}\r\n\r\n\t\telse if (beginString.equals(QFixMessengerConstants.BEGIN_STRING_FIX44))\r\n\t\t{\r\n\t\t\treturn getFix44DictionaryLocation();\r\n\t\t}\r\n\r\n\t\telse if (beginString.equals(QFixMessengerConstants.BEGIN_STRING_FIX50))\r\n\t\t{\r\n\t\t\treturn getFix50DictionaryLocation();\r\n\t\t}\r\n\r\n\t\telse if (beginString.equals(QFixMessengerConstants.BEGIN_STRING_FIXT11))\r\n\t\t{\r\n\t\t\treturn getFixT11DictionaryLocation();\r\n\t\t}\r\n\r\n\t\treturn \"\";\r\n\t}\r\n\r\n\tpublic String getFixT11DictionaryLocation()\r\n\t{\r\n\t\treturn properties.getProperty(DICT_FIXT11_PROP, \"/FIXT11.xml\");\r\n\t}\r\n\r\n\tpublic boolean isInitiator()\r\n\t{\r\n\t\treturn Boolean.valueOf(\r\n\t\t\t\tproperties.getProperty(IS_INITIATOR_PROP, \"true\"))\r\n\t\t\t\t.booleanValue();\r\n\t}\r\n\r\n\tpublic String getIconsLocation()\r\n\t{\r\n\t\treturn properties.getProperty(ICONS_PROP, \"/icons/\");\r\n\t}\r\n\r\n\tpublic String getLicenseLocation()\r\n\t{\r\n\t\treturn properties.getProperty(LICENSE_PROP, \"/license.txt\");\r\n\t}\r\n\r\n\tpublic String getHomeUrl()\r\n\t{\r\n\t\treturn properties.getProperty(HOME_URL_PROP,\r\n\t\t\t\t\"https://github.com/jramoyo/quickfix-messenger\");\r\n\t}\r\n\r\n\tpublic String getHelpUrl()\r\n\t{\r\n\t\treturn properties\r\n\t\t\t\t.getProperty(HELP_URL_PROP,\r\n\t\t\t\t\t\t\"https://github.com/jramoyo/quickfix-messenger/wiki/User's-Guide\");\r\n\t}\r\n\r\n\tpublic String getFixWikiUrl()\r\n\t{\r\n\t\treturn properties.getProperty(FIXWIKI_URL_PROP,\r\n\t\t\t\t\"http://fixwiki.org/fixwiki/\");\r\n\t}\r\n\r\n\tpublic int getNoOfParserThreads()\r\n\t{\r\n\t\treturn Integer.parseInt(properties.getProperty(PARSER_THREADS_PROP,\r\n\t\t\t\t\"20\"));\r\n\t}\r\n\r\n\tpublic String getLogFilePath()\r\n\t{\r\n\t\treturn properties.getProperty(LOG_PATH);\r\n\t}\r\n\r\n}\r",
"public class ComponentHelper\r\n{\r\n\tprivate final List<StringField> fields;\r\n\tprivate final List<quickfix.Group> groups;\r\n\r\n\tpublic ComponentHelper(List<StringField> fields, List<quickfix.Group> groups)\r\n\t{\r\n\t\tthis.fields = fields;\r\n\t\tthis.groups = groups;\r\n\t}\r\n\r\n\tpublic List<StringField> getFields()\r\n\t{\r\n\t\treturn Collections.unmodifiableList(fields);\r\n\t}\r\n\r\n\tpublic List<quickfix.Group> getGroups()\r\n\t{\r\n\t\treturn Collections.unmodifiableList(groups);\r\n\t}\r\n}\r",
"public class QFixMessengerApplication implements Application\r\n{\r\n\tprivate static final Logger logger = LoggerFactory\r\n\t\t\t.getLogger(QFixMessengerApplication.class);\r\n\r\n\tprivate final SessionSettings sessionSettings;\r\n\r\n\tprivate final List<QFixMessageListener> messageListeners = new ArrayList<QFixMessageListener>();\r\n\r\n\tpublic QFixMessengerApplication(SessionSettings sessionSettings)\r\n\t{\r\n\t\tthis.sessionSettings = sessionSettings;\r\n\t}\r\n\r\n\tpublic void addMessageListener(QFixMessageListener messageListener)\r\n\t{\r\n\t\tmessageListeners.add(messageListener);\r\n\t}\r\n\r\n\tpublic void removeMessageListener(QFixMessageListener messageListener)\r\n\t{\r\n\t\tmessageListeners.remove(messageListener);\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void fromAdmin(Message message, SessionID sessionId)\r\n\t\t\tthrows FieldNotFound, IncorrectDataFormat, IncorrectTagValue,\r\n\t\t\tRejectLogon\r\n\t{\r\n\t\t// Listen for Session Reject messages\r\n\t\tMsgType msgType = (MsgType) message.getHeader().getField(new MsgType());\r\n\t\tif (msgType.getValue().equals(\"3\"))\r\n\t\t{\r\n\t\t\tfor (QFixMessageListener messageListener : messageListeners)\r\n\t\t\t{\r\n\t\t\t\tmessageListener.onMessage(QFixMessageListener.RECV, message,\r\n\t\t\t\t\t\tsessionId);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void fromApp(Message message, SessionID sessionId)\r\n\t\t\tthrows FieldNotFound, IncorrectDataFormat, IncorrectTagValue,\r\n\t\t\tUnsupportedMessageType\r\n\t{\r\n\t\tfor (QFixMessageListener messageListener : messageListeners)\r\n\t\t{\r\n\t\t\tmessageListener.onMessage(QFixMessageListener.RECV, message,\r\n\t\t\t\t\tsessionId);\r\n\t\t}\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void onCreate(SessionID sessionId)\r\n\t{\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void onLogon(SessionID sessionId)\r\n\t{\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void onLogout(SessionID sessionId)\r\n\t{\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void toAdmin(Message message, SessionID sessionId)\r\n\t{\r\n\t\t// Customize logon\r\n\t\tif (isMessageOfType(message, MsgType.LOGON))\r\n\t\t{\r\n\t\t\ttry\r\n\t\t\t{\r\n\t\t\t\ttry\r\n\t\t\t\t{\r\n\t\t\t\t\tString usernameSetting = sessionSettings.getString(\r\n\t\t\t\t\t\t\tsessionId, \"Username\");\r\n\t\t\t\t\tif (!StringUtil.isNullOrEmpty(usernameSetting))\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tmessage.setField(new Username(usernameSetting));\r\n\t\t\t\t\t}\r\n\t\t\t\t} catch (ConfigError ex)\r\n\t\t\t\t{\r\n\t\t\t\t\tlogger.debug(ex.getMessage());\r\n\t\t\t\t}\r\n\r\n\t\t\t\ttry\r\n\t\t\t\t{\r\n\t\t\t\t\tString passwordSetting = sessionSettings.getString(\r\n\t\t\t\t\t\t\tsessionId, \"Password\");\r\n\t\t\t\t\tif (!StringUtil.isNullOrEmpty(passwordSetting))\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tmessage.setField(new Password(passwordSetting));\r\n\t\t\t\t\t}\r\n\t\t\t\t} catch (ConfigError ex)\r\n\t\t\t\t{\r\n\t\t\t\t\tlogger.debug(ex.getMessage());\r\n\t\t\t\t}\r\n\r\n\t\t\t\ttry\r\n\t\t\t\t{\r\n\t\t\t\t\tString rawDataSetting = sessionSettings.getString(\r\n\t\t\t\t\t\t\tsessionId, \"RawData\");\r\n\t\t\t\t\tif (!StringUtil.isNullOrEmpty(rawDataSetting))\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tmessage.setField(new RawData(rawDataSetting));\r\n\t\t\t\t\t}\r\n\t\t\t\t} catch (ConfigError ex)\r\n\t\t\t\t{\r\n\t\t\t\t\tlogger.debug(ex.getMessage());\r\n\t\t\t\t}\r\n\r\n\t\t\t\ttry\r\n\t\t\t\t{\r\n\t\t\t\t\tlong rawDataLengthSetting = sessionSettings.getLong(\r\n\t\t\t\t\t\t\tsessionId, \"RawDataLength\");\r\n\t\t\t\t\tif (rawDataLengthSetting > 0)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tmessage.setField(new RawDataLength(\r\n\t\t\t\t\t\t\t\t(int) rawDataLengthSetting));\r\n\t\t\t\t\t}\r\n\t\t\t\t} catch (ConfigError ex)\r\n\t\t\t\t{\r\n\t\t\t\t\tlogger.debug(ex.getMessage());\r\n\t\t\t\t}\r\n\r\n\t\t\t\ttry\r\n\t\t\t\t{\r\n\t\t\t\t\tString testMessageIndicatorSetting = sessionSettings\r\n\t\t\t\t\t\t\t.getString(sessionId, \"TestMessageIndicator\");\r\n\t\t\t\t\tif (!StringUtil.isNullOrEmpty(testMessageIndicatorSetting))\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tmessage.setField(new TestMessageIndicator(Boolean\r\n\t\t\t\t\t\t\t\t.valueOf(testMessageIndicatorSetting)));\r\n\t\t\t\t\t}\r\n\t\t\t\t} catch (ConfigError ex)\r\n\t\t\t\t{\r\n\t\t\t\t\tlogger.debug(ex.getMessage());\r\n\t\t\t\t}\r\n\t\t\t} catch (FieldConvertError ex)\r\n\t\t\t{\r\n\t\t\t\tlogger.error(\"An error occured while \"\r\n\t\t\t\t\t\t+ \"fetching custom logon settings!\", ex);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t@Override\r\n\tpublic void toApp(Message message, SessionID sessionId) throws DoNotSend\r\n\t{\r\n\t\tfor (QFixMessageListener messageListener : messageListeners)\r\n\t\t{\r\n\t\t\tmessageListener.onMessage(QFixMessageListener.SENT, message,\r\n\t\t\t\t\tsessionId);\r\n\t\t}\r\n\t}\r\n\r\n\tprivate boolean isMessageOfType(Message message, String type)\r\n\t{\r\n\t\ttry\r\n\t\t{\r\n\t\t\treturn type.equals(message.getHeader().getField(new MsgType())\r\n\t\t\t\t\t.getValue());\r\n\t\t} catch (FieldNotFound ex)\r\n\t\t{\r\n\t\t\tlogger.error(\"Unable to find MsgType from Message!\", ex);\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n}\r",
"public class QFixDictionaryParser implements FixDictionaryParser\r\n{\r\n\tprivate static final Logger logger = LoggerFactory\r\n\t\t\t.getLogger(QFixDictionaryParser.class);\r\n\r\n\tprivate final ExecutorService threadPool;\r\n\r\n\t/**\r\n\t * Creates a new QFixDictionaryParser\r\n\t * \r\n\t * @param noOfThreads\r\n\t * the number of parser threads to use\r\n\t */\r\n\tpublic QFixDictionaryParser(int noOfThreads)\r\n\t{\r\n\t\tthreadPool = Executors.newFixedThreadPool(noOfThreads,\r\n\t\t\t\tnew ParserThreadFactory());\r\n\t}\r\n\r\n\t@Override\r\n\t@Deprecated\r\n\tpublic FixDictionary parse(String fileName) throws FixParsingException\r\n\t{\r\n\t\tFixDictionary dictionary;\r\n\t\ttry\r\n\t\t{\r\n\t\t\tFileInputStream fileInputStream = new FileInputStream(fileName);\r\n\t\t\tdictionary = parse(fileInputStream);\r\n\r\n\t\t} catch (FileNotFoundException ex)\r\n\t\t{\r\n\t\t\tthrow new FixParsingException(\"File \" + fileName + \" not foud!\", ex);\r\n\t\t}\r\n\r\n\t\treturn dictionary;\r\n\t}\r\n\r\n\t@Override\r\n\tpublic FixDictionary parse(InputStream inputStream)\r\n\t\t\tthrows FixParsingException\r\n\t{\r\n\t\tlong startTime = System.currentTimeMillis();\r\n\r\n\t\tFixDictionary dictionary;\r\n\t\ttry\r\n\t\t{\r\n\t\t\tSAXBuilder saxBuilder = new SAXBuilder();\r\n\t\t\tDocument document = saxBuilder.build(inputStream);\r\n\r\n\t\t\tElement root = document.getRootElement();\r\n\r\n\t\t\t// Parse the dictionary (version) attributes\r\n\t\t\tString type = root.getAttributeValue(\"type\");\r\n\t\t\tString majorVersion = root.getAttributeValue(\"major\");\r\n\t\t\tString minorVersion = root.getAttributeValue(\"minor\");\r\n\r\n\t\t\tdictionary = new FixDictionary(type, majorVersion, minorVersion);\r\n\r\n\t\t\t// Parse the field definitions\r\n\t\t\tlogger.debug(\"Parsing field definitions...\");\r\n\r\n\t\t\tElement fieldsElement = root.getChild(\"fields\");\r\n\t\t\t@SuppressWarnings(\"unchecked\")\r\n\t\t\tList<Element> fieldElements = fieldsElement.getChildren(\"field\");\r\n\t\t\tparseFields(dictionary, fieldElements);\r\n\r\n\t\t\t// Parse the component definitions\r\n\t\t\tlogger.debug(\"Parsing component definitions...\");\r\n\r\n\t\t\tElement componentsElement = root.getChild(\"components\");\r\n\t\t\tif (componentsElement != null)\r\n\t\t\t{\r\n\t\t\t\t@SuppressWarnings(\"unchecked\")\r\n\t\t\t\tList<Element> componentElements = componentsElement\r\n\t\t\t\t\t\t.getChildren(\"component\");\r\n\t\t\t\tparseComponents(dictionary, componentElements);\r\n\t\t\t}\r\n\r\n\t\t\t// Parse the message definitions\r\n\t\t\tlogger.debug(\"Parsing message definitions...\");\r\n\r\n\t\t\tElement messagesElement = root.getChild(\"messages\");\r\n\t\t\t@SuppressWarnings(\"unchecked\")\r\n\t\t\tList<Element> messageElements = messagesElement\r\n\t\t\t\t\t.getChildren(\"message\");\r\n\t\t\tparseMessages(dictionary, messageElements);\r\n\r\n\t\t\t// Parse the header definition\r\n\t\t\tlogger.debug(\"Parsing header definition...\");\r\n\r\n\t\t\tElement headerElement = root.getChild(\"header\");\r\n\t\t\tparseHeader(dictionary, headerElement);\r\n\r\n\t\t\t// Parse the trailer definition\r\n\t\t\tlogger.debug(\"Parsing trailer definition...\");\r\n\r\n\t\t\tElement trailerElement = root.getChild(\"trailer\");\r\n\t\t\tparseTrailer(dictionary, trailerElement);\r\n\t\t} catch (IOException ex)\r\n\t\t{\r\n\t\t\tthrow new FixParsingException(\"An IOException occured!\", ex);\r\n\t\t} catch (JDOMException ex)\r\n\t\t{\r\n\t\t\tthrow new FixParsingException(\"A JDOMException occured!\", ex);\r\n\t\t}\r\n\r\n\t\tif (logger.isDebugEnabled())\r\n\t\t{\r\n\t\t\tlong elapsedTime = System.currentTimeMillis() - startTime;\r\n\t\t\tlogger.debug(\"Time taken to parse dictionary \" + dictionary + \": \"\r\n\t\t\t\t\t+ elapsedTime + \" ms.\");\r\n\t\t}\r\n\r\n\t\treturn dictionary;\r\n\t}\r\n\r\n\tprivate Component parseComponent(FixDictionary dictionary,\r\n\t\t\tElement componentElement) throws FixParsingException\r\n\t{\r\n\t\tString name = componentElement.getAttributeValue(\"name\");\r\n\t\tlogger.trace(\"Parsing component \" + name);\r\n\r\n\t\tElement firstTagElement = componentElement.getChild(\"field\");\r\n\t\tString firstTagName = null;\r\n\t\tif (firstTagElement != null)\r\n\t\t{\r\n\t\t\tfirstTagName = firstTagElement.getAttributeValue(\"name\");\r\n\t\t}\r\n\t\tField firstTag = null;\r\n\t\tif (!StringUtil.isNullOrEmpty(firstTagName))\r\n\t\t{\r\n\t\t\tfirstTag = dictionary.getFields().get(firstTagName);\r\n\t\t}\r\n\r\n\t\tMap<MemberOrder, Boolean> members = parseMembers(dictionary,\r\n\t\t\t\tcomponentElement);\r\n\r\n\t\treturn new Component(name, members, firstTag);\r\n\t}\r\n\r\n\t/*\r\n\t * Due to nested components, parsing cannot be done in parallel\r\n\t */\r\n\tprivate void parseComponents(final FixDictionary dictionary,\r\n\t\t\tList<Element> componentElements) throws FixParsingException\r\n\t{\r\n\t\tlong startTime = System.nanoTime();\r\n\r\n\t\tfor (Element componentElement : componentElements)\r\n\t\t{\r\n\t\t\tString componentName = componentElement.getAttributeValue(\"name\");\r\n\t\t\tif (dictionary.getComponents().get(componentName) == null)\r\n\t\t\t{\r\n\t\t\t\tComponent component = parseComponent(dictionary,\r\n\t\t\t\t\t\tcomponentElement);\r\n\t\t\t\tdictionary.getComponents().put(component.getName(), component);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (logger.isDebugEnabled())\r\n\t\t{\r\n\t\t\tlong elapsedTime = System.nanoTime() - startTime;\r\n\t\t\tlogger.debug(\"Time taken to parse components: \" + elapsedTime\r\n\t\t\t\t\t+ \" ns.\");\r\n\t\t}\r\n\t}\r\n\r\n\tprivate Field parseField(Element fieldElement)\r\n\t{\r\n\t\tint number = Integer.parseInt(fieldElement.getAttributeValue(\"number\"));\r\n\t\tString name = fieldElement.getAttributeValue(\"name\");\r\n\r\n\t\tlogger.trace(\"Parsing field \" + name);\r\n\r\n\t\tFieldType type;\r\n\t\ttry\r\n\t\t{\r\n\t\t\t// TODO Map all fields\r\n\t\t\ttype = FieldType.valueOf(fieldElement.getAttributeValue(\"type\"));\r\n\t\t} catch (IllegalArgumentException ex)\r\n\t\t{\r\n\t\t\t// Default to String\r\n\t\t\ttype = FieldType.STRING;\r\n\t\t}\r\n\r\n\t\tList<FieldValue> values = null;\r\n\t\t@SuppressWarnings(\"unchecked\")\r\n\t\tList<Element> valueElements = fieldElement.getChildren(\"value\");\r\n\t\tif (valueElements != null && !valueElements.isEmpty())\r\n\t\t{\r\n\t\t\tvalues = new ArrayList<FieldValue>();\r\n\t\t\tfor (Element valueElement : valueElements)\r\n\t\t\t{\r\n\t\t\t\tString enumValue = valueElement.getAttributeValue(\"enum\");\r\n\t\t\t\tString description = valueElement\r\n\t\t\t\t\t\t.getAttributeValue(\"description\");\r\n\r\n\t\t\t\tFieldValue value = new FieldValue(enumValue, description);\r\n\t\t\t\tvalues.add(value);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn new Field(number, name, type, values);\r\n\t}\r\n\r\n\t/*\r\n\t * Because field definitions are independent of each other, they can be\r\n\t * parsed in parallel.\r\n\t */\r\n\tprivate void parseFields(final FixDictionary dictionary,\r\n\t\t\tList<Element> fieldElements)\r\n\t{\r\n\t\tlong startTime = System.nanoTime();\r\n\r\n\t\tfinal CountDownLatch latch = new CountDownLatch(fieldElements.size());\r\n\t\tfor (final Element fieldElement : fieldElements)\r\n\t\t{\r\n\t\t\tthreadPool.execute(new Runnable()\r\n\t\t\t{\r\n\t\t\t\t@Override\r\n\t\t\t\tpublic void run()\r\n\t\t\t\t{\r\n\t\t\t\t\tField field = parseField(fieldElement);\r\n\t\t\t\t\tdictionary.getFields().put(field.getName(), field);\r\n\t\t\t\t\tlatch.countDown();\r\n\t\t\t\t\tlogger.trace(\"Completed parsing \" + field\r\n\t\t\t\t\t\t\t+ \". Remaining field tasks: \" + latch.getCount());\r\n\t\t\t\t}\r\n\t\t\t});\r\n\t\t}\r\n\r\n\t\ttry\r\n\t\t{\r\n\t\t\tlogger.debug(\"Awaiting field parsing tasks to complete...\");\r\n\t\t\tlatch.await();\r\n\t\t} catch (InterruptedException ex)\r\n\t\t{\r\n\t\t\tThread.currentThread().interrupt();\r\n\t\t}\r\n\r\n\t\tif (logger.isDebugEnabled())\r\n\t\t{\r\n\t\t\tlong elapsedTime = System.nanoTime() - startTime;\r\n\t\t\tlogger.debug(\"Time taken to parse fields: \" + elapsedTime + \" ns.\");\r\n\t\t}\r\n\t}\r\n\r\n\tprivate Group parseGroup(FixDictionary dictionary, Element groupElement)\r\n\t\t\tthrows FixParsingException\r\n\t{\r\n\t\tString groupName = groupElement.getAttributeValue(\"name\");\r\n\r\n\t\tField field = dictionary.getFields().get(groupName);\r\n\t\tMap<MemberOrder, Boolean> members = parseMembers(dictionary,\r\n\t\t\t\tgroupElement);\r\n\r\n\t\tMember firstMember = null;\r\n\t\tElement firstChildElement = (Element) groupElement.getChildren().get(0);\r\n\t\tif (firstChildElement.getName().equals(\"field\"))\r\n\t\t{\r\n\t\t\tString firstFieldName = firstChildElement.getAttributeValue(\"name\");\r\n\t\t\tif (!StringUtil.isNullOrEmpty(firstFieldName))\r\n\t\t\t{\r\n\t\t\t\tfirstMember = dictionary.getFields().get(firstFieldName);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\telse if (firstChildElement.getName().equals(\"component\"))\r\n\t\t{\r\n\t\t\tString firstComponentName = firstChildElement\r\n\t\t\t\t\t.getAttributeValue(\"name\");\r\n\t\t\tif (!StringUtil.isNullOrEmpty(firstComponentName))\r\n\t\t\t{\r\n\t\t\t\tfirstMember = dictionary.getComponents()\r\n\t\t\t\t\t\t.get(firstComponentName);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn new Group(field, members, firstMember);\r\n\t}\r\n\r\n\tprivate void parseHeader(FixDictionary dictionary, Element headerElement)\r\n\t\t\tthrows FixParsingException\r\n\t{\r\n\t\tMap<MemberOrder, Boolean> members = parseMembers(dictionary,\r\n\t\t\t\theaderElement);\r\n\t\tdictionary.setHeader(new Header(members));\r\n\t}\r\n\r\n\tprivate SortedMap<MemberOrder, Boolean> parseMembers(\r\n\t\t\tFixDictionary dictionary, Element element)\r\n\t\t\tthrows FixParsingException\r\n\t{\r\n\t\tSortedMap<MemberOrder, Boolean> members = new TreeMap<MemberOrder, Boolean>();\r\n\r\n\t\t@SuppressWarnings(\"unchecked\")\r\n\t\tList<Element> memberElements = element.getChildren();\r\n\t\tfor (int i = 0; i < memberElements.size(); i++)\r\n\t\t{\r\n\t\t\tElement memberElement = memberElements.get(i);\r\n\t\t\tif (memberElement.getName().equals(\"field\"))\r\n\t\t\t{\r\n\t\t\t\tString fieldName = memberElement.getAttributeValue(\"name\");\r\n\t\t\t\tBoolean isRequired = convertStringToBoolean(memberElement\r\n\t\t\t\t\t\t.getAttributeValue(\"required\"));\r\n\r\n\t\t\t\tField field = dictionary.getFields().get(fieldName);\r\n\t\t\t\tif (field != null)\r\n\t\t\t\t{\r\n\t\t\t\t\tmembers.put(new MemberOrder(i, field), isRequired);\r\n\t\t\t\t} else\r\n\t\t\t\t{\r\n\t\t\t\t\tthrow new FixParsingException(fieldName\r\n\t\t\t\t\t\t\t+ \" is not defined!\");\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\telse if (memberElement.getName().equals(\"group\"))\r\n\t\t\t{\r\n\t\t\t\tBoolean isRequired = convertStringToBoolean(memberElement\r\n\t\t\t\t\t\t.getAttributeValue(\"required\"));\r\n\t\t\t\tmembers.put(\r\n\t\t\t\t\t\tnew MemberOrder(i,\r\n\t\t\t\t\t\t\t\tparseGroup(dictionary, memberElement)),\r\n\t\t\t\t\t\tisRequired);\r\n\t\t\t}\r\n\r\n\t\t\telse if (memberElement.getName().equals(\"component\"))\r\n\t\t\t{\r\n\t\t\t\tString componentName = memberElement.getAttributeValue(\"name\");\r\n\t\t\t\tBoolean isRequired = convertStringToBoolean(memberElement\r\n\t\t\t\t\t\t.getAttributeValue(\"required\"));\r\n\r\n\t\t\t\tComponent component = dictionary.getComponents().get(\r\n\t\t\t\t\t\tcomponentName);\r\n\t\t\t\tif (component == null)\r\n\t\t\t\t{\r\n\t\t\t\t\t// TODO Improve\r\n\t\t\t\t\tElement root = element.getDocument().getRootElement();\r\n\t\t\t\t\t@SuppressWarnings(\"unchecked\")\r\n\t\t\t\t\tList<Element> componentElements = root.getChild(\r\n\t\t\t\t\t\t\t\"components\").getChildren(\"component\");\r\n\t\t\t\t\tfor (Element componentElement : componentElements)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tString componentElementName = componentElement\r\n\t\t\t\t\t\t\t\t.getAttributeValue(\"name\");\r\n\t\t\t\t\t\tif (componentElementName.equals(componentName))\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tcomponent = parseComponent(dictionary,\r\n\t\t\t\t\t\t\t\t\tcomponentElement);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\tmembers.put(new MemberOrder(i, component), isRequired);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn members;\r\n\t}\r\n\r\n\tprivate Message parseMessage(FixDictionary dictionary,\r\n\t\t\tElement messageElement) throws FixParsingException\r\n\t{\r\n\t\tString name = messageElement.getAttributeValue(\"name\");\r\n\t\tlogger.trace(\"Parsing message \" + name);\r\n\r\n\t\tString msgType = messageElement.getAttributeValue(\"msgtype\");\r\n\t\tMessageCategory category = MessageCategory.valueOf(messageElement\r\n\t\t\t\t.getAttributeValue(\"msgcat\"));\r\n\t\tMap<MemberOrder, Boolean> members = parseMembers(dictionary,\r\n\t\t\t\tmessageElement);\r\n\r\n\t\treturn new Message(name, msgType, category, members);\r\n\t}\r\n\r\n\t/*\r\n\t * Because message definitions are independent of each other, they can be\r\n\t * parsed in parallel.\r\n\t */\r\n\tprivate void parseMessages(final FixDictionary dictionary,\r\n\t\t\tList<Element> messageElements) throws FixParsingException\r\n\t{\r\n\t\tlong startTime = System.nanoTime();\r\n\r\n\t\tfinal CountDownLatch latch = new CountDownLatch(messageElements.size());\r\n\t\tList<Future<Void>> results = new ArrayList<Future<Void>>();\r\n\t\tfor (final Element messageElement : messageElements)\r\n\t\t{\r\n\t\t\tFuture<Void> result = threadPool.submit(new Callable<Void>()\r\n\t\t\t{\r\n\t\t\t\t@Override\r\n\t\t\t\tpublic Void call() throws Exception\r\n\t\t\t\t{\r\n\t\t\t\t\tMessage message = parseMessage(dictionary, messageElement);\r\n\t\t\t\t\tdictionary.getMessages().put(message.getName(), message);\r\n\t\t\t\t\tlatch.countDown();\r\n\r\n\t\t\t\t\tlogger.trace(\"Completed parsing \" + message\r\n\t\t\t\t\t\t\t+ \". Remaining message tasks: \" + latch.getCount());\r\n\r\n\t\t\t\t\treturn null;\r\n\t\t\t\t}\r\n\t\t\t});\r\n\t\t\tresults.add(result);\r\n\t\t}\r\n\r\n\t\ttry\r\n\t\t{\r\n\t\t\tlogger.debug(\"Awaiting messages parsing tasks to complete...\");\r\n\r\n\t\t\tlatch.await();\r\n\t\t\tfor (Future<Void> result : results)\r\n\t\t\t{\r\n\t\t\t\ttry\r\n\t\t\t\t{\r\n\t\t\t\t\tresult.get();\r\n\t\t\t\t} catch (ExecutionException ex)\r\n\t\t\t\t{\r\n\t\t\t\t\tthrow new FixParsingException(\"Unable to parse messages!\",\r\n\t\t\t\t\t\t\tex);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t} catch (InterruptedException ex)\r\n\t\t{\r\n\t\t\tThread.currentThread().interrupt();\r\n\t\t}\r\n\r\n\t\tif (logger.isDebugEnabled())\r\n\t\t{\r\n\t\t\tlong elapsedTime = System.nanoTime() - startTime;\r\n\t\t\tlogger.debug(\"Time taken to parse messages: \" + elapsedTime\r\n\t\t\t\t\t+ \" ns.\");\r\n\t\t}\r\n\t}\r\n\r\n\tprivate void parseTrailer(FixDictionary dictionary, Element trailerElement)\r\n\t\t\tthrows FixParsingException\r\n\t{\r\n\t\tMap<MemberOrder, Boolean> members = parseMembers(dictionary,\r\n\t\t\t\ttrailerElement);\r\n\t\tdictionary.setTrailer(new Trailer(members));\r\n\t}\r\n\r\n\tprivate Boolean convertStringToBoolean(String string)\r\n\t{\r\n\t\tif (string == null)\r\n\t\t\treturn Boolean.FALSE;\r\n\r\n\t\tif (string.equalsIgnoreCase(\"Y\"))\r\n\t\t\treturn Boolean.TRUE;\r\n\t\telse\r\n\t\t\treturn Boolean.FALSE;\r\n\t}\r\n\r\n\tprivate static class ParserThreadFactory implements ThreadFactory\r\n\t{\r\n\t\t@Override\r\n\t\tpublic Thread newThread(Runnable r)\r\n\t\t{\r\n\t\t\treturn new Thread(r, \"parser\");\r\n\t\t}\r\n\t}\r\n\r\n}\r",
"public class QFixUtil\r\n{\r\n\t/**\r\n\t * Returns the preferred session name format from a QuickFIX SessionID\r\n\t * instance\r\n\t * \r\n\t * @param sessionId the QuickFIX SessionID instance\r\n\t * @return the preferred session name format from a QuickFIX SessionID\r\n\t * instance\r\n\t */\r\n\tpublic static String getSessionName(SessionID sessionId)\r\n\t{\r\n\t\treturn new StringBuilder(sessionId.getBeginString()).append(':')\r\n\t\t\t\t.append(sessionId.getSenderCompID()).append(\">\").append(\r\n\t\t\t\t\t\tsessionId.getTargetCompID()).toString();\r\n\t}\r\n}\r",
"public class QFixMessengerFrame extends JFrame\r\n{\r\n\tprivate static final long serialVersionUID = 7906369617506618477L;\r\n\r\n\tprivate static final Logger logger = LoggerFactory\r\n\t\t\t.getLogger(QFixMessengerFrame.class);\r\n\r\n\tprivate static final int FRAME_MIN_HEIGHT = 510;\r\n\r\n\tprivate static final int FRAME_MIN_WIDTH = 600;\r\n\r\n\tprivate static final int LEFT_PANEL_WIDTH = 170;\r\n\r\n\tprivate static final String VERSION = \"2.0\";\r\n\r\n\tprivate static final String EMPTY_PROJECT_NAME = \"None\";\r\n\r\n\t/**\r\n\t * Launches the frame\r\n\t */\r\n\tpublic static void launch(QFixMessenger messenger)\r\n\t{\r\n\t\tclass Launcher implements Runnable\r\n\t\t{\r\n\t\t\tprivate final QFixMessenger messenger;\r\n\r\n\t\t\tprivate Launcher(QFixMessenger messenger)\r\n\t\t\t{\r\n\t\t\t\tthis.messenger = messenger;\r\n\t\t\t}\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic void run()\r\n\t\t\t{\r\n\t\t\t\tQFixMessengerFrame frame = new QFixMessengerFrame(messenger);\r\n\t\t\t\tframe.initFrame();\r\n\t\t\t\tframe.initComponents();\r\n\t\t\t\tframe.positionFrame();\r\n\t\t\t\tframe.setVisible(true);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tSwingUtilities.invokeLater(new Launcher(messenger));\r\n\t}\r\n\r\n\tprivate final Message freeTextMessage = new Message(\"Free Text\",\r\n\t\t\t\"FIX Message\", null, new HashMap<MemberOrder, Boolean>());\r\n\r\n\tprivate final JPanel blankPanel = new JPanel();\r\n\r\n\tprivate final QFixMessenger messenger;\r\n\r\n\tprivate final FixDictionary fixTDictionary;\r\n\r\n\tprivate final MemberPanelCache memberPanelCache;\r\n\r\n\tprivate String frameTitle;\r\n\r\n\tprivate String projectTitle = EMPTY_PROJECT_NAME;\r\n\r\n\tprivate ProjectType activeXmlProject;\r\n\r\n\tprivate File activeProjectFile;\r\n\r\n\tprivate FixDictionary activeDictionary;\r\n\r\n\tprivate Message activeMessage;\r\n\r\n\tprivate boolean isRequiredOnly = true;\r\n\r\n\tprivate boolean isModifyHeader;\r\n\r\n\tprivate boolean isModifyTrailer;\r\n\r\n\tprivate boolean isFixTSession;\r\n\r\n\tprivate boolean isPreviewBeforeSend;\r\n\r\n\tprivate JMenuBar menuBar;\r\n\r\n\tprivate JMenu fileMenu;\r\n\r\n\tprivate JMenu sessionMenu;\r\n\r\n\tprivate JMenu helpMenu;\r\n\r\n\tprivate JMenu windowMenu;\r\n\r\n\tprivate JMenuItem closeProjectMenuItem;\r\n\r\n\tprivate JMenuItem saveProjectMenuItem;\r\n\r\n\tprivate JPanel leftPanel;\r\n\r\n\tprivate JScrollPane mainPanelScrollPane;\r\n\r\n\tprivate JScrollPane bottomPanelScrollPane;\r\n\r\n\tprivate JPanel rightPanel;\r\n\r\n\tprivate JList<Session> sessionsList;\r\n\r\n\tprivate JList<Message> messagesList;\r\n\r\n\tprivate DefaultListModel<Message> recentMessagesListModel;\r\n\r\n\tprivate JList<Message> recentMessagesList;\r\n\r\n\tprivate Map<String, DefaultListModel<Message>> recentMessagesMap;\r\n\r\n\tprivate JTabbedPane messagesTabPane;\r\n\r\n\tprivate JComboBox<String> appVersionsComboBox;\r\n\r\n\tprivate JCheckBox requiredCheckBox;\r\n\r\n\tprivate JCheckBox modifyHeaderCheckBox;\r\n\r\n\tprivate JCheckBox modifyTrailerCheckBox;\r\n\r\n\tprivate JCheckBox previewBeforeSendCheckBox;\r\n\r\n\tprivate JButton destroyButton;\r\n\r\n\tprivate JButton addButton;\r\n\r\n\tprivate JButton sendButton;\r\n\r\n\tprivate JTable messagesTable;\r\n\r\n\tprivate MessagePanel messagePanel;\r\n\r\n\tprivate FreeTextMessagePanel freeTextMessagePanel;\r\n\r\n\tprivate ProjectDialog projectDialog;\r\n\r\n\tprivate LogfileDialog logfileDialog;\r\n\r\n\tprivate QFixMessengerFrame(QFixMessenger messenger)\r\n\t{\r\n\t\tsuper();\r\n\t\tthis.messenger = messenger;\r\n\r\n\t\tmemberPanelCache = new MemberPanelCache();\r\n\r\n\t\tFixDictionaryParser parser = messenger.getParser();\r\n\t\tString fixTDictionaryFile = messenger.getConfig()\r\n\t\t\t\t.getFixT11DictionaryLocation();\r\n\r\n\t\tFixDictionary dictionary = null;\r\n\t\ttry\r\n\t\t{\r\n\t\t\tdictionary = parser.parse(getClass().getResourceAsStream(\r\n\t\t\t\t\tfixTDictionaryFile));\r\n\t\t} catch (FixParsingException ex)\r\n\t\t{\r\n\t\t\tlogger.error(\"Unable to parse FIXT 1.1 Dictionary!\", ex);\r\n\t\t\tSystem.exit(1);\r\n\t\t}\r\n\r\n\t\tfixTDictionary = dictionary;\r\n\t}\r\n\r\n\t/**\r\n\t * Disposes the frame and gracefully exits the application\r\n\t */\r\n\tpublic void close()\r\n\t{\r\n\t\tint choice = JOptionPane.showConfirmDialog(this,\r\n\t\t\t\t\"Exit QuickFIX Messenger?\", \"Quit\", JOptionPane.YES_NO_OPTION);\r\n\t\tif (choice == JOptionPane.YES_OPTION)\r\n\t\t{\r\n\t\t\tif (activeXmlProject != null)\r\n\t\t\t{\r\n\t\t\t\tchoice = JOptionPane.showConfirmDialog(this,\r\n\t\t\t\t\t\t\"Do you want to save \\\"\" + activeXmlProject.getName()\r\n\t\t\t\t\t\t\t\t+ \"\\\"?\", \"Save Current Project\",\r\n\t\t\t\t\t\tJOptionPane.YES_NO_CANCEL_OPTION);\r\n\t\t\t\tswitch (choice)\r\n\t\t\t\t{\r\n\t\t\t\tcase JOptionPane.NO_OPTION:\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase JOptionPane.YES_OPTION:\r\n\t\t\t\t\tmarshallActiveXmlProject();\r\n\t\t\t\t\tbreak;\r\n\t\t\t\tcase JOptionPane.CANCEL_OPTION:\r\n\t\t\t\t\treturn;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tdispose();\r\n\t\t\tmessenger.exit();\r\n\t\t}\r\n\t}\r\n\r\n\tpublic void displayMainPanel()\r\n\t{\r\n\t\tif (messagePanel != null)\r\n\t\t{\r\n\t\t\tmemberPanelCache.encacheMembers(messagePanel.getHeaderMembers());\r\n\t\t\tmemberPanelCache.encacheMembers(messagePanel.getBodyMembers());\r\n\t\t\tmemberPanelCache.encacheMembers(messagePanel.getTrailerMembers());\r\n\t\t}\r\n\r\n\t\tJPanel mainPanel;\r\n\t\tif (activeMessage != null)\r\n\t\t{\r\n\t\t\tif (!activeMessage.equals(freeTextMessage))\r\n\t\t\t{\r\n\t\t\t\tMessagePanelBuilder builder = new MessagePanelBuilder();\r\n\t\t\t\tbuilder.setFrame(this);\r\n\t\t\t\tbuilder.setSession(sessionsList.getSelectedValue());\r\n\t\t\t\tbuilder.setAppVersion((String) appVersionsComboBox\r\n\t\t\t\t\t\t.getSelectedItem());\r\n\t\t\t\tbuilder.setMessage(activeMessage);\r\n\t\t\t\tbuilder.setIsRequiredOnly(isRequiredOnly);\r\n\t\t\t\tbuilder.setIsModifyHeader(isModifyHeader);\r\n\t\t\t\tbuilder.setIsModifyTrailer(isModifyTrailer);\r\n\t\t\t\tbuilder.setIsFixTSession(isFixTSession);\r\n\t\t\t\tbuilder.setDictionary(activeDictionary);\r\n\t\t\t\tbuilder.setFixTDictionary(fixTDictionary);\r\n\r\n\t\t\t\tmessagePanel = builder.build();\r\n\t\t\t\tmainPanel = messagePanel;\r\n\t\t\t} else\r\n\t\t\t{\r\n\t\t\t\tfreeTextMessagePanel = new FreeTextMessagePanel(messenger,\r\n\t\t\t\t\t\tsessionsList.getSelectedValue(),\r\n\t\t\t\t\t\t(String) appVersionsComboBox.getSelectedItem(),\r\n\t\t\t\t\t\tisFixTSession);\r\n\t\t\t\tmainPanel = freeTextMessagePanel;\r\n\t\t\t}\r\n\t\t} else\r\n\t\t{\r\n\t\t\tmainPanel = blankPanel;\r\n\t\t}\r\n\r\n\t\tmainPanelScrollPane.getViewport().add(mainPanel);\r\n\t}\r\n\r\n\t/**\r\n\t * Returns the active XML ProjectType\r\n\t * \r\n\t * @return the active XML ProjectType\r\n\t */\r\n\tpublic ProjectType getActiveXmlProject()\r\n\t{\r\n\t\treturn activeXmlProject;\r\n\t}\r\n\r\n\tpublic MemberPanelCache getMemberPanelCache()\r\n\t{\r\n\t\treturn memberPanelCache;\r\n\t}\r\n\r\n\t/**\r\n\t * Returns the application instance\r\n\t * \r\n\t * @return the application instance\r\n\t */\r\n\tpublic QFixMessenger getMessenger()\r\n\t{\r\n\t\treturn messenger;\r\n\t}\r\n\r\n\t/**\r\n\t * Returns the current ProjectFrame instance\r\n\t * \r\n\t * @return the current ProjectFrame instance\r\n\t */\r\n\tpublic ProjectDialog getProjectFrame()\r\n\t{\r\n\t\treturn projectDialog;\r\n\t}\r\n\r\n\t/**\r\n\t * Loads an XML MessageType to the UI\r\n\t * \r\n\t * @param xmlMessageType\r\n\t * an XML MessageType\r\n\t */\r\n\tpublic void loadXmlMessage(MessageType xmlMessageType)\r\n\t{\r\n\t\tif (selectSession(xmlMessageType.getSession()))\r\n\t\t{\r\n\t\t\tif (selectMessage(xmlMessageType))\r\n\t\t\t{\r\n\t\t\t\tmessagePanel.populateXml(xmlMessageType);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Saves the active XML ProjectType to a file\r\n\t */\r\n\tpublic void marshallActiveXmlProject()\r\n\t{\r\n\t\tif (activeProjectFile == null)\r\n\t\t{\r\n\t\t\tJFileChooser jFileChooser = new JFileChooser();\r\n\t\t\tjFileChooser.setFileFilter(XmlFileFilter.INSTANCE);\r\n\t\t\tjFileChooser.setDialogTitle(\"Save Project\");\r\n\t\t\tjFileChooser.setSelectedFile(new File(\"*.xml\"));\r\n\r\n\t\t\tint choice = jFileChooser.showSaveDialog(this);\r\n\t\t\tif (choice == JFileChooser.APPROVE_OPTION)\r\n\t\t\t{\r\n\t\t\t\tactiveProjectFile = jFileChooser.getSelectedFile();\r\n\t\t\t}\r\n\r\n\t\t\telse if (choice == JFileChooser.CANCEL_OPTION)\r\n\t\t\t{\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tnew MarshallProjectTypeWorker(this, activeXmlProject, activeProjectFile)\r\n\t\t\t\t.execute();\r\n\t}\r\n\r\n\t/**\r\n\t * Saves an XML MessageType to a file\r\n\t * \r\n\t * @param xmlMessageType\r\n\t * an XML MessageType\r\n\t */\r\n\tpublic void marshallXmlMessage(MessageType xmlMessageType)\r\n\t{\r\n\t\tJFileChooser jFileChooser = new JFileChooser();\r\n\t\tjFileChooser.setFileFilter(XmlFileFilter.INSTANCE);\r\n\t\tjFileChooser.setDialogTitle(\"Export Message\");\r\n\t\tjFileChooser.setSelectedFile(new File(\"*.xml\"));\r\n\r\n\t\tint choice = jFileChooser.showSaveDialog(this);\r\n\t\tif (choice == JFileChooser.APPROVE_OPTION)\r\n\t\t{\r\n\t\t\tFile file = jFileChooser.getSelectedFile();\r\n\t\t\tnew MarshallMessageTypeWorker(this, xmlMessageType, file).execute();\r\n\t\t}\r\n\t}\r\n\r\n\t/**\r\n\t * Sets the active XML ProjectType\r\n\t * \r\n\t * @param xmlProjectType\r\n\t * an XML ProjectType\r\n\t */\r\n\tpublic void setActiveXmlProject(ProjectType xmlProjectType,\r\n\t\t\tFile xmlProjectFile)\r\n\t{\r\n\t\tthis.activeXmlProject = xmlProjectType;\r\n\t\tthis.activeProjectFile = xmlProjectFile;\r\n\t\tif (projectDialog != null)\r\n\t\t{\r\n\t\t\tprojectDialog.dispose();\r\n\t\t\tprojectDialog = null;\r\n\t\t}\r\n\r\n\t\tif (xmlProjectType != null)\r\n\t\t{\r\n\t\t\tprojectTitle = xmlProjectType.getName();\r\n\t\t\tloadFrameTitle();\r\n\t\t\tsaveProjectMenuItem.setEnabled(true);\r\n\t\t\tcloseProjectMenuItem.setEnabled(true);\r\n\t\t\tlaunchProjectDialog();\r\n\t\t} else\r\n\t\t{\r\n\t\t\tprojectTitle = EMPTY_PROJECT_NAME;\r\n\t\t\tloadFrameTitle();\r\n\t\t\tsaveProjectMenuItem.setEnabled(false);\r\n\t\t\tcloseProjectMenuItem.setEnabled(false);\r\n\t\t}\r\n\r\n\t\tupdateButtons();\r\n\t}\r\n\r\n\tprivate GridBagConstraints createRightPanelConstraints()\r\n\t{\r\n\t\tGridBagConstraints c = new GridBagConstraints();\r\n\t\tc.fill = GridBagConstraints.HORIZONTAL;\r\n\r\n\t\tc.weightx = 0.5;\r\n\t\tc.weighty = 0.0;\r\n\r\n\t\tc.ipadx = 2;\r\n\t\tc.ipady = 2;\r\n\r\n\t\tc.gridx = 0;\r\n\t\tc.gridy = GridBagConstraints.RELATIVE;\r\n\r\n\t\treturn c;\r\n\t}\r\n\r\n\tprivate void initAppVersionsComboBox()\r\n\t{\r\n\t\tappVersionsComboBox.setEnabled(false);\r\n\t\tappVersionsComboBox\r\n\t\t\t\t.addActionListener(new AppVersionsComboBoxActionListener(this));\r\n\t}\r\n\r\n\tprivate void initBottomPanel()\r\n\t{\r\n\t\tMessagesTableModel messagesTableModel = new MessagesTableModel();\r\n\r\n\t\tmessagesTable = new JTable(messagesTableModel);\r\n\t\tmessagesTable.getColumnModel().getColumn(0).setPreferredWidth(90);\r\n\t\tmessagesTable.getColumnModel().getColumn(1).setPreferredWidth(5);\r\n\t\tmessagesTable.getColumnModel().getColumn(2).setPreferredWidth(75);\r\n\t\tmessagesTable.getColumnModel().getColumn(3).setPreferredWidth(5);\r\n\t\tmessagesTable.getColumnModel().getColumn(4).setPreferredWidth(510);\r\n\r\n\t\tmessagesTable.setDefaultRenderer(String.class,\r\n\t\t\t\tnew MessagesTableCellRender());\r\n\t\tmessagesTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);\r\n\t\tmessagesTable.addMouseListener(new MessagesTableMouseListener(this));\r\n\r\n\t\tmessenger.getApplication().addMessageListener(messagesTableModel);\r\n\r\n\t\tbottomPanelScrollPane = new JScrollPane(messagesTable);\r\n\t\tbottomPanelScrollPane.setPreferredSize(new Dimension(\r\n\t\t\t\tbottomPanelScrollPane.getPreferredSize().width, 120));\r\n\t\tbottomPanelScrollPane.getViewport().add(messagesTable);\r\n\t\tadd(bottomPanelScrollPane, BorderLayout.SOUTH);\r\n\t}\r\n\r\n\tprivate void initComponents()\r\n\t{\r\n\t\tsetLayout(new BorderLayout());\r\n\r\n\t\tinitMenuBar();\r\n\t\tinitLeftPanel();\r\n\t\tinitMainPanel();\r\n\t\tinitBottomPanel();\r\n\t\tinitRightPanel();\r\n\r\n\t\tpack();\r\n\t}\r\n\r\n\tprivate void initFileMenu()\r\n\t{\r\n\t\tfileMenu = new JMenu(\"File\");\r\n\t\tfileMenu.setMnemonic('F');\r\n\r\n\t\tJMenuItem newProjectMenuItem = new JMenuItem(\"New Project\");\r\n\t\tnewProjectMenuItem.setIcon(IconBuilder.build(\r\n\t\t\t\tgetMessenger().getConfig(), IconBuilder.NEW_ICON));\r\n\t\tnewProjectMenuItem.setMnemonic('N');\r\n\t\tnewProjectMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,\r\n\t\t\t\tInputEvent.CTRL_DOWN_MASK));\r\n\t\tnewProjectMenuItem\r\n\t\t\t\t.addActionListener(new NewProjectActionListener(this));\r\n\r\n\t\tsaveProjectMenuItem = new JMenuItem(\"Save Project\");\r\n\t\tsaveProjectMenuItem.setIcon(IconBuilder.build(getMessenger()\r\n\t\t\t\t.getConfig(), IconBuilder.SAVE_ICON));\r\n\t\tsaveProjectMenuItem.setMnemonic('S');\r\n\t\tsaveProjectMenuItem.setAccelerator(KeyStroke.getKeyStroke(\r\n\t\t\t\tKeyEvent.VK_S, InputEvent.CTRL_DOWN_MASK));\r\n\t\tsaveProjectMenuItem.addActionListener(new SaveProjectActionListener(\r\n\t\t\t\tthis));\r\n\t\tsaveProjectMenuItem.setEnabled(false);\r\n\r\n\t\tJMenuItem openProjectMenuItem = new JMenuItem(\"Open Project\");\r\n\t\topenProjectMenuItem.setIcon(IconBuilder.build(getMessenger()\r\n\t\t\t\t.getConfig(), IconBuilder.OPEN_ICON));\r\n\t\topenProjectMenuItem.setMnemonic('O');\r\n\t\topenProjectMenuItem.setAccelerator(KeyStroke.getKeyStroke(\r\n\t\t\t\tKeyEvent.VK_O, InputEvent.CTRL_DOWN_MASK));\r\n\t\topenProjectMenuItem.addActionListener(new OpenProjectActionListener(\r\n\t\t\t\tthis));\r\n\r\n\t\tcloseProjectMenuItem = new JMenuItem(\"Close Project\");\r\n\t\tcloseProjectMenuItem.setIcon(IconBuilder.build(getMessenger()\r\n\t\t\t\t.getConfig(), IconBuilder.CLOSE_ICON));\r\n\t\tcloseProjectMenuItem.setMnemonic('C');\r\n\t\tcloseProjectMenuItem.addActionListener(new CloseProjectActionListener(\r\n\t\t\t\tthis));\r\n\t\tcloseProjectMenuItem.setEnabled(false);\r\n\r\n\t\tJMenuItem importMessageMenuItem = new JMenuItem(\"Import Message\");\r\n\t\timportMessageMenuItem.setIcon(IconBuilder.build(getMessenger()\r\n\t\t\t\t.getConfig(), IconBuilder.IMPORT_ICON));\r\n\t\timportMessageMenuItem.setMnemonic('I');\r\n\t\timportMessageMenuItem.setAccelerator(KeyStroke.getKeyStroke(\r\n\t\t\t\tKeyEvent.VK_I, InputEvent.CTRL_DOWN_MASK));\r\n\t\timportMessageMenuItem\r\n\t\t\t\t.addActionListener(new ImportMessageActionListener(this));\r\n\r\n\t\tJMenuItem exportMessageMenuItem = new JMenuItem(\"Export Message\");\r\n\t\texportMessageMenuItem.setIcon(IconBuilder.build(getMessenger()\r\n\t\t\t\t.getConfig(), IconBuilder.EXPORT_ICON));\r\n\t\texportMessageMenuItem\r\n\t\t\t\t.addActionListener(new ExportMessageActionListener(this));\r\n\t\texportMessageMenuItem.setMnemonic('X');\r\n\t\texportMessageMenuItem.setAccelerator(KeyStroke.getKeyStroke(\r\n\t\t\t\tKeyEvent.VK_E, InputEvent.CTRL_DOWN_MASK));\r\n\r\n\t\tJMenuItem exitMenuItem = new JMenuItem(\"Exit\");\r\n\t\texitMenuItem.setIcon(IconBuilder.build(getMessenger().getConfig(),\r\n\t\t\t\tIconBuilder.EXIT_ICON));\r\n\t\texitMenuItem.setMnemonic('x');\r\n\t\texitMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X,\r\n\t\t\t\tInputEvent.ALT_DOWN_MASK));\r\n\t\texitMenuItem.addActionListener(new FrameExitActionListener(this));\r\n\r\n\t\tfileMenu.add(newProjectMenuItem);\r\n\t\tfileMenu.add(saveProjectMenuItem);\r\n\t\tfileMenu.add(openProjectMenuItem);\r\n\t\tfileMenu.add(closeProjectMenuItem);\r\n\t\tfileMenu.addSeparator();\r\n\t\tfileMenu.add(importMessageMenuItem);\r\n\t\tfileMenu.add(exportMessageMenuItem);\r\n\t\tfileMenu.addSeparator();\r\n\t\tfileMenu.add(exitMenuItem);\r\n\t}\r\n\r\n\tprivate void initFrame()\r\n\t{\r\n\t\tif (messenger.getConfig().isInitiator())\r\n\t\t{\r\n\t\t\tframeTitle = \"QuickFIX Messenger \" + VERSION + \" (Initiator)\";\r\n\t\t} else\r\n\t\t{\r\n\t\t\tframeTitle = \"QuickFIX Messenger \" + VERSION + \" (Acceptor)\";\r\n\t\t}\r\n\t\tloadFrameTitle();\r\n\t\tsetIconImage(IconBuilder.build(getMessenger().getConfig(),\r\n\t\t\t\tIconBuilder.APP_ICON).getImage());\r\n\t\tsetDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);\r\n\t\taddWindowListener(new FrameWindowAdapter(this));\r\n\t\tsetMinimumSize(new Dimension(FRAME_MIN_WIDTH, FRAME_MIN_HEIGHT));\r\n\t}\r\n\r\n\tprivate void initHelpMenu()\r\n\t{\r\n\t\thelpMenu = new JMenu(\"Help\");\r\n\t\thelpMenu.setMnemonic('H');\r\n\r\n\t\tJMenuItem helpMenuItem = new JMenuItem(\"Help\");\r\n\t\thelpMenuItem.setIcon(IconBuilder.build(getMessenger().getConfig(),\r\n\t\t\t\tIconBuilder.HELP_ICON));\r\n\t\thelpMenuItem.setMnemonic('H');\r\n\t\thelpMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F2,\r\n\t\t\t\tInputEvent.SHIFT_DOWN_MASK));\r\n\t\thelpMenuItem.addActionListener(new HelpActionListener(this));\r\n\r\n\t\tJMenuItem aboutMenuItem = new JMenuItem(\"About\");\r\n\t\taboutMenuItem.setMnemonic('A');\r\n\t\taboutMenuItem.addActionListener(new AboutActionListener(this));\r\n\r\n\t\thelpMenu.add(helpMenuItem);\r\n\t\thelpMenu.add(aboutMenuItem);\r\n\t}\r\n\r\n\tprivate void initLeftPanel()\r\n\t{\r\n\t\tleftPanel = new JPanel();\r\n\t\tleftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.Y_AXIS));\r\n\r\n\t\t// Sessions Panel\r\n\t\tsessionsList = new JList<Session>();\r\n\t\tappVersionsComboBox = new JComboBox<String>(\r\n\t\t\t\tQFixMessengerConstants.FIXT_APP_VERSIONS);\r\n\t\tJPanel sessionsPanel = new JPanel();\r\n\t\tsessionsPanel.setBorder(new TitledBorder(\"Current Sessions\"));\r\n\t\tsessionsPanel.setLayout(new BorderLayout());\r\n\r\n\t\tinitSessionsList();\r\n\t\tJScrollPane sessionsListScrollPane = new JScrollPane(sessionsList);\r\n\t\tsessionsListScrollPane.setPreferredSize(new Dimension(LEFT_PANEL_WIDTH,\r\n\t\t\t\t120));\r\n\t\tsessionsListScrollPane.setMaximumSize(sessionsListScrollPane\r\n\t\t\t\t.getPreferredSize());\r\n\r\n\t\tinitAppVersionsComboBox();\r\n\t\tJPanel appVersionsPanel = new JPanel();\r\n\t\tappVersionsPanel.setLayout(new GridLayout(2, 1));\r\n\t\tappVersionsPanel.add(new JLabel(\"ApplVerID: \"));\r\n\t\tappVersionsPanel.add(appVersionsComboBox);\r\n\r\n\t\tsessionsPanel.add(sessionsListScrollPane, BorderLayout.CENTER);\r\n\t\tsessionsPanel.add(appVersionsPanel, BorderLayout.SOUTH);\r\n\r\n\t\t// Prevent resize\r\n\t\tsessionsPanel.setMinimumSize(sessionsPanel.getPreferredSize());\r\n\t\tsessionsPanel.setMaximumSize(sessionsPanel.getPreferredSize());\r\n\r\n\t\t// Messages Panel\r\n\t\tmessagesList = new JList<Message>();\r\n\r\n\t\trecentMessagesMap = new HashMap<>();\r\n\t\trecentMessagesListModel = new DefaultListModel<Message>();\r\n\t\trecentMessagesList = new JList<Message>(recentMessagesListModel);\r\n\r\n\t\tJPanel messagesPanel = new JPanel();\r\n\t\tmessagesPanel.setBorder(new TitledBorder(\"Available Messages\"));\r\n\t\tmessagesPanel.setLayout(new BoxLayout(messagesPanel, BoxLayout.Y_AXIS));\r\n\r\n\t\tinitMessagesList();\r\n\r\n\t\tJScrollPane messagesListScrollPane = new JScrollPane(messagesList);\r\n\t\tmessagesListScrollPane.setPreferredSize(new Dimension(LEFT_PANEL_WIDTH,\r\n\t\t\t\t300));\r\n\r\n\t\tJScrollPane recentMessagesListScrollPane = new JScrollPane(\r\n\t\t\t\trecentMessagesList);\r\n\t\tmessagesTabPane = new JTabbedPane();\r\n\t\tmessagesTabPane.setPreferredSize(new Dimension(LEFT_PANEL_WIDTH, 300));\r\n\t\tmessagesTabPane.addTab(\"All\", messagesListScrollPane);\r\n\t\tmessagesTabPane.addTab(\"Recent\", recentMessagesListScrollPane);\r\n\r\n\t\tmessagesPanel.add(messagesTabPane);\r\n\r\n\t\tleftPanel.add(sessionsPanel);\r\n\t\tleftPanel.add(messagesPanel);\r\n\t\tadd(leftPanel, BorderLayout.WEST);\r\n\t}\r\n\r\n\tprivate void initMainPanel()\r\n\t{\r\n\t\tmainPanelScrollPane = new JScrollPane();\r\n\t\tadd(mainPanelScrollPane, BorderLayout.CENTER);\r\n\t}\r\n\r\n\tprivate void initMenuBar()\r\n\t{\r\n\t\tmenuBar = new JMenuBar();\r\n\r\n\t\tinitFileMenu();\r\n\t\tinitSessionMenu();\r\n\t\tinitHelpMenu();\r\n\t\tinitWindowMenu();\r\n\r\n\t\tmenuBar.add(fileMenu);\r\n\t\tmenuBar.add(sessionMenu);\r\n\t\tmenuBar.add(helpMenu);\r\n\t\tmenuBar.add(windowMenu);\r\n\r\n\t\tsetJMenuBar(menuBar);\r\n\t}\r\n\r\n\tprivate void initMessagesList()\r\n\t{\r\n\t\tmessagesList.setCellRenderer(new MessagesListCellRenderer());\r\n\t\tmessagesList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);\r\n\t\tmessagesList.getSelectionModel().addListSelectionListener(\r\n\t\t\t\tnew MessagesListSelectionListener(this));\r\n\t\tmessagesList.addMouseListener(new MessagesListMouseAdapter(this));\r\n\r\n\t\trecentMessagesList.setCellRenderer(new MessagesListCellRenderer());\r\n\t\trecentMessagesList\r\n\t\t\t\t.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);\r\n\t\trecentMessagesList.getSelectionModel().addListSelectionListener(\r\n\t\t\t\tnew RecentMessagesListSelectionListener(this));\r\n\t\trecentMessagesList.addMouseListener(new RecentMessagesListMouseAdapter(\r\n\t\t\t\tthis));\r\n\t}\r\n\r\n\tprivate void initRightPanel()\r\n\t{\r\n\t\trightPanel = new JPanel();\r\n\t\trightPanel.setLayout(new BorderLayout());\r\n\r\n\t\tJPanel optionsPanel = new JPanel();\r\n\t\toptionsPanel.setBorder(new TitledBorder(\"Options\"));\r\n\t\toptionsPanel.setLayout(new BoxLayout(optionsPanel, BoxLayout.Y_AXIS));\r\n\r\n\t\trequiredCheckBox = new JCheckBox(\"Required Only\", true);\r\n\t\trequiredCheckBox.addItemListener(new ItemListener()\r\n\t\t{\r\n\t\t\t@Override\r\n\t\t\tpublic void itemStateChanged(ItemEvent e)\r\n\t\t\t{\r\n\t\t\t\tif (e.getStateChange() == ItemEvent.SELECTED)\r\n\t\t\t\t{\r\n\t\t\t\t\tisRequiredOnly = true;\r\n\t\t\t\t} else\r\n\t\t\t\t{\r\n\t\t\t\t\tisRequiredOnly = false;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (logger.isDebugEnabled())\r\n\t\t\t\t{\r\n\t\t\t\t\tlogger.debug(\"Selected isRequiredOnly = \" + isRequiredOnly);\r\n\t\t\t\t}\r\n\t\t\t\tdisplayMainPanel();\r\n\t\t\t}\r\n\t\t});\r\n\r\n\t\tmodifyHeaderCheckBox = new JCheckBox(\"Modify Header\", false);\r\n\t\tmodifyHeaderCheckBox.addItemListener(new ItemListener()\r\n\t\t{\r\n\t\t\t@Override\r\n\t\t\tpublic void itemStateChanged(ItemEvent e)\r\n\t\t\t{\r\n\t\t\t\tif (e.getStateChange() == ItemEvent.SELECTED)\r\n\t\t\t\t{\r\n\t\t\t\t\tisModifyHeader = true;\r\n\t\t\t\t} else\r\n\t\t\t\t{\r\n\t\t\t\t\tisModifyHeader = false;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (logger.isDebugEnabled())\r\n\t\t\t\t{\r\n\t\t\t\t\tlogger.debug(\"Selected isModifyHeader = \" + isModifyHeader);\r\n\t\t\t\t}\r\n\t\t\t\tdisplayMainPanel();\r\n\t\t\t}\r\n\t\t});\r\n\r\n\t\tmodifyTrailerCheckBox = new JCheckBox(\"Modify Trailer\", false);\r\n\t\tmodifyTrailerCheckBox.addItemListener(new ItemListener()\r\n\t\t{\r\n\t\t\t@Override\r\n\t\t\tpublic void itemStateChanged(ItemEvent e)\r\n\t\t\t{\r\n\t\t\t\tif (e.getStateChange() == ItemEvent.SELECTED)\r\n\t\t\t\t{\r\n\t\t\t\t\tisModifyTrailer = true;\r\n\t\t\t\t} else\r\n\t\t\t\t{\r\n\t\t\t\t\tisModifyTrailer = false;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (logger.isDebugEnabled())\r\n\t\t\t\t{\r\n\t\t\t\t\tlogger.debug(\"Selected isModifyTrailer = \"\r\n\t\t\t\t\t\t\t+ isModifyTrailer);\r\n\t\t\t\t}\r\n\t\t\t\tdisplayMainPanel();\r\n\t\t\t}\r\n\t\t});\r\n\r\n\t\toptionsPanel.add(requiredCheckBox);\r\n\t\toptionsPanel.add(modifyHeaderCheckBox);\r\n\t\toptionsPanel.add(modifyTrailerCheckBox);\r\n\r\n\t\tJPanel sendPanel = new JPanel();\r\n\t\tsendPanel.setLayout(new GridBagLayout());\r\n\r\n\t\tpreviewBeforeSendCheckBox = new JCheckBox(\"Preview Before Sending\",\r\n\t\t\t\tfalse);\r\n\t\tpreviewBeforeSendCheckBox.addItemListener(new ItemListener()\r\n\t\t{\r\n\t\t\t@Override\r\n\t\t\tpublic void itemStateChanged(ItemEvent e)\r\n\t\t\t{\r\n\t\t\t\tif (e.getStateChange() == ItemEvent.SELECTED)\r\n\t\t\t\t{\r\n\t\t\t\t\tisPreviewBeforeSend = true;\r\n\t\t\t\t} else\r\n\t\t\t\t{\r\n\t\t\t\t\tisPreviewBeforeSend = false;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (logger.isDebugEnabled())\r\n\t\t\t\t{\r\n\t\t\t\t\tlogger.debug(\"Selected isPreviewBeforeSend = \"\r\n\t\t\t\t\t\t\t+ isPreviewBeforeSend);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t});\r\n\r\n\t\tImageIcon destroyImageIcon = IconBuilder.build(getMessenger()\r\n\t\t\t\t.getConfig(), IconBuilder.DESTROY_ICON);\r\n\t\tdestroyButton = new JButton(destroyImageIcon);\r\n\t\tdestroyButton.addActionListener(new DestroyMessageActionListener(this));\r\n\t\tdestroyButton.setToolTipText(\"Destroys the message\");\r\n\t\tdestroyButton.setEnabled(false);\r\n\r\n\t\tImageIcon addImageIcon = IconBuilder.build(getMessenger().getConfig(),\r\n\t\t\t\tIconBuilder.ADD_ICON);\r\n\t\taddButton = new JButton(addImageIcon);\r\n\t\taddButton.addActionListener(new AddMessageActionListener(this));\r\n\t\taddButton.setToolTipText(\"Adds the message to the current project\");\r\n\t\taddButton.setEnabled(false);\r\n\r\n\t\tImageIcon sendImageIcon = IconBuilder.build(getMessenger().getConfig(),\r\n\t\t\t\tIconBuilder.SEND_ICON);\r\n\t\tsendButton = new JButton(sendImageIcon);\r\n\t\tsendButton.addActionListener(new SendActionListener(this));\r\n\t\tsendButton.setToolTipText(\"Sends the message across the session\");\r\n\t\tsendButton.setEnabled(false);\r\n\r\n\t\tsendPanel.add(destroyButton, createRightPanelConstraints());\r\n\t\tsendPanel.add(addButton, createRightPanelConstraints());\r\n\t\tsendPanel.add(sendButton, createRightPanelConstraints());\r\n\t\tsendPanel.add(previewBeforeSendCheckBox, createRightPanelConstraints());\r\n\r\n\t\trightPanel.add(optionsPanel, BorderLayout.NORTH);\r\n\t\trightPanel.add(sendPanel, BorderLayout.SOUTH);\r\n\t\tadd(rightPanel, BorderLayout.EAST);\r\n\t}\r\n\r\n\tprivate void initSessionMenu()\r\n\t{\r\n\t\tsessionMenu = new JMenu(\"Session\");\r\n\t\tsessionMenu.setMnemonic('S');\r\n\r\n\t\tJMenu currentSessionMenu;\r\n\t\tJCheckBoxMenuItem logonMenuItem;\r\n\t\tJMenuItem resetMenuItem;\r\n\t\tJMenuItem statusMenuItem;\r\n\t\tfor (SessionID sessionId : messenger.getConnector().getSessions())\r\n\t\t{\r\n\t\t\tSession session = Session.lookupSession(sessionId);\r\n\t\t\tcurrentSessionMenu = new JMenu(QFixUtil.getSessionName(sessionId));\r\n\r\n\t\t\tlogonMenuItem = new JCheckBoxMenuItem(\"Logon\");\r\n\t\t\tlogonMenuItem\r\n\t\t\t\t\t.addItemListener(new LogonSessionItemListener(session));\r\n\t\t\tif (session.isLoggedOn())\r\n\t\t\t{\r\n\t\t\t\tlogonMenuItem.setSelected(true);\r\n\t\t\t} else\r\n\t\t\t{\r\n\t\t\t\tlogonMenuItem.setSelected(false);\r\n\t\t\t}\r\n\t\t\tsession.addStateListener(new LogonSessionMenuItemSessionStateListener(\r\n\t\t\t\t\tlogonMenuItem));\r\n\r\n\t\t\tresetMenuItem = new JMenuItem(\"Reset\");\r\n\t\t\tresetMenuItem.addActionListener(new ResetSessionActionListener(\r\n\t\t\t\t\tthis, session));\r\n\r\n\t\t\tstatusMenuItem = new JMenuItem(\"Status\");\r\n\t\t\tstatusMenuItem.addActionListener(new SessionStatusActionListener(\r\n\t\t\t\t\tthis, session));\r\n\r\n\t\t\tcurrentSessionMenu.add(logonMenuItem);\r\n\t\t\tcurrentSessionMenu.add(resetMenuItem);\r\n\t\t\tcurrentSessionMenu.add(statusMenuItem);\r\n\t\t\tsessionMenu.add(currentSessionMenu);\r\n\t\t}\r\n\r\n\t\tJMenuItem logonAllSessionsMenuItem = new JMenuItem(\r\n\t\t\t\t\"All Sessions - Logon\");\r\n\t\tlogonAllSessionsMenuItem.setIcon(IconBuilder.build(getMessenger()\r\n\t\t\t\t.getConfig(), IconBuilder.LOGON_ICON));\r\n\t\tlogonAllSessionsMenuItem.setMnemonic('n');\r\n\t\tlogonAllSessionsMenuItem.setAccelerator(KeyStroke.getKeyStroke(\r\n\t\t\t\tKeyEvent.VK_N, InputEvent.CTRL_DOWN_MASK));\r\n\t\tlogonAllSessionsMenuItem\r\n\t\t\t\t.addActionListener(new LogonAllSessionsActionListener(this));\r\n\r\n\t\tJMenuItem logoffAllSessionsMenuItem = new JMenuItem(\r\n\t\t\t\t\"All Sessions - Logoff\");\r\n\t\tlogoffAllSessionsMenuItem.setIcon(IconBuilder.build(getMessenger()\r\n\t\t\t\t.getConfig(), IconBuilder.LOGOFF_ICON));\r\n\t\tlogoffAllSessionsMenuItem.setMnemonic('f');\r\n\t\tlogoffAllSessionsMenuItem.setAccelerator(KeyStroke.getKeyStroke(\r\n\t\t\t\tKeyEvent.VK_F, InputEvent.CTRL_DOWN_MASK));\r\n\t\tlogoffAllSessionsMenuItem\r\n\t\t\t\t.addActionListener(new LogoffAllSessionsActionListener(this));\r\n\r\n\t\tJMenuItem resetAllSessionsMenuItem = new JMenuItem(\r\n\t\t\t\t\"All Sessions - Reset\");\r\n\t\tresetAllSessionsMenuItem.setIcon(IconBuilder.build(getMessenger()\r\n\t\t\t\t.getConfig(), IconBuilder.RESET_ICON));\r\n\t\tresetAllSessionsMenuItem.setMnemonic('R');\r\n\t\tresetAllSessionsMenuItem.setAccelerator(KeyStroke.getKeyStroke(\r\n\t\t\t\tKeyEvent.VK_R, InputEvent.CTRL_DOWN_MASK));\r\n\t\tresetAllSessionsMenuItem\r\n\t\t\t\t.addActionListener(new ResetAllSessionsActionListener(this));\r\n\r\n\t\tsessionMenu.addSeparator();\r\n\t\tsessionMenu.add(logonAllSessionsMenuItem);\r\n\t\tsessionMenu.add(logoffAllSessionsMenuItem);\r\n\t\tsessionMenu.add(resetAllSessionsMenuItem);\r\n\t}\r\n\r\n\tprivate void initSessionsList()\r\n\t{\r\n\t\tsessionsList = new JList<Session>();\r\n\r\n\t\tList<SessionID> sessionIds = messenger.getConnector().getSessions();\r\n\t\tList<Session> sessions = new ArrayList<Session>(sessionIds.size());\r\n\t\tfor (SessionID sessionId : sessionIds)\r\n\t\t{\r\n\t\t\tSession session = Session.lookupSession(sessionId);\r\n\t\t\tsession.addStateListener(new SessionsListSessionStateListener(\r\n\t\t\t\t\tsessionsList));\r\n\t\t\tsessions.add(session);\r\n\t\t}\r\n\r\n\t\tCollections.sort(sessions, new Comparator<Session>()\r\n\t\t{\r\n\t\t\t@Override\r\n\t\t\tpublic int compare(Session o1, Session o2)\r\n\t\t\t{\r\n\t\t\t\treturn o1.getSessionID().getBeginString()\r\n\t\t\t\t\t\t.compareTo(o2.getSessionID().getBeginString());\r\n\t\t\t}\r\n\t\t});\r\n\r\n\t\tsessionsList.setListData(sessions.toArray(new Session[] {}));\r\n\t\tsessionsList.setCellRenderer(new SessionsListCellRenderer());\r\n\t\tsessionsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);\r\n\t\tsessionsList.getSelectionModel().addListSelectionListener(\r\n\t\t\t\tnew SessionsListSelectionListener(this));\r\n\t\tsessionsList.addMouseListener(new SessionsListMouseAdapter(this));\r\n\t}\r\n\r\n\tprivate void initWindowMenu()\r\n\t{\r\n\t\twindowMenu = new JMenu(\"Window\");\r\n\t\twindowMenu.setMnemonic('W');\r\n\r\n\t\tJMenuItem projectWindowMenuItem = new JMenuItem(\"Project Window\");\r\n\t\tJMenuItem logfileWindowMenuItem = new JMenuItem(\"Logfile Window\");\r\n\r\n\t\tprojectWindowMenuItem.setIcon(IconBuilder.build(getMessenger()\r\n\t\t\t\t.getConfig(), IconBuilder.WINDOW_ICON));\r\n\t\tprojectWindowMenuItem.setMnemonic('P');\r\n\t\tprojectWindowMenuItem.setAccelerator(KeyStroke.getKeyStroke(\r\n\t\t\t\tKeyEvent.VK_P, InputEvent.CTRL_DOWN_MASK));\r\n\t\tprojectWindowMenuItem\r\n\t\t\t\t.addActionListener(new ProjectWindowActionListener(this));\r\n\r\n\t\tlogfileWindowMenuItem.setIcon(IconBuilder.build(getMessenger()\r\n\t\t\t\t.getConfig(), IconBuilder.WINDOW_ICON));\r\n\t\tlogfileWindowMenuItem.setMnemonic('L');\r\n\t\tlogfileWindowMenuItem.setAccelerator(KeyStroke.getKeyStroke(\r\n\t\t\t\tKeyEvent.VK_L, InputEvent.CTRL_DOWN_MASK));\r\n\t\tlogfileWindowMenuItem\r\n\t\t\t\t.addActionListener(new LogfileWindowActionListener(this));\r\n\r\n\t\twindowMenu.add(logfileWindowMenuItem);\r\n\t\twindowMenu.add(projectWindowMenuItem);\r\n\t}\r\n\r\n\tprivate void launchProjectDialog()\r\n\t{\r\n\t\tif (projectDialog == null || !projectDialog.isDisplayable())\r\n\t\t{\r\n\t\t\tprojectDialog = new ProjectDialog(this, activeXmlProject);\r\n\t\t\tprojectDialog.launch();\r\n\t\t} else\r\n\t\t{\r\n\t\t\tprojectDialog.requestFocus();\r\n\t\t}\r\n\t}\r\n\r\n\tprivate void launchLogfileDialog()\r\n\t{\r\n\t\tString beginStr = sessionsList.getSelectedValue().getSessionID()\r\n\t\t\t\t.getBeginString();\r\n\r\n\t\tif (logfileDialog == null || !logfileDialog.isDisplayable())\r\n\t\t{\r\n\r\n\t\t\tlogfileDialog = new LogfileDialog(this);\r\n\t\t\tlogfileDialog.launch(beginStr);\r\n\t\t} else\r\n\t\t{\r\n\t\t\tlogfileDialog.loadLogfile(beginStr);\r\n\t\t\tlogfileDialog.requestFocus();\r\n\t\t}\r\n\t}\r\n\r\n\tprivate void loadFrameTitle()\r\n\t{\r\n\t\tsetTitle(frameTitle + \" - \" + projectTitle);\r\n\t}\r\n\r\n\tprivate void loadMessagesList()\r\n\t{\r\n\t\tif (activeDictionary != null)\r\n\t\t{\r\n\t\t\tList<Message> messages = new ArrayList<Message>();\r\n\t\t\tmessages.addAll(activeDictionary.getMessages().values());\r\n\t\t\tCollections.sort(messages);\r\n\r\n\t\t\tmessages.add(0, freeTextMessage);\r\n\r\n\t\t\tmessagesList.setListData(messages.toArray(new Message[] {}));\r\n\r\n\t\t\tDefaultListModel<Message> listModel = recentMessagesMap\r\n\t\t\t\t\t.get(activeDictionary.getFullVersion());\r\n\t\t\tif (listModel != null)\r\n\t\t\t{\r\n\t\t\t\trecentMessagesListModel = listModel;\r\n\t\t\t} else\r\n\t\t\t{\r\n\t\t\t\trecentMessagesListModel = new DefaultListModel<>();\r\n\t\t\t}\r\n\r\n\t\t} else\r\n\t\t{\r\n\t\t\trecentMessagesListModel = new DefaultListModel<Message>();\r\n\t\t\tmessagesList.setListData(new Message[] {});\r\n\t\t}\r\n\r\n\t\trecentMessagesList.setModel(recentMessagesListModel);\r\n\r\n\t}\r\n\r\n\t/*\r\n\t * Position the frame at the center of the screen\r\n\t */\r\n\tprivate void positionFrame()\r\n\t{\r\n\t\tToolkit defaultToolkit = Toolkit.getDefaultToolkit();\r\n\t\tDimension screenSize = defaultToolkit.getScreenSize();\r\n\t\tint screenHeight = screenSize.height;\r\n\t\tint screenWidth = screenSize.width;\r\n\t\tsetSize(screenWidth / 2, screenHeight / 2);\r\n\t\tsetLocation(screenWidth / 4, screenHeight / 4);\r\n\t}\r\n\r\n\tprivate boolean selectMessage(MessageType xmlMessageType)\r\n\t{\r\n\t\tboolean isRecognizedMessage = false;\r\n\t\tListModel<Message> listModel = messagesList.getModel();\r\n\t\tfor (int i = 0; i < listModel.getSize(); i++)\r\n\t\t{\r\n\t\t\tMessage message = listModel.getElementAt(i);\r\n\t\t\tif (message.getMsgType().equals(xmlMessageType.getMsgType()))\r\n\t\t\t{\r\n\t\t\t\tmessagesList.setSelectedIndex(i);\r\n\r\n\t\t\t\tif (xmlMessageType.isIsRequiredOnly())\r\n\t\t\t\t{\r\n\t\t\t\t\trequiredCheckBox.setSelected(true);\r\n\t\t\t\t} else\r\n\t\t\t\t{\r\n\t\t\t\t\trequiredCheckBox.setSelected(false);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (xmlMessageType.getHeader() != null\r\n\t\t\t\t\t\t&& xmlMessageType.getHeader().getField() != null\r\n\t\t\t\t\t\t&& xmlMessageType.getHeader().getField().isEmpty())\r\n\t\t\t\t{\r\n\t\t\t\t\tmodifyHeaderCheckBox.setSelected(true);\r\n\t\t\t\t} else\r\n\t\t\t\t{\r\n\t\t\t\t\tmodifyHeaderCheckBox.setSelected(false);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (xmlMessageType.getTrailer() != null\r\n\t\t\t\t\t\t&& xmlMessageType.getTrailer().getField() != null\r\n\t\t\t\t\t\t&& xmlMessageType.getTrailer().getField().isEmpty())\r\n\t\t\t\t{\r\n\t\t\t\t\tmodifyTrailerCheckBox.setSelected(true);\r\n\t\t\t\t} else\r\n\t\t\t\t{\r\n\t\t\t\t\tmodifyTrailerCheckBox.setSelected(false);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tisRecognizedMessage = true;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (!isRecognizedMessage)\r\n\t\t{\r\n\t\t\tlogger.error(\"Unrecognized message: \", xmlMessageType.getName()\r\n\t\t\t\t\t+ \" (\" + xmlMessageType.getMsgType() + \")\");\r\n\t\t\tJOptionPane.showMessageDialog(\r\n\t\t\t\t\tthis,\r\n\t\t\t\t\t\"Unable to import message from unrecognized message: \"\r\n\t\t\t\t\t\t\t+ xmlMessageType.getName() + \" (\"\r\n\t\t\t\t\t\t\t+ xmlMessageType.getMsgType() + \")\", \"Error\",\r\n\t\t\t\t\tJOptionPane.ERROR_MESSAGE);\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\treturn true;\r\n\t}\r\n\r\n\tprivate boolean selectSession(SessionType xmlSessionType)\r\n\t{\r\n\t\tboolean isRecognizedSession = false;\r\n\t\tListModel<Session> listModel = sessionsList.getModel();\r\n\t\tfor (int i = 0; i < listModel.getSize(); i++)\r\n\t\t{\r\n\t\t\tSession session = listModel.getElementAt(i);\r\n\t\t\tif (QFixUtil.getSessionName(session.getSessionID()).equals(\r\n\t\t\t\t\txmlSessionType.getName()))\r\n\t\t\t{\r\n\t\t\t\tsessionsList.setSelectedIndex(i);\r\n\t\t\t\tisRecognizedSession = true;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (isRecognizedSession)\r\n\t\t{\r\n\t\t\tif (isFixTSession)\r\n\t\t\t{\r\n\t\t\t\tif (xmlSessionType.getAppVersionId() != null\r\n\t\t\t\t\t\t&& !xmlSessionType.getAppVersionId().isEmpty())\r\n\t\t\t\t{\r\n\t\t\t\t\tboolean isRecognizedAppVersionId = false;\r\n\t\t\t\t\tComboBoxModel<String> comboBoxModel = appVersionsComboBox\r\n\t\t\t\t\t\t\t.getModel();\r\n\t\t\t\t\tfor (int i = 0; i < comboBoxModel.getSize(); i++)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tif (comboBoxModel.getElementAt(i).equals(\r\n\t\t\t\t\t\t\t\txmlSessionType.getAppVersionId()))\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tappVersionsComboBox.setSelectedIndex(i);\r\n\t\t\t\t\t\t\tisRecognizedAppVersionId = true;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tif (!isRecognizedAppVersionId)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tlogger.error(\"Unrecognized AppVersionId: \"\r\n\t\t\t\t\t\t\t\t+ xmlSessionType.getAppVersionId());\r\n\t\t\t\t\t\tJOptionPane.showMessageDialog(\r\n\t\t\t\t\t\t\t\tthis,\r\n\t\t\t\t\t\t\t\t\"Unrecognized AppVersionId: \"\r\n\t\t\t\t\t\t\t\t\t\t+ xmlSessionType.getAppVersionId(),\r\n\t\t\t\t\t\t\t\t\"Error\", JOptionPane.ERROR_MESSAGE);\r\n\t\t\t\t\t\treturn false;\r\n\t\t\t\t\t}\r\n\t\t\t\t} else\r\n\t\t\t\t{\r\n\t\t\t\t\tlogger.error(\"FIXT session \", xmlSessionType.getName()\r\n\t\t\t\t\t\t\t+ \" has no AppVersionId\");\r\n\t\t\t\t\tJOptionPane.showMessageDialog(this,\r\n\t\t\t\t\t\t\t\"Unable to find AppVersionId for FIXT session: \"\r\n\t\t\t\t\t\t\t\t\t+ xmlSessionType.getName(), \"Error\",\r\n\t\t\t\t\t\t\tJOptionPane.ERROR_MESSAGE);\r\n\t\t\t\t\treturn false;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t} else\r\n\t\t{\r\n\t\t\tlogger.error(\"Unrecognized session: \", xmlSessionType.getName());\r\n\t\t\tJOptionPane.showMessageDialog(this, \"Unable to\"\r\n\t\t\t\t\t+ \" import message from unrecognized session: \"\r\n\t\t\t\t\t+ xmlSessionType.getName(), \"Error\",\r\n\t\t\t\t\tJOptionPane.ERROR_MESSAGE);\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\treturn true;\r\n\t}\r\n\r\n\tprivate void updateButtons()\r\n\t{\r\n\t\tif (activeMessage != null)\r\n\t\t{\r\n\t\t\tdestroyButton.setEnabled(true);\r\n\t\t\tsendButton.setEnabled(true);\r\n\t\t\tif (activeXmlProject != null)\r\n\t\t\t{\r\n\t\t\t\taddButton.setEnabled(true);\r\n\t\t\t} else\r\n\t\t\t{\r\n\t\t\t\taddButton.setEnabled(false);\r\n\t\t\t}\r\n\t\t} else\r\n\t\t{\r\n\t\t\tdestroyButton.setEnabled(false);\r\n\t\t\tsendButton.setEnabled(false);\r\n\t\t\taddButton.setEnabled(false);\r\n\t\t}\r\n\t}\r\n\r\n\tprivate void updateLogFile(String beginStr)\r\n\t{\r\n\t\tif (logfileDialog != null && logfileDialog.isVisible())\r\n\t\t{\r\n\t\t\tlogfileDialog.loadLogfile(beginStr);\r\n\t\t}\r\n\t}\r\n\r\n\tpublic static class XmlFileFilter extends FileFilter\r\n\t{\r\n\t\tpublic static final XmlFileFilter INSTANCE = new XmlFileFilter();\r\n\r\n\t\t@Override\r\n\t\tpublic boolean accept(File f)\r\n\t\t{\r\n\t\t\tif (f.isDirectory())\r\n\t\t\t{\r\n\t\t\t\treturn true;\r\n\t\t\t}\r\n\t\t\treturn f.getName().endsWith(\".xml\");\r\n\t\t}\r\n\r\n\t\t@Override\r\n\t\tpublic String getDescription()\r\n\t\t{\r\n\t\t\treturn \"XML Files (*.xml)\";\r\n\t\t}\r\n\t}\r\n\r\n\tprivate static class AddMessageActionListener implements ActionListener\r\n\t{\r\n\t\tprivate QFixMessengerFrame frame;\r\n\r\n\t\tpublic AddMessageActionListener(QFixMessengerFrame frame)\r\n\t\t{\r\n\t\t\tthis.frame = frame;\r\n\t\t}\r\n\r\n\t\t@Override\r\n\t\tpublic void actionPerformed(ActionEvent e)\r\n\t\t{\r\n\t\t\tif (!frame.activeMessage.equals(frame.freeTextMessage))\r\n\t\t\t{\r\n\t\t\t\tMessageType xmlMessageType = frame.messagePanel.getXmlMember();\r\n\t\t\t\tProjectType xmlProjectType = frame.getActiveXmlProject();\r\n\t\t\t\txmlProjectType.getMessages().getMessage().add(xmlMessageType);\r\n\t\t\t\tframe.projectDialog.updateMessageAdded(xmlMessageType);\r\n\t\t\t} else\r\n\t\t\t{\r\n\t\t\t\tJOptionPane.showMessageDialog(frame,\r\n\t\t\t\t\t\t\"Projects do not support free text messages!\", \"Error\",\r\n\t\t\t\t\t\tJOptionPane.WARNING_MESSAGE);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tprivate static class AppVersionsComboBoxActionListener implements\r\n\t\t\tActionListener\r\n\t{\r\n\t\tprivate QFixMessengerFrame frame;\r\n\r\n\t\tpublic AppVersionsComboBoxActionListener(QFixMessengerFrame frame)\r\n\t\t{\r\n\t\t\tthis.frame = frame;\r\n\t\t}\r\n\r\n\t\t@Override\r\n\t\tpublic void actionPerformed(ActionEvent e)\r\n\t\t{\r\n\t\t\tString appVersion = (String) frame.appVersionsComboBox\r\n\t\t\t\t\t.getSelectedItem();\r\n\t\t\ttry\r\n\t\t\t{\r\n\t\t\t\tString fixDictionaryLocation = frame.messenger.getConfig()\r\n\t\t\t\t\t\t.getFixDictionaryLocation(appVersion);\r\n\t\t\t\tframe.activeDictionary = frame.messenger.getParser().parse(\r\n\t\t\t\t\t\tgetClass().getResourceAsStream(fixDictionaryLocation));\r\n\t\t\t} catch (FixParsingException ex)\r\n\t\t\t{\r\n\t\t\t\tJOptionPane.showMessageDialog(frame, \"An error occured while\"\r\n\t\t\t\t\t\t+ \" parsing the FIX dictionary: \" + ex, \"Error\",\r\n\t\t\t\t\t\tJOptionPane.ERROR_MESSAGE);\r\n\t\t\t}\r\n\r\n\t\t\tif (logger.isDebugEnabled())\r\n\t\t\t{\r\n\t\t\t\tlogger.debug(\"Selected dictionary \" + frame.activeDictionary);\r\n\t\t\t}\r\n\t\t\tframe.loadMessagesList();\r\n\t\t}\r\n\t}\r\n\r\n\tprivate static class DestroyMessageActionListener implements ActionListener\r\n\t{\r\n\t\tprivate QFixMessengerFrame frame;\r\n\r\n\t\tprivate DestroyMessageActionListener(QFixMessengerFrame frame)\r\n\t\t{\r\n\t\t\tthis.frame = frame;\r\n\t\t}\r\n\r\n\t\t@Override\r\n\t\tpublic void actionPerformed(ActionEvent e)\r\n\t\t{\r\n\t\t\tint choice = JOptionPane.showConfirmDialog(frame,\r\n\t\t\t\t\t\"Clear all saved fields?\", \"Destroy Message?\",\r\n\t\t\t\t\tJOptionPane.YES_NO_OPTION);\r\n\t\t\tif (choice == JOptionPane.YES_OPTION)\r\n\t\t\t{\r\n\t\t\t\tframe.messagePanel = null;\r\n\t\t\t\tframe.getMemberPanelCache().clear();\r\n\t\t\t\tframe.displayMainPanel();\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tprivate static class ExportMessageActionListener implements ActionListener\r\n\t{\r\n\t\tprivate QFixMessengerFrame frame;\r\n\r\n\t\tpublic ExportMessageActionListener(QFixMessengerFrame frame)\r\n\t\t{\r\n\t\t\tthis.frame = frame;\r\n\t\t}\r\n\r\n\t\t@Override\r\n\t\tpublic void actionPerformed(ActionEvent e)\r\n\t\t{\r\n\t\t\tif (frame.activeMessage != null)\r\n\t\t\t{\r\n\t\t\t\tif (!frame.activeMessage.equals(frame.freeTextMessage))\r\n\t\t\t\t{\r\n\t\t\t\t\tMessageType xmlMessageType = frame.messagePanel\r\n\t\t\t\t\t\t\t.getXmlMember();\r\n\t\t\t\t\tframe.marshallXmlMessage(xmlMessageType);\r\n\t\t\t\t} else\r\n\t\t\t\t{\r\n\t\t\t\t\tJOptionPane.showMessageDialog(frame,\r\n\t\t\t\t\t\t\t\"Free text message cannot be exported!\", \"Error\",\r\n\t\t\t\t\t\t\tJOptionPane.WARNING_MESSAGE);\r\n\t\t\t\t}\r\n\t\t\t} else\r\n\t\t\t{\r\n\t\t\t\tJOptionPane.showMessageDialog(frame,\r\n\t\t\t\t\t\t\"Please create a message!\", \"Error\",\r\n\t\t\t\t\t\tJOptionPane.WARNING_MESSAGE);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tprivate static class FrameWindowAdapter extends WindowAdapter\r\n\t{\r\n\t\tprivate QFixMessengerFrame frame;\r\n\r\n\t\tpublic FrameWindowAdapter(QFixMessengerFrame frame)\r\n\t\t{\r\n\t\t\tthis.frame = frame;\r\n\t\t}\r\n\r\n\t\t@Override\r\n\t\tpublic void windowClosing(WindowEvent e)\r\n\t\t{\r\n\t\t\tframe.close();\r\n\t\t}\r\n\t}\r\n\r\n\tprivate static class MarshallMessageTypeWorker extends\r\n\t\t\tSwingWorker<Void, Void>\r\n\t{\r\n\t\tprivate final QFixMessengerFrame frame;\r\n\t\tprivate final MessageType xmlMessageType;\r\n\t\tprivate final File file;\r\n\r\n\t\tMarshallMessageTypeWorker(QFixMessengerFrame frame,\r\n\t\t\t\tMessageType xmlMessageType, File file)\r\n\t\t{\r\n\t\t\tthis.frame = frame;\r\n\t\t\tthis.xmlMessageType = xmlMessageType;\r\n\t\t\tthis.file = file;\r\n\t\t}\r\n\r\n\t\t@Override\r\n\t\tprotected Void doInBackground() throws Exception\r\n\t\t{\r\n\t\t\tJAXBElement<MessageType> rootElement = new JAXBElement<MessageType>(\r\n\t\t\t\t\tnew QName(\"http://xml.fix.jramoyo.com\", \"message\"),\r\n\t\t\t\t\tMessageType.class, xmlMessageType);\r\n\t\t\tMarshaller marshaller = frame.messenger.getJaxbContext()\r\n\t\t\t\t\t.createMarshaller();\r\n\t\t\tmarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,\r\n\t\t\t\t\tBoolean.TRUE);\r\n\t\t\tmarshaller.marshal(rootElement, file);\r\n\t\t\treturn null;\r\n\t\t}\r\n\r\n\t\tprotected void done()\r\n\t\t{\r\n\t\t\ttry\r\n\t\t\t{\r\n\t\t\t\tget();\r\n\t\t\t\tlogger.debug(\"Message exported to \" + file.getName());\r\n\t\t\t\tJOptionPane.showMessageDialog(frame, \"Message exported to \"\r\n\t\t\t\t\t\t+ file.getName(), \"Export\",\r\n\t\t\t\t\t\tJOptionPane.INFORMATION_MESSAGE);\r\n\t\t\t} catch (Exception ex)\r\n\t\t\t{\r\n\t\t\t\tlogger.error(\r\n\t\t\t\t\t\t\"A JAXBException occurred while exporting message.\", ex);\r\n\t\t\t\tJOptionPane.showMessageDialog(frame,\r\n\t\t\t\t\t\t\"An error occurred while exporting message!\", \"Error\",\r\n\t\t\t\t\t\tJOptionPane.ERROR_MESSAGE);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tprivate static class MarshallProjectTypeWorker extends\r\n\t\t\tSwingWorker<Void, Void>\r\n\t{\r\n\t\tprivate final QFixMessengerFrame frame;\r\n\t\tprivate final ProjectType xmlProjectType;\r\n\t\tprivate final File file;\r\n\r\n\t\tMarshallProjectTypeWorker(QFixMessengerFrame frame,\r\n\t\t\t\tProjectType xmlProjectType, File file)\r\n\t\t{\r\n\t\t\tthis.frame = frame;\r\n\t\t\tthis.xmlProjectType = xmlProjectType;\r\n\t\t\tthis.file = file;\r\n\t\t}\r\n\r\n\t\t@Override\r\n\t\tprotected Void doInBackground() throws Exception\r\n\t\t{\r\n\t\t\tJAXBElement<ProjectType> rootElement = new JAXBElement<ProjectType>(\r\n\t\t\t\t\tnew QName(\"http://xml.fix.jramoyo.com\", \"project\"),\r\n\t\t\t\t\tProjectType.class, xmlProjectType);\r\n\t\t\tMarshaller marshaller = frame.messenger.getJaxbContext()\r\n\t\t\t\t\t.createMarshaller();\r\n\t\t\tmarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,\r\n\t\t\t\t\tBoolean.TRUE);\r\n\t\t\tmarshaller.marshal(rootElement, file);\r\n\t\t\treturn null;\r\n\t\t}\r\n\r\n\t\tprotected void done()\r\n\t\t{\r\n\t\t\ttry\r\n\t\t\t{\r\n\t\t\t\tget();\r\n\t\t\t\tlogger.debug(\"Project saved to \" + file.getName());\r\n\t\t\t\tJOptionPane.showMessageDialog(frame,\r\n\t\t\t\t\t\t\"Project saved to \" + file.getName(), \"Export\",\r\n\t\t\t\t\t\tJOptionPane.INFORMATION_MESSAGE);\r\n\t\t\t} catch (Exception ex)\r\n\t\t\t{\r\n\t\t\t\tlogger.error(\r\n\t\t\t\t\t\t\"A JAXBException occurred while exporting message.\", ex);\r\n\t\t\t\tJOptionPane.showMessageDialog(frame,\r\n\t\t\t\t\t\t\"An error occurred while saving project!\", \"Error\",\r\n\t\t\t\t\t\tJOptionPane.ERROR_MESSAGE);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tprivate class RecentMessagesListMouseAdapter extends MouseAdapter\r\n\t{\r\n\t\tprivate QFixMessengerFrame frame;\r\n\r\n\t\tpublic RecentMessagesListMouseAdapter(QFixMessengerFrame frame)\r\n\t\t{\r\n\t\t\tthis.frame = frame;\r\n\t\t}\r\n\r\n\t\t@Override\r\n\t\tpublic void mouseClicked(MouseEvent e)\r\n\t\t{\r\n\t\t\tif (e.getClickCount() == 2)\r\n\t\t\t{\r\n\t\t\t\tint index = frame.recentMessagesList.locationToIndex(e\r\n\t\t\t\t\t\t.getPoint());\r\n\t\t\t\tif (index != -1)\r\n\t\t\t\t{\r\n\t\t\t\t\tMessage message = (Message) frame.recentMessagesList\r\n\t\t\t\t\t\t\t.getModel().getElementAt(index);\r\n\r\n\t\t\t\t\tMessage selectedMessage = (Message) frame.recentMessagesList\r\n\t\t\t\t\t\t\t.getSelectedValue();\r\n\t\t\t\t\tif (message == selectedMessage\r\n\t\t\t\t\t\t\t&& message.getCategory() != null)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\ttry\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tString url = frame.getMessenger().getConfig()\r\n\t\t\t\t\t\t\t\t\t.getFixWikiUrl()\r\n\t\t\t\t\t\t\t\t\t+ message.getName();\r\n\t\t\t\t\t\t\tjava.awt.Desktop.getDesktop().browse(\r\n\t\t\t\t\t\t\t\t\tjava.net.URI.create(url));\r\n\t\t\t\t\t\t} catch (IOException ex)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tJOptionPane.showMessageDialog(\r\n\t\t\t\t\t\t\t\t\tframe,\r\n\t\t\t\t\t\t\t\t\t\"An exception occured:\\n\"\r\n\t\t\t\t\t\t\t\t\t\t\t+ Arrays.toString(ex\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t.getStackTrace()), \"Error\",\r\n\t\t\t\t\t\t\t\t\tJOptionPane.ERROR_MESSAGE);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tprivate static class RecentMessagesListSelectionListener implements\r\n\t\t\tListSelectionListener\r\n\t{\r\n\t\tprivate QFixMessengerFrame frame;\r\n\r\n\t\tpublic RecentMessagesListSelectionListener(QFixMessengerFrame frame)\r\n\t\t{\r\n\t\t\tthis.frame = frame;\r\n\t\t}\r\n\r\n\t\t@Override\r\n\t\tpublic void valueChanged(ListSelectionEvent e)\r\n\t\t{\r\n\t\t\tif (!e.getValueIsAdjusting())\r\n\t\t\t{\r\n\t\t\t\tframe.activeMessage = (Message) frame.recentMessagesList\r\n\t\t\t\t\t\t.getSelectedValue();\r\n\r\n\t\t\t\tif (logger.isDebugEnabled())\r\n\t\t\t\t{\r\n\t\t\t\t\tlogger.debug(\"Selected message \" + frame.activeMessage);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tframe.requiredCheckBox.setSelected(true);\r\n\t\t\t\tframe.modifyHeaderCheckBox.setSelected(false);\r\n\t\t\t\tframe.modifyTrailerCheckBox.setSelected(false);\r\n\r\n\t\t\t\tframe.updateButtons();\r\n\t\t\t\tframe.displayMainPanel();\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tprivate class MessagesListMouseAdapter extends MouseAdapter\r\n\t{\r\n\t\tprivate QFixMessengerFrame frame;\r\n\r\n\t\tpublic MessagesListMouseAdapter(QFixMessengerFrame frame)\r\n\t\t{\r\n\t\t\tthis.frame = frame;\r\n\t\t}\r\n\r\n\t\t@Override\r\n\t\tpublic void mouseClicked(MouseEvent e)\r\n\t\t{\r\n\t\t\tif (e.getClickCount() == 2)\r\n\t\t\t{\r\n\t\t\t\tint index = frame.messagesList.locationToIndex(e.getPoint());\r\n\t\t\t\tMessage message = (Message) frame.messagesList.getModel()\r\n\t\t\t\t\t\t.getElementAt(index);\r\n\r\n\t\t\t\tMessage selectedMessage = (Message) frame.messagesList\r\n\t\t\t\t\t\t.getSelectedValue();\r\n\t\t\t\tif (message == selectedMessage && message.getCategory() != null)\r\n\t\t\t\t{\r\n\t\t\t\t\ttry\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tString url = frame.getMessenger().getConfig()\r\n\t\t\t\t\t\t\t\t.getFixWikiUrl()\r\n\t\t\t\t\t\t\t\t+ message.getName();\r\n\t\t\t\t\t\tjava.awt.Desktop.getDesktop().browse(\r\n\t\t\t\t\t\t\t\tjava.net.URI.create(url));\r\n\t\t\t\t\t} catch (IOException ex)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tJOptionPane.showMessageDialog(\r\n\t\t\t\t\t\t\t\tframe,\r\n\t\t\t\t\t\t\t\t\"An exception occured:\\n\"\r\n\t\t\t\t\t\t\t\t\t\t+ Arrays.toString(ex.getStackTrace()),\r\n\t\t\t\t\t\t\t\t\"Error\", JOptionPane.ERROR_MESSAGE);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tprivate static class MessagesListSelectionListener implements\r\n\t\t\tListSelectionListener\r\n\t{\r\n\t\tprivate QFixMessengerFrame frame;\r\n\r\n\t\tpublic MessagesListSelectionListener(QFixMessengerFrame frame)\r\n\t\t{\r\n\t\t\tthis.frame = frame;\r\n\t\t}\r\n\r\n\t\t@Override\r\n\t\tpublic void valueChanged(ListSelectionEvent e)\r\n\t\t{\r\n\t\t\tif (!e.getValueIsAdjusting())\r\n\t\t\t{\r\n\t\t\t\tframe.activeMessage = (Message) frame.messagesList\r\n\t\t\t\t\t\t.getSelectedValue();\r\n\r\n\t\t\t\tif (logger.isDebugEnabled())\r\n\t\t\t\t{\r\n\t\t\t\t\tlogger.debug(\"Selected message \" + frame.activeMessage);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tframe.requiredCheckBox.setSelected(true);\r\n\t\t\t\tframe.modifyHeaderCheckBox.setSelected(false);\r\n\t\t\t\tframe.modifyTrailerCheckBox.setSelected(false);\r\n\r\n\t\t\t\tframe.updateButtons();\r\n\t\t\t\tframe.displayMainPanel();\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tprivate class MessagesTableMouseListener extends MouseAdapter\r\n\t{\r\n\t\tprivate QFixMessengerFrame frame;\r\n\r\n\t\tpublic MessagesTableMouseListener(QFixMessengerFrame frame)\r\n\t\t{\r\n\t\t\tthis.frame = frame;\r\n\t\t}\r\n\r\n\t\t@Override\r\n\t\tpublic void mouseClicked(MouseEvent e)\r\n\t\t{\r\n\t\t\tif (e.getButton() == MouseEvent.BUTTON1)\r\n\t\t\t{\r\n\t\t\t\tif (e.getClickCount() == 2)\r\n\t\t\t\t{\r\n\t\t\t\t\tint viewRow = frame.messagesTable.rowAtPoint(e.getPoint());\r\n\t\t\t\t\tint modelRow = frame.messagesTable\r\n\t\t\t\t\t\t\t.convertRowIndexToModel(viewRow);\r\n\r\n\t\t\t\t\tMessagesTableModel model = (MessagesTableModel) frame.messagesTable\r\n\t\t\t\t\t\t\t.getModel();\r\n\t\t\t\t\tMessagesTableModelData data = model.getData(modelRow);\r\n\r\n\t\t\t\t\tJPanel panel = new JPanel();\r\n\t\t\t\t\tpanel.setLayout(new GridBagLayout());\r\n\t\t\t\t\tGridBagConstraints c = new GridBagConstraints();\r\n\t\t\t\t\tc.fill = GridBagConstraints.HORIZONTAL;\r\n\t\t\t\t\tc.weightx = 0.5;\r\n\t\t\t\t\tc.weighty = 0.0;\r\n\t\t\t\t\tc.ipadx = 2;\r\n\t\t\t\t\tc.ipady = 2;\r\n\r\n\t\t\t\t\tJLabel timeLabel = new JLabel(\r\n\t\t\t\t\t\t\t\"<html><b>Time Stamp:</b> <i><font color = 'blue'>\"\r\n\t\t\t\t\t\t\t\t\t+ data.getDate() + \"</font></i></html>\");\r\n\r\n\t\t\t\t\tc.gridx = 0;\r\n\t\t\t\t\tc.gridy = 3;\r\n\t\t\t\t\tpanel.add(Box.createRigidArea(new Dimension(50, 10)), c);\r\n\r\n\t\t\t\t\tJLabel directionLabel;\r\n\t\t\t\t\tif (data.getDirection().equals(QFixMessageListener.RECV))\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tdirectionLabel = new JLabel(\r\n\t\t\t\t\t\t\t\t\"<html><b>Direction:</b> <i><b><font color = '#FF8040'>\"\r\n\t\t\t\t\t\t\t\t\t\t+ data.getDirection()\r\n\t\t\t\t\t\t\t\t\t\t+ \"</font></b></i></html>\");\r\n\t\t\t\t\t} else\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tdirectionLabel = new JLabel(\r\n\t\t\t\t\t\t\t\t\"<html><b>Direction:</b> <i><b><font color = '#669900'>\"\r\n\t\t\t\t\t\t\t\t\t\t+ data.getDirection()\r\n\t\t\t\t\t\t\t\t\t\t+ \"</font></b></i></html>\");\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tJLabel sessionIdLabel = new JLabel(\r\n\t\t\t\t\t\t\t\"<html><b>Session ID:</b> <i><font color = 'blue'>\"\r\n\t\t\t\t\t\t\t\t\t+ data.getSessionName()\r\n\t\t\t\t\t\t\t\t\t+ \"</font></i></html>\");\r\n\r\n\t\t\t\t\tJLabel messageLabel = new JLabel(\r\n\t\t\t\t\t\t\t\"<html><b>Message:</b></html>\");\r\n\r\n\t\t\t\t\tc.gridx = 0;\r\n\t\t\t\t\tc.gridy = 0;\r\n\t\t\t\t\tpanel.add(timeLabel, c);\r\n\r\n\t\t\t\t\tc.gridx = 0;\r\n\t\t\t\t\tc.gridy = 1;\r\n\t\t\t\t\tpanel.add(directionLabel, c);\r\n\r\n\t\t\t\t\tc.gridx = 0;\r\n\t\t\t\t\tc.gridy = 2;\r\n\t\t\t\t\tpanel.add(sessionIdLabel, c);\r\n\r\n\t\t\t\t\tc.gridx = 0;\r\n\t\t\t\t\tc.gridy = 2;\r\n\t\t\t\t\tpanel.add(sessionIdLabel, c);\r\n\r\n\t\t\t\t\tc.gridx = 0;\r\n\t\t\t\t\tc.gridy = 4;\r\n\t\t\t\t\tpanel.add(messageLabel, c);\r\n\r\n\t\t\t\t\tJTextArea messageText = new JTextArea(data.getMessage(), 5,\r\n\t\t\t\t\t\t\t40);\r\n\t\t\t\t\tmessageText.setLineWrap(true);\r\n\t\t\t\t\tmessageText.setEditable(false);\r\n\r\n\t\t\t\t\tJScrollPane messageTextScrollPane = new JScrollPane(\r\n\t\t\t\t\t\t\tmessageText);\r\n\t\t\t\t\tmessageTextScrollPane.setBorder(new EtchedBorder());\r\n\r\n\t\t\t\t\tc.gridx = 0;\r\n\t\t\t\t\tc.gridy = 5;\r\n\t\t\t\t\tpanel.add(messageTextScrollPane, c);\r\n\r\n\t\t\t\t\tJOptionPane.showMessageDialog(frame, panel,\r\n\t\t\t\t\t\t\t\"MsgType(35) = \" + data.getMsgType(),\r\n\t\t\t\t\t\t\tJOptionPane.PLAIN_MESSAGE);\r\n\t\t\t\t}\r\n\t\t\t} else if (e.getButton() == MouseEvent.BUTTON3)\r\n\t\t\t{\r\n\t\t\t\tJPopupMenu popupMenu = new JPopupMenu();\r\n\r\n\t\t\t\tJMenuItem clearAllMenuItem = new JMenuItem(\"Clear All\");\r\n\t\t\t\tJMenuItem resendMenuItem = new JMenuItem(\"Resend\");\r\n\r\n\t\t\t\tclearAllMenuItem.setIcon(IconBuilder.build(getMessenger()\r\n\t\t\t\t\t\t.getConfig(), IconBuilder.CLEAR_ALL_ICON));\r\n\t\t\t\tclearAllMenuItem.addActionListener(new ActionListener()\r\n\t\t\t\t{\r\n\t\t\t\t\t@Override\r\n\t\t\t\t\tpublic void actionPerformed(ActionEvent e)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tMessagesTableModel model = (MessagesTableModel) frame.messagesTable\r\n\t\t\t\t\t\t\t\t.getModel();\r\n\t\t\t\t\t\tmodel.clear();\r\n\t\t\t\t\t}\r\n\t\t\t\t});\r\n\r\n\t\t\t\tresendMenuItem.setIcon(IconBuilder.build(getMessenger()\r\n\t\t\t\t\t\t.getConfig(), IconBuilder.SEND_SMALL_ICON));\r\n\t\t\t\tresendMenuItem\r\n\t\t\t\t\t\t.addActionListener(new ResendMessagesActionListener(\r\n\t\t\t\t\t\t\t\tframe, e));\r\n\r\n\t\t\t\tpopupMenu.add(clearAllMenuItem);\r\n\t\t\t\tpopupMenu.add(resendMenuItem);\r\n\t\t\t\tpopupMenu.show(frame.messagesTable, e.getX(), e.getY());\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tprivate class ResendMessagesActionListener implements ActionListener\r\n\t{\r\n\r\n\t\tprivate QFixMessengerFrame frame;\r\n\t\tprivate MouseEvent event;\r\n\t\tprivate Session session;\r\n\r\n\t\tpublic ResendMessagesActionListener(QFixMessengerFrame frame,\r\n\t\t\t\tMouseEvent event)\r\n\t\t{\r\n\t\t\tthis.frame = frame;\r\n\t\t\tthis.event = event;\r\n\t\t\tthis.session = frame.sessionsList.getSelectedValue();\r\n\t\t}\r\n\r\n\t\t@Override\r\n\t\tpublic void actionPerformed(ActionEvent e)\r\n\t\t{\r\n\t\t\tint viewRow = frame.messagesTable.rowAtPoint(event.getPoint());\r\n\t\t\tint modelRow = frame.messagesTable.convertRowIndexToModel(viewRow);\r\n\r\n\t\t\tquickfix.Message message = new quickfix.Message();\r\n\r\n\t\t\tMessagesTableModel model = (MessagesTableModel) frame.messagesTable\r\n\t\t\t\t\t.getModel();\r\n\t\t\tMessagesTableModelData data = model.getData(modelRow);\r\n\r\n\t\t\ttry\r\n\t\t\t{\r\n\t\t\t\tmessage.fromString(data.getMessage(),\r\n\t\t\t\t\t\tsession.getDataDictionary(), false);\r\n\t\t\t\tsession.send(message);\r\n\t\t\t} catch (InvalidMessage e1)\r\n\t\t\t{\r\n\t\t\t\t// TODO Auto-generated catch block\r\n\t\t\t\te1.printStackTrace();\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t}\r\n\r\n\tprivate static class ProjectWindowActionListener implements ActionListener\r\n\t{\r\n\t\tprivate QFixMessengerFrame frame;\r\n\r\n\t\tpublic ProjectWindowActionListener(QFixMessengerFrame frame)\r\n\t\t{\r\n\t\t\tthis.frame = frame;\r\n\t\t}\r\n\r\n\t\t@Override\r\n\t\tpublic void actionPerformed(ActionEvent e)\r\n\t\t{\r\n\t\t\tif (frame.activeXmlProject != null)\r\n\t\t\t{\r\n\t\t\t\tframe.launchProjectDialog();\r\n\t\t\t} else\r\n\t\t\t{\r\n\t\t\t\tJOptionPane.showMessageDialog(frame, \"No active project!\",\r\n\t\t\t\t\t\t\"Error\", JOptionPane.WARNING_MESSAGE);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tprivate static class LogfileWindowActionListener implements ActionListener\r\n\t{\r\n\t\tprivate QFixMessengerFrame frame;\r\n\r\n\t\tpublic LogfileWindowActionListener(QFixMessengerFrame frame)\r\n\t\t{\r\n\t\t\tthis.frame = frame;\r\n\t\t}\r\n\r\n\t\t@Override\r\n\t\tpublic void actionPerformed(ActionEvent e)\r\n\t\t{\r\n\t\t\tif (!frame.sessionsList.isSelectionEmpty())\r\n\t\t\t{\r\n\t\t\t\tframe.launchLogfileDialog();\r\n\t\t\t} else\r\n\t\t\t{\r\n\t\t\t\tJOptionPane.showMessageDialog(frame,\r\n\t\t\t\t\t\t\"Please select a session first!\", \"Error\",\r\n\t\t\t\t\t\tJOptionPane.WARNING_MESSAGE);\r\n\t\t\t}\r\n\r\n\t\t}\r\n\r\n\t}\r\n\r\n\tprivate static class SendActionListener implements ActionListener\r\n\t{\r\n\t\tprivate QFixMessengerFrame frame;\r\n\r\n\t\tpublic SendActionListener(QFixMessengerFrame frame)\r\n\t\t{\r\n\t\t\tthis.frame = frame;\r\n\t\t}\r\n\r\n\t\t@Override\r\n\t\tpublic void actionPerformed(ActionEvent e)\r\n\t\t{\r\n\t\t\tSession session = (Session) frame.sessionsList.getSelectedValue();\r\n\t\t\tif (session != null)\r\n\t\t\t{\r\n\t\t\t\tif (session.isLoggedOn())\r\n\t\t\t\t{\r\n\t\t\t\t\tif (frame.activeMessage != null)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tquickfix.Message message = null;\r\n\t\t\t\t\t\tif (!frame.activeMessage.equals(frame.freeTextMessage))\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tif (frame.messagePanel.hasValidFormat())\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tmessage = frame.messagePanel\r\n\t\t\t\t\t\t\t\t\t\t.getQuickFixMember();\r\n\t\t\t\t\t\t\t} else\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tint choice = JOptionPane\r\n\t\t\t\t\t\t\t\t\t\t.showConfirmDialog(\r\n\t\t\t\t\t\t\t\t\t\t\t\tframe,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"Some fields have format errors, send anyway?\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\"Format Errors\",\r\n\t\t\t\t\t\t\t\t\t\t\t\tJOptionPane.YES_NO_OPTION,\r\n\t\t\t\t\t\t\t\t\t\t\t\tJOptionPane.WARNING_MESSAGE);\r\n\t\t\t\t\t\t\t\tif (choice == JOptionPane.YES_OPTION)\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\tmessage = frame.messagePanel\r\n\t\t\t\t\t\t\t\t\t\t\t.getQuickFixMember();\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t} else\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tmessage = frame.freeTextMessagePanel\r\n\t\t\t\t\t\t\t\t\t.getQuickFixMember();\r\n\t\t\t\t\t\t}\r\n\r\n\t\t\t\t\t\tif (message != null)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tif (frame.isPreviewBeforeSend)\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tJTextArea messageText = new JTextArea(\r\n\t\t\t\t\t\t\t\t\t\tmessage.toString(), 5, 40);\r\n\t\t\t\t\t\t\t\tmessageText.setLineWrap(true);\r\n\t\t\t\t\t\t\t\tmessageText.setEditable(false);\r\n\r\n\t\t\t\t\t\t\t\tJScrollPane messageTextScrollPane = new JScrollPane(\r\n\t\t\t\t\t\t\t\t\t\tmessageText);\r\n\t\t\t\t\t\t\t\tmessageTextScrollPane\r\n\t\t\t\t\t\t\t\t\t\t.setBorder(new EtchedBorder());\r\n\r\n\t\t\t\t\t\t\t\tint choice = JOptionPane.showConfirmDialog(\r\n\t\t\t\t\t\t\t\t\t\tframe, messageTextScrollPane,\r\n\t\t\t\t\t\t\t\t\t\t\"Send Message?\",\r\n\t\t\t\t\t\t\t\t\t\tJOptionPane.YES_NO_OPTION,\r\n\t\t\t\t\t\t\t\t\t\tJOptionPane.PLAIN_MESSAGE);\r\n\t\t\t\t\t\t\t\tif (choice == JOptionPane.YES_OPTION)\r\n\t\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\t\tlogger.info(\"Sending message \"\r\n\t\t\t\t\t\t\t\t\t\t\t+ message.toString());\r\n\t\t\t\t\t\t\t\t\tsession.send(message);\r\n\t\t\t\t\t\t\t\t\tupdateRecentList(frame.activeMessage);\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t} else\r\n\t\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\t\tlogger.info(\"Sending message \"\r\n\t\t\t\t\t\t\t\t\t\t+ message.toString());\r\n\t\t\t\t\t\t\t\tframe.getMessenger().sendQFixMessage(message,\r\n\t\t\t\t\t\t\t\t\t\tsession);\r\n\t\t\t\t\t\t\t\tupdateRecentList(frame.activeMessage);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t} else\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tJOptionPane.showMessageDialog(frame,\r\n\t\t\t\t\t\t\t\t\"Please create a message!\", \"Error\",\r\n\t\t\t\t\t\t\t\tJOptionPane.WARNING_MESSAGE);\r\n\t\t\t\t\t}\r\n\t\t\t\t} else\r\n\t\t\t\t{\r\n\t\t\t\t\tJOptionPane.showMessageDialog(frame,\r\n\t\t\t\t\t\t\tQFixUtil.getSessionName(session.getSessionID())\r\n\t\t\t\t\t\t\t\t\t+ \" is not logged on!\", \"Error\",\r\n\t\t\t\t\t\t\tJOptionPane.WARNING_MESSAGE);\r\n\t\t\t\t}\r\n\t\t\t} else\r\n\t\t\t{\r\n\t\t\t\tJOptionPane.showMessageDialog(frame,\r\n\t\t\t\t\t\t\"Please create a message!\", \"Error\",\r\n\t\t\t\t\t\tJOptionPane.WARNING_MESSAGE);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t// Get Message from ActiveMessage rather than recent list or message\r\n\t\t// list\r\n\t\tpublic void updateRecentList(Message recentMsg)\r\n\t\t{\r\n\t\t\tif (\"Free Text\".equals(recentMsg.getName()))\r\n\t\t\t{\r\n\t\t\t\treturn;\r\n\t\t\t}\r\n\r\n\t\t\tString key = frame.activeDictionary.getFullVersion();\r\n\t\t\tMap<String, DefaultListModel<Message>> tmpMap = frame.recentMessagesMap;\r\n\t\t\tDefaultListModel<Message> tmpListModel;\r\n\r\n\t\t\tif (tmpMap.containsKey(key))\r\n\t\t\t{\r\n\t\t\t\ttmpListModel = tmpMap.get(key);\r\n\t\t\t\tif (tmpListModel.contains(recentMsg))\r\n\t\t\t\t{\r\n\t\t\t\t\ttmpListModel.remove(tmpListModel.indexOf(recentMsg));\r\n\t\t\t\t\ttmpListModel.add(0, recentMsg);\r\n\t\t\t\t} else\r\n\t\t\t\t{\r\n\t\t\t\t\ttmpListModel.add(0, recentMsg);\r\n\t\t\t\t}\r\n\t\t\t} else\r\n\t\t\t{\r\n\t\t\t\ttmpListModel = new DefaultListModel<Message>();\r\n\t\t\t\ttmpListModel.add(0, recentMsg);\r\n\t\t\t\ttmpMap.put(key, tmpListModel);\r\n\t\t\t}\r\n\r\n\t\t\tframe.recentMessagesList.setModel(tmpMap.get(key));\r\n\t\t}\r\n\t}\r\n\r\n\tprivate class SessionsListMouseAdapter extends MouseAdapter\r\n\t{\r\n\t\tprivate QFixMessengerFrame frame;\r\n\r\n\t\tpublic SessionsListMouseAdapter(QFixMessengerFrame frame)\r\n\t\t{\r\n\t\t\tthis.frame = frame;\r\n\t\t}\r\n\r\n\t\t@Override\r\n\t\tpublic void mouseClicked(MouseEvent e)\r\n\t\t{\r\n\t\t\tif (e.getButton() == MouseEvent.BUTTON3)\r\n\t\t\t{\r\n\t\t\t\tint index = frame.sessionsList.locationToIndex(e.getPoint());\r\n\t\t\t\tSession session = (Session) frame.sessionsList.getModel()\r\n\t\t\t\t\t\t.getElementAt(index);\r\n\r\n\t\t\t\tSession selectedSession = (Session) frame.sessionsList\r\n\t\t\t\t\t\t.getSelectedValue();\r\n\t\t\t\tif (session == selectedSession)\r\n\t\t\t\t{\r\n\t\t\t\t\tJPopupMenu sessionMenuPopup;\r\n\t\t\t\t\tJCheckBoxMenuItem logonMenuItem;\r\n\t\t\t\t\tJMenuItem resetMenuItem;\r\n\t\t\t\t\tJMenuItem statusMenuItem;\r\n\r\n\t\t\t\t\tsessionMenuPopup = new JPopupMenu();\r\n\r\n\t\t\t\t\tlogonMenuItem = new JCheckBoxMenuItem(\"Logon\");\r\n\t\t\t\t\tlogonMenuItem.addItemListener(new LogonSessionItemListener(\r\n\t\t\t\t\t\t\tsession));\r\n\t\t\t\t\tif (session.isLoggedOn())\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tlogonMenuItem.setSelected(true);\r\n\t\t\t\t\t} else\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tlogonMenuItem.setSelected(false);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tsession.addStateListener(new LogonSessionMenuItemSessionStateListener(\r\n\t\t\t\t\t\t\tlogonMenuItem));\r\n\r\n\t\t\t\t\tresetMenuItem = new JMenuItem(\"Reset\");\r\n\t\t\t\t\tresetMenuItem\r\n\t\t\t\t\t\t\t.addActionListener(new ResetSessionActionListener(\r\n\t\t\t\t\t\t\t\t\tframe, session));\r\n\r\n\t\t\t\t\tstatusMenuItem = new JMenuItem(\"Status\");\r\n\t\t\t\t\tstatusMenuItem\r\n\t\t\t\t\t\t\t.addActionListener(new SessionStatusActionListener(\r\n\t\t\t\t\t\t\t\t\tframe, session));\r\n\r\n\t\t\t\t\tsessionMenuPopup.add(logonMenuItem);\r\n\t\t\t\t\tsessionMenuPopup.add(resetMenuItem);\r\n\t\t\t\t\tsessionMenuPopup.add(statusMenuItem);\r\n\r\n\t\t\t\t\tsessionMenuPopup.show(frame.sessionsList, e.getX(),\r\n\t\t\t\t\t\t\te.getY());\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tprivate static class SessionsListSelectionListener implements\r\n\t\t\tListSelectionListener\r\n\t{\r\n\t\tprivate QFixMessengerFrame frame;\r\n\r\n\t\tpublic SessionsListSelectionListener(QFixMessengerFrame frame)\r\n\t\t{\r\n\t\t\tthis.frame = frame;\r\n\t\t}\r\n\r\n\t\t@Override\r\n\t\tpublic void valueChanged(ListSelectionEvent e)\r\n\t\t{\r\n\t\t\tif (!e.getValueIsAdjusting())\r\n\t\t\t{\r\n\t\t\t\tSession session = (Session) frame.sessionsList\r\n\t\t\t\t\t\t.getSelectedValue();\r\n\t\t\t\tSessionID sessionId = session.getSessionID();\r\n\r\n\t\t\t\tif (sessionId.getBeginString().equals(\r\n\t\t\t\t\t\tQFixMessengerConstants.BEGIN_STRING_FIXT11))\r\n\t\t\t\t{\r\n\t\t\t\t\tframe.appVersionsComboBox.setEnabled(true);\r\n\t\t\t\t\tframe.activeDictionary = null;\r\n\t\t\t\t\tframe.isFixTSession = true;\r\n\t\t\t\t} else\r\n\t\t\t\t{\r\n\t\t\t\t\tframe.appVersionsComboBox.setEnabled(false);\r\n\t\t\t\t\tframe.isFixTSession = false;\r\n\r\n\t\t\t\t\ttry\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tFixDictionaryParser parser = frame.messenger\r\n\t\t\t\t\t\t\t\t.getParser();\r\n\t\t\t\t\t\tString fixDictionaryLocation = frame.messenger\r\n\t\t\t\t\t\t\t\t.getConfig().getFixDictionaryLocation(\r\n\t\t\t\t\t\t\t\t\t\tsessionId.getBeginString());\r\n\t\t\t\t\t\tframe.activeDictionary = parser.parse(getClass()\r\n\t\t\t\t\t\t\t\t.getResourceAsStream(fixDictionaryLocation));\r\n\t\t\t\t\t} catch (FixParsingException ex)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tJOptionPane.showMessageDialog(frame,\r\n\t\t\t\t\t\t\t\t\"An error occured while\"\r\n\t\t\t\t\t\t\t\t\t\t+ \" parsing the FIX dictionary: \" + ex,\r\n\t\t\t\t\t\t\t\t\"Error\", JOptionPane.ERROR_MESSAGE);\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (logger.isDebugEnabled())\r\n\t\t\t\t{\r\n\t\t\t\t\tlogger.debug(\"Selected dictionary \"\r\n\t\t\t\t\t\t\t+ frame.activeDictionary);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tframe.activeMessage = null;\r\n\t\t\t\tframe.updateButtons();\r\n\t\t\t\tframe.displayMainPanel();\r\n\t\t\t\tframe.loadMessagesList();\r\n\t\t\t\tframe.updateLogFile(sessionId.getBeginString());\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n}\r"
] | import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import quickfix.ConfigError;
import quickfix.Connector;
import quickfix.DefaultMessageFactory;
import quickfix.FileLogFactory;
import quickfix.FileStoreFactory;
import quickfix.Group;
import quickfix.LogFactory;
import quickfix.Message;
import quickfix.MessageFactory;
import quickfix.MessageStoreFactory;
import quickfix.Session;
import quickfix.SessionID;
import quickfix.SessionSettings;
import quickfix.SocketAcceptor;
import quickfix.SocketInitiator;
import quickfix.StringField;
import quickfix.field.ApplVerID;
import com.jramoyo.fix.model.parser.FixDictionaryParser;
import com.jramoyo.fix.xml.BodyType;
import com.jramoyo.fix.xml.ComponentType;
import com.jramoyo.fix.xml.FieldType;
import com.jramoyo.fix.xml.GroupType;
import com.jramoyo.fix.xml.GroupsType;
import com.jramoyo.fix.xml.HeaderType;
import com.jramoyo.fix.xml.MessageType;
import com.jramoyo.fix.xml.TrailerType;
import com.jramoyo.qfixmessenger.config.QFixMessengerConfig;
import com.jramoyo.qfixmessenger.quickfix.ComponentHelper;
import com.jramoyo.qfixmessenger.quickfix.QFixMessengerApplication;
import com.jramoyo.qfixmessenger.quickfix.parser.QFixDictionaryParser;
import com.jramoyo.qfixmessenger.quickfix.util.QFixUtil;
import com.jramoyo.qfixmessenger.ui.QFixMessengerFrame;
| /*
* Copyright (c) 2011, Jan Amoyo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
* THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
* QFixMessenger.java
* 6 Jun 2011
*/
package com.jramoyo.qfixmessenger;
/**
* QuickFIX Messenger main application
*
* @author jamoyo
*/
public class QFixMessenger
{
private static final Logger logger = LoggerFactory
.getLogger(QFixMessenger.class);
private static final CountDownLatch shutdownLatch = new CountDownLatch(1);
public static void main(String[] args) throws Exception
{
Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler()
{
@Override
public void uncaughtException(Thread t, Throwable ex)
{
logger.error("An unexpected exception occured!", ex);
}
});
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
setLookAndFeel();
}
});
if (args.length == 2)
{
InputStream inputStream = null;
String configFileName = args[0];
try
{
inputStream = new FileInputStream(args[1]);
} catch (FileNotFoundException ex)
{
logger.error("File not found: " + args[1]);
logger.error("Quitting...");
System.err.println("File not found: " + args[1]);
System.err.println("Quitting...");
System.exit(0);
}
if (inputStream != null)
{
try
{
SessionSettings settings = new SessionSettings(inputStream);
inputStream.close();
QFixMessenger messenger = new QFixMessenger(configFileName,
settings);
messenger.logon();
| QFixMessengerFrame.launch(messenger);
| 6 |
R2RML-api/R2RML-api | r2rml-api-rdf4j-binding/src/test/java/rdf4jTest/InMemoryStructureCreation1_Test.java | [
"public class RDF4JR2RMLMappingManager extends R2RMLMappingManagerImpl {\n\n private static RDF4JR2RMLMappingManager INSTANCE = new RDF4JR2RMLMappingManager(new RDF4J());\n\n private RDF4JR2RMLMappingManager(RDF4J rdf) {\n super(rdf);\n }\n\n public Collection<TriplesMap> importMappings(Model model) throws InvalidR2RMLMappingException {\n return importMappings(((RDF4J) getRDF()).asGraph(model));\n }\n\n @Override\n public RDF4JGraph exportMappings(Collection<TriplesMap> maps) {\n return (RDF4JGraph) super.exportMappings(maps);\n }\n\n public static RDF4JR2RMLMappingManager getInstance(){\n return INSTANCE;\n }\n}",
"@W3C_R2RML_Recommendation(R2RMLVocabulary.TYPE_LOGICAL_TABLE)\r\npublic interface LogicalTable extends MappingComponent {\r\n\r\n\t/**\r\n\t * Returns the effective SQL query of this LogicalTable. The effective SQL\r\n\t * query of a R2RMLView is it's own SQL query. For a SQLBaseTableOrView it's\r\n\t * \"SELECT * FROM {table}\".\r\n\t * \r\n\t * @return The effective SQL query of this LogicalTable.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_SQL_QUERY)\r\n\tpublic String getSQLQuery();\r\n\r\n}\r",
"public interface MappingFactory {\r\n\r\n /**\r\n * Create a new TriplesMap with the given LogicalTable and SubjectMap.\r\n *\r\n * @param lt The LogicalTable of the TriplesMap. This must either be a\r\n * SQLBaseTableOrView or a R2RMLView.\r\n * @param sm The SubjectMap of the TriplesMap.\r\n * @return The created TriplesMap.\r\n */\r\n TriplesMap createTriplesMap(LogicalTable lt, SubjectMap sm);\r\n\r\n TriplesMap createTriplesMap(LogicalTable lt, SubjectMap sm, BlankNodeOrIRI node);\r\n\r\n /**\r\n * Create a new TriplesMap with the given LogicalTable, SubjectMap and\r\n * PredicateObjectMap.\r\n *\r\n * @param lt The LogicalTable of the TriplesMap. This must either be a\r\n * SQLBaseTableOrView or a R2RMLView.\r\n * @param sm The SubjectMap of the TriplesMap.\r\n * @param pom A PredicateObjectMap for the TriplesMap.\r\n * @return The created TriplesMap.\r\n */\r\n TriplesMap createTriplesMap(LogicalTable lt, SubjectMap sm, PredicateObjectMap pom);\r\n\r\n TriplesMap createTriplesMap(LogicalTable lt, SubjectMap sm, PredicateObjectMap pom, BlankNodeOrIRI node);\r\n\r\n /**\r\n * Create a new TriplesMap with the given LogicalTable, SubjectMap and list\r\n * of PredicateObjectMaps.\r\n *\r\n * @param lt The LogicalTable of the TriplesMap. This must either be a\r\n * SQLBaseTableOrView or a R2RMLView.\r\n * @param sm The SubjectMap of the TriplesMap.\r\n * @param listOfPom The list of PredicateObjectMaps that will be added to the\r\n * TriplesMap.\r\n * @return The created TriplesMap.\r\n */\r\n TriplesMap createTriplesMap(LogicalTable lt, SubjectMap sm, List<PredicateObjectMap> listOfPom);\r\n\r\n /**\r\n * Create a new PredicateObjectMap with the given PredicateMap and\r\n * ObjectMap.\r\n *\r\n * @param pm The PredicateMap for the PredicateObjectMap.\r\n * @param om The ObjectMap for the PredicateObjectMap.\r\n * @return The created PredicateObjectMap.\r\n */\r\n PredicateObjectMap createPredicateObjectMap(PredicateMap pm, ObjectMap om);\r\n\r\n /**\r\n * Create a new PredicateObjectMap with the given PredicateMap and\r\n * RefObjectMap.\r\n *\r\n * @param pm The PredicateMap for the PredicateObjectMap.\r\n * @param rom The RefObjectMap for the PredicateObjectMap.\r\n * @return The created PredicateObjectMap.\r\n */\r\n PredicateObjectMap createPredicateObjectMap(PredicateMap pm, RefObjectMap rom);\r\n\r\n /**\r\n * Creates a new PredicateObjectMap with the given lists of PredicateMaps,\r\n * ObjectMaps and RefObjectMaps. The lists must contain at least one\r\n * PredicateMap and at least one of either an ObjectMap or a RefObjectMap.\r\n *\r\n * @param pms The list of PredicateMaps.\r\n * @param oms The list of ObjectMaps.\r\n * @param roms The list of RefObjectMaps.\r\n * @return The created PredicateObjectMap.\r\n */\r\n PredicateObjectMap createPredicateObjectMap(List<PredicateMap> pms,\r\n List<ObjectMap> oms, List<RefObjectMap> roms);\r\n\r\n /**\r\n * Create a new R2RMLView with the given SQL query.\r\n *\r\n * @param query The SQL query for the R2RMLView.\r\n * @return The created R2RMLView.\r\n */\r\n R2RMLView createR2RMLView(String query);\r\n\r\n /**\r\n * Create a new SQLBaseTableOrView with the given table name.\r\n *\r\n * @param tableName The table name for the SQLBaseTableOrView.\r\n * @return The created SQLBaseTableOrView.\r\n */\r\n SQLBaseTableOrView createSQLBaseTableOrView(String tableName);\r\n\r\n /**\r\n * Create a new GraphMap with the given template. The term map type of the\r\n * GraphMap will be set to TermMapType.TEMPLATE_VALUED.\r\n *\r\n * @param template The template for the GraphMap.\r\n * @return The created GraphMap.\r\n */\r\n GraphMap createGraphMap(Template template);\r\n\r\n /**\r\n * Create a new GraphMap with the given term map type and a column or\r\n * constant value. The term map type of the GraphMap will be set to\r\n * TermMapType.COLUMN_VALUED.\r\n *\r\n * @param columnName The value for the GraphMap.\r\n * @return The created GraphMap.\r\n */\r\n GraphMap createGraphMap(String columnName);\r\n\r\n /**\r\n * Create a new GraphMap with the given term map type and a column or\r\n * constant value. The term map type of the GraphMap will be set to\r\n * TermMapType.CONSTANT_VALUED .\r\n *\r\n * @param constant The value for the GraphMap.\r\n * @return The created GraphMap.\r\n */\r\n GraphMap createGraphMap(IRI constant);\r\n\r\n /**\r\n * Create a new SubjectMap with the given template. The term map type of the\r\n * SubjectMap will be set to TermMapType.TEMPLATE_VALUED.\r\n *\r\n * @param template The template for the SubjectMap.\r\n * @return The created SubjectMap.\r\n */\r\n SubjectMap createSubjectMap(Template template);\r\n\r\n /**\r\n * Create a new SubjectMap with the given term map type and a column or\r\n * constant value. The term map type of the SubjectMap will be set to TermMapType.COLUMN_VALUED.\r\n *\r\n * @param columnName The value for the SubjectMap.\r\n * @return The created SubjectMap.\r\n */\r\n SubjectMap createSubjectMap(String columnName);\r\n\r\n /**\r\n * Create a new SubjectMap with the given term map type and a column or\r\n * constant value. The term map type of the SubjectMap will be set to\r\n * TermMapType.CONSTANT_VALUED.\r\n *\r\n * @param constant The value for the SubjectMap.\r\n * @return The created SubjectMap.\r\n */\r\n SubjectMap createSubjectMap(IRI constant);\r\n\r\n /**\r\n * Create a new SubjectMap containing an embedded triple, the embedded\r\n * triple consists of three embedded term maps which are passed to the\r\n * constructor. The term map type of the SubjectMap will be set to\r\n * TermMapType.RDF_STAR_VALUED.\r\n *\r\n * @param subject The embedded subject.\r\n * @param predicate The embedded predicate.\r\n * @param object The embedded object.\r\n * @return The created SubjectMap.\r\n */\r\n SubjectMap createSubjectMap(ObjectMap subject, PredicateMap predicate, ObjectMap object);\r\n\r\n /**\r\n * Create a new PredicateMap with the given template. The term map type of\r\n * the PredicateMap will be set to TermMapType.TEMPLATE_VALUED.\r\n *\r\n * @param template The template for the PredicateMap.\r\n * @return The created PredicateMap.\r\n */\r\n PredicateMap createPredicateMap(Template template);\r\n\r\n /**\r\n * Create a new PredicateMap with the given term map type and a column or\r\n * constant value. The term map type of the PredicateMap will be set to TermMapType.COLUMN_VALUED.\r\n *\r\n * @param columnName The value for the PredicateMap.\r\n * @return The created PredicateMap.\r\n */\r\n PredicateMap createPredicateMap(String columnName);\r\n\r\n /**\r\n * Create a new PredicateMap with the given term map type and a column or\r\n * constant value. The term map type of the PredicateMap will be set to\r\n * TermMapType.CONSTANT_VALUED.\r\n *\r\n * @param constant The value for the PredicateMap.\r\n * @return The created PredicateMap.\r\n */\r\n PredicateMap createPredicateMap(IRI constant);\r\n\r\n /**\r\n * Create a new ObjectMap with the given template. The term map type of the\r\n * ObjectMap will be set to TermMapType.TEMPLATE_VALUED.\r\n *\r\n * @param template The template for the ObjectMap.\r\n * @return The created ObjectMap.\r\n */\r\n ObjectMap createObjectMap(Template template);\r\n\r\n /**\r\n * Create a new ObjectMap with the given term map type and a column or\r\n * constant value. The term map type of the ObjectMap will be set to TermMapType.COLUMN_VALUED.\r\n * TermMapType.CONSTANT_VALUED or TermMapType.COLUMN_VALUED.\r\n *\r\n * @param columnName The value for the ObjectMap.\r\n * @return The created ObjectMap.\r\n */\r\n ObjectMap createObjectMap(String columnName);\r\n\r\n /**\r\n * Create a new ObjectMap with the given term map type and a column or\r\n * constant value. The term map type of the ObjectMap will be set to TermMapType.CONSTANT_VALUED.\r\n *\r\n * @param constant The value for the ObjectMap.\r\n * @return The created ObjectMap.\r\n */\r\n ObjectMap createObjectMap(RDFTerm constant);\r\n\r\n /**\r\n * Create a new ObjectMap containing an embedded triple, the embedded\r\n * triple consists of three embedded term maps which are passed to the\r\n * constructor. The term map type of the SubjectMap will be set to\r\n * TermMapType.RDF_STAR_VALUED.\r\n *\r\n * @param subject The embedded subject.\r\n * @param predicate The embedded predicate.\r\n * @param object The embedded object.\r\n * @return The created ObjectMap.\r\n */\r\n ObjectMap createObjectMap(ObjectMap subject, PredicateMap predicate, ObjectMap object);\r\n\r\n /**\r\n * Create a new RefObjectMap with the given resource for the parent triples\r\n * map.\r\n *\r\n * @param parentMap The parent triples map for the RefObjectMap.\r\n * @return The created RefObjectMap.\r\n */\r\n RefObjectMap createRefObjectMap(TriplesMap parentMap);\r\n\r\n /**\r\n * Create a new Join with the given child and parent columns.\r\n *\r\n * @param childColumn The child column of the Join.\r\n * @param parentColumn The parent column of the Join.\r\n * @return The created Join.\r\n */\r\n Join createJoinCondition(String childColumn, String parentColumn);\r\n\r\n /**\r\n * Create a new template.\r\n *\r\n * @return The created template.\r\n */\r\n Template createTemplate();\r\n\r\n /**\r\n * Create a new template given a template string.\r\n *\r\n * @param template The template as a string.\r\n * @return The created template.\r\n */\r\n Template createTemplate(String template);\r\n\r\n /**\r\n * Create a new InverseExpression with the given string template.\r\n *\r\n * @param invExp The string template for the inverse expression.\r\n * @return The created InverseExpression.\r\n */\r\n InverseExpression createInverseExpression(String invExp);\r\n}\r",
"@W3C_R2RML_Recommendation(R2RMLVocabulary.TYPE_OBJECT_MAP)\r\npublic interface ObjectMap extends TermMap {\r\n\r\n /**\r\n * {@inheritDoc}\r\n *\r\n * The possible values for the term type are:<br>\r\n * - rr:IRI<br>\r\n * - rr:BlankNode<br>\r\n * - rr:Literal\r\n *\r\n */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_TERM_TYPE)\r\n @Override\r\n void setTermType(IRI typeIRI);\r\n\r\n /**\r\n\t * Set the language tag of this ObjectMap if the term type is set to\r\n\t * rr:Literal. If the ObjectMap is data typed, the data type will be\r\n\t * removed.\r\n\t * \r\n\t * @param lang\r\n\t * The language tag to be set. Must be a valid language tag.\r\n\t * @throws IllegalStateException\r\n\t * If the term type of this ObjectMap is not rr:Literal.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_LANGUAGE)\r\n public void setLanguageTag(String lang);\r\n\r\n\t/**\r\n\t * Set the data type for this ObjectMap. A ObjectMap can have either zero or\r\n\t * one data types. The ObjectMap can only be data typed if the term type is\r\n\t * rr:Literal. If the ObjectMap has a language tag, the language tag will be\r\n\t * removed. The datatypeURI parameter must be an instance of the library's\r\n\t * resource class.\r\n\t * \r\n\t * @param datatypeURI\r\n\t * The data type IRI to be set.\r\n\t * @throws IllegalStateException\r\n\t * If the term type of this ObjectMap is not rr:Literal.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_DATATYPE)\r\n\tpublic void setDatatype(IRI datatypeURI);\r\n\r\n\t/**\r\n\t * Get the language tag for this ObjectMap. It will return null if the\r\n\t * ObjectMap doesn't have a language tag.\r\n\t * \r\n\t * @return The language tag of this ObjectMap.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_LANGUAGE)\r\n\tpublic String getLanguageTag();\r\n\r\n\t/**\r\n\t * Get the data type for this ObjectMap. It will return null if the\r\n\t * ObjectMap is not data typed.\r\n\t *\r\n\t * @return The data type of this ObjectMap.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_DATATYPE)\r\n public IRI getDatatype();\r\n\r\n\t/**\r\n\t * Remove the data type associated with this ObjectMap. The ObjectMap will\r\n\t * no longer be data typed.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_DATATYPE)\r\n\tpublic void removeDatatype();\r\n\r\n\t/**\r\n\t * Removes the language tag from this ObjectMap if there is one.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_LANGUAGE)\r\n\tpublic void removeLanguageTag();\r\n\r\n}\r",
"@W3C_R2RML_Recommendation(R2RMLVocabulary.TYPE_PREDICATE_MAP)\r\npublic interface PredicateMap extends TermMap {\r\n\r\n}\r",
"@W3C_R2RML_Recommendation(R2RMLVocabulary.TYPE_PREDICATE_OBJECT_MAP)\r\npublic interface PredicateObjectMap extends MappingComponent {\r\n\r\n\t/**\r\n\t * Adds a PredicateMap to this PredicateObjectMap. The PredicateMap will be\r\n\t * added to the end of the PredicateMap list. A PredicateObjectMap must have\r\n\t * one or more PredicateMaps.\r\n\t * \r\n\t * @param pm\r\n\t * The PredicateMap that will be added.\r\n\t */\r\n\t@W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_PREDICATE_MAP)\r\n\tpublic void addPredicateMap(PredicateMap pm);\r\n\r\n\t/**\r\n\t * Adds an ObjectMap to this PredicateObjectMap. The ObjectMap will be added\r\n\t * to the end of the ObjectMap list. A PredicateObjectMap must have at least\r\n\t * one ObjectMap or RefObjectMap.\r\n\t * \r\n\t * @param om\r\n\t * The ObjectMap that will be added.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_OBJECT_MAP)\r\n\tpublic void addObjectMap(ObjectMap om);\r\n\r\n\t/**\r\n\t * Adds an RefObjectMap to this PredicateObjectMap. The RefObjectMap will be\r\n\t * added to the end of the RefObjectMap list. A PredicateObjectMap must have\r\n\t * at least one ObjectMap or RefObjectMap.\r\n\t * \r\n\t * @param rom\r\n\t * The RefObjectMap that will be added.\r\n\t */\r\n\t@W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_OBJECT_MAP)\r\n\tpublic void addRefObjectMap(RefObjectMap rom);\r\n\r\n\t/**\r\n\t * Adds a GraphMap to this PredicateObjectMap. A PredicateObjectMap can have\r\n\t * zero or more GraphMaps. The GraphMap will be added to the end of the\r\n\t * GraphMap list.\r\n\t * \r\n\t * @param gm\r\n\t * The GraphMap that will be added.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_GRAPH_MAP)\r\n\tpublic void addGraphMap(GraphMap gm);\r\n\r\n\t/**\r\n\t * Adds a list of GraphMaps to this PredicateObjectMap. A PredicateObjectMap\r\n\t * can have zero or more GraphMaps. The GraphMaps will be added to the end\r\n\t * of the GraphMap list.\r\n\t * \r\n\t * @param gms\r\n\t * The list of GraphMaps that will be added.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_GRAPH_MAP)\r\n public void addGraphMaps(List<GraphMap> gms);\r\n\r\n\t/**\r\n\t * Get the GraphMap located at the given index.\r\n\t * \r\n\t * @param index\r\n\t * The index of the GraphMap.\r\n\t * @return The GraphMap located at the given index.\r\n\t * @throws IndexOutOfBoundsException\r\n\t * If the given index is out of range.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_GRAPH_MAP)\r\n\tpublic GraphMap getGraphMap(int index);\r\n\r\n\t/**\r\n\t * Get the RefObjectMap located at the given index.\r\n\t * \r\n\t * @param index\r\n\t * The index of the RefObjectMap.\r\n\t * @return The RefObjectMap located at the given index.\r\n\t * @throws IndexOutOfBoundsException\r\n\t * If the given index is out of range.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_OBJECT_MAP)\r\n public RefObjectMap getRefObjectMap(int index);\r\n\r\n\t/**\r\n\t * Get the ObjectMap located at the given index.\r\n\t * \r\n\t * @param index\r\n\t * The index of the ObjectMap.\r\n\t * @return The ObjectMap located at the given index.\r\n\t * @throws IndexOutOfBoundsException\r\n\t * If the given index is out of range.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_OBJECT_MAP)\r\n public ObjectMap getObjectMap(int index);\r\n\r\n\t/**\r\n\t * Get the PredicateMap located at the given index.\r\n\t * \r\n\t * @param index\r\n\t * The index of the PredicateMap.\r\n\t * @return The PredicateMap located at the given index.\r\n\t * @throws IndexOutOfBoundsException\r\n\t * If the given index is out of range.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_PREDICATE_MAP)\r\n public PredicateMap getPredicateMap(int index);\r\n\r\n\t/**\r\n\t * Returns an unmodifiable view of the list of GraphMaps that have been\r\n\t * added to this PredicateObjectMap.\r\n\t * \r\n\t * @return An unmodifiable list of GraphMaps.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_GRAPH_MAP)\r\n\tpublic List<GraphMap> getGraphMaps();\r\n\r\n\t/**\r\n\t * Returns an unmodifiable view of the list of RefObjectMaps that have been\r\n\t * added to this PredicateObjectMap.\r\n\t * \r\n\t * @return An unmodifiable list of RefObjectMaps.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_OBJECT_MAP)\r\n\tpublic List<RefObjectMap> getRefObjectMaps();\r\n\r\n\t/**\r\n\t * Returns an unmodifiable view of the list of ObjectMaps that have been\r\n\t * added to this PredicateObjectMap.\r\n\t * \r\n\t * @return An unmodifiable list of ObjectMaps.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_OBJECT_MAP)\r\n public List<ObjectMap> getObjectMaps();\r\n\r\n\t/**\r\n\t * Returns an unmodifiable view of the list of PredicateMaps that have been\r\n\t * added to this PredicateObjectMap.\r\n\t * \r\n\t * @return An unmodifiable list of PredicateMaps.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_PREDICATE_MAP)\r\n public List<PredicateMap> getPredicateMaps();\r\n\r\n\t/**\r\n\t * Remove the GraphMap given by the parameter, from the PredicateObjectMap.\r\n\t * The subsequent GraphMaps in the list will be shifted left.\r\n\t * \r\n\t * @param gm\r\n\t * The GraphMap to be removed.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_GRAPH_MAP)\r\n public void removeGraphMap(GraphMap gm);\r\n\r\n\t/**\r\n\t * Remove the RefObjectMap, given by the parameter, from the\r\n\t * PredicateObjectMap. The subsequent RefObjectMaps in the list will be\r\n\t * shifted left.\r\n\t * \r\n\t * @param rom\r\n\t * The RefObjectMap to be removed.\r\n\t * @throws IllegalStateException\r\n\t * If removing the RefObjectMap would cause the\r\n\t * PredicateObjectMap to contain no RefObjectMaps or ObjectMaps.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_OBJECT_MAP)\r\n\tpublic void removeRefObjectMap(RefObjectMap rom);\r\n\r\n\t/**\r\n\t * Remove the ObjectMap, given by the parameter, from the\r\n\t * PredicateObjectMap. The subsequent ObjectMaps in the list will be shifted\r\n\t * left.\r\n\t * \r\n\t * @param om\r\n\t * The ObjectMap to be removed.\r\n\t * @throws IllegalStateException\r\n\t * If removing the RefObjectMap would cause the\r\n\t * PredicateObjectMap to contain no RefObjectMaps or ObjectMaps.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_OBJECT_MAP)\r\n\tpublic void removeObjectMap(ObjectMap om);\r\n\r\n\t/**\r\n\t * Remove the PredicateMap, given by the parameter, from the\r\n\t * PredicateObjectMap. The subsequent PredicateMaps in the list will be\r\n\t * shifted left.\r\n\t * \r\n\t * @param pm\r\n\t * The PredicateMap to be removed.\r\n\t * @throws IllegalStateException\r\n\t * If removing the RefObjectMap would cause the\r\n\t * PredicateObjectMap to contain no PredicateMaps.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_OBJECT_MAP)\r\n\tpublic void removePredicateMap(PredicateMap pm);\r\n\r\n}\r",
"@W3C_R2RML_Recommendation(R2RMLVocabulary.TYPE_SUBJECT_MAP)\r\npublic interface SubjectMap extends TermMap {\r\n\r\n /**\r\n * Adds a class to the SubjectMap. The class URI will be added to the end of\r\n * the class list. A SubjectMap can have zero or more classes. The classURI\r\n * parameter must be an instance of the library's resource class.\r\n *\r\n * @param classURI The class URI that will be added.\r\n */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_CLASS)\r\n public void addClass(IRI classURI);\r\n\r\n /**\r\n * Adds a GraphMap to this SubjectMap. The GraphMap will be added to the end\r\n * of the GraphMap list. A SubjectMap can have zero or more GraphMaps.\r\n *\r\n * @param gm The GraphMap that will be added.\r\n */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_GRAPH_MAP)\r\n public void addGraphMap(GraphMap gm);\r\n\r\n /**\r\n * Adds a list of GraphMaps to this SubjectMap. A SubjectMap can have zero\r\n * or more GraphMaps. The GraphMaps will be added to the end of the GraphMap\r\n * list.\r\n *\r\n * @param gms The list of GraphMaps that will be added.\r\n */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_GRAPH_MAP)\r\n public void addGraphMap(List<GraphMap> gms);\r\n\r\n /**\r\n * {@inheritDoc}\r\n *\r\n * The possible values for the term type are\r\n * (http://www.w3.org/TR/r2rml/#dfn-term-type>):<br>\r\n * - rr:IRI<br>\r\n * - rr:BlankNode\r\n */\r\n @Override\r\n public void setTermType(IRI typeIRI);\r\n\r\n /**\r\n * Get the class URI located at the given index.\r\n *\r\n * @param index The index of the class URI.\r\n * @return The class URI located at the given index.\r\n * @throws IndexOutOfBoundsException If the given index is out of range.\r\n */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_CLASS)\r\n public IRI getClass(int index);\r\n\r\n /**\r\n * Get the GraphMap located at the given index.\r\n *\r\n * @param index The index of the GraphMap.\r\n * @return The GraphMap located at the given index.\r\n * @throws IndexOutOfBoundsException If the given index is out of range.\r\n */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_GRAPH_MAP)\r\n public GraphMap getGraphMap(int index);\r\n\r\n /**\r\n * Returns an unmodifiable view of the list of classes that have been added\r\n * to this SubjectMap.\r\n *\r\n * @return An unmodifiable list of classes.\r\n */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_CLASS)\r\n public List<IRI> getClasses();\r\n\r\n /**\r\n * Returns an unmodifiable view of the list of GraphMaps that have been\r\n * added to this SubjectMap.\r\n *\r\n * @return An unmodifiable list of GraphMaps.\r\n */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_GRAPH_MAP)\r\n public List<GraphMap> getGraphMaps();\r\n\r\n /**\r\n * Remove the class given by the parameter, from the SubjectMap. The\r\n * subsequent class URIs in the list will be shifted left. The classURI\r\n * parameter must be an instance of the library's resource class.\r\n *\r\n * @param classURI The class that will be removed.\r\n */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_CLASS)\r\n public void removeClass(IRI classURI);\r\n\r\n /**\r\n * Remove the GraphMap given by the parameter, from the SubjectMap. The\r\n * subsequent GraphMaps in the list will be shifted left.\r\n *\r\n * @param gm The GraphMap to be removed.\r\n */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_GRAPH_MAP)\r\n public void removeGraphMap(GraphMap gm);\r\n\r\n}\r",
"public interface Template {\r\n\r\n\t/**\r\n\t * Gets the string segment at the given index.\r\n\t * \r\n\t * @param segIndex\r\n\t * The index of the string segment.\r\n\t * @return The string segment at the given index.\r\n\t */\r\n\tString getStringSegment(int segIndex);\r\n\r\n /**\r\n * Gets the string segments\r\n * @return The string segments\r\n */\r\n List<String> getStringSegments();\r\n\r\n String getTemplateStringWithoutColumnNames();\r\n\r\n /**\r\n\t * Set the string segment on the given index. Any previously set segments on\r\n\t * this index will be removed. Adding a new string segment (that don't\r\n\t * overwrite older ones), must be done by adding it with an index one higher\r\n\t * that the previously highest index.\r\n\t * \r\n\t * @param segIndex\r\n\t * The index where the string segment will be set.\r\n\t * @param segment\r\n\t * The string segment to insert.\r\n\t * @throws IndexOutOfBoundsException\r\n\t * If the index is larger than the previously highest index plus\r\n\t * one.\r\n\t */\r\n\tvoid addStringSegment(int segIndex, String segment);\r\n\r\n\t/**\r\n\t * Gets the column name at the given index.\r\n\t * \r\n\t * @param colIndex\r\n\t * The index of the column name.\r\n\t * @return The column name at the given index.\r\n\t */\r\n\tString getColumnName(int colIndex);\r\n\r\n\t/**\r\n\t * Returns an unmodifiable view of all the column names in this template.\r\n\t * \r\n\t * @return An unmodifiable view of all column names.\r\n\t */\r\n\tList<String> getColumnNames();\r\n\r\n\t/**\r\n\t * Set the column name on the given index. Any previously set column names\r\n\t * on this index will be removed. Adding new column name (that don't\r\n\t * overwrite older ones), must be done by adding it with an index one higher\r\n\t * that the previously highest index.\r\n\t * \r\n\t * @param colIndex\r\n\t * The index where the column name will be set.\r\n\t * @param columnName\r\n\t * The column name to insert.\r\n\t * @throws IndexOutOfBoundsException\r\n\t * If the index is larger than the previously highest index plus\r\n\t * one.\r\n\t */\r\n\tvoid addColumnName(int colIndex, String columnName);\r\n}\r",
"@W3C_R2RML_Recommendation(R2RMLVocabulary.TYPE_TRIPLES_MAP)\r\npublic interface TriplesMap extends MappingComponent {\r\n\r\n\t/**\r\n\t * Set the LogicalTable of this TriplesMap. A TriplesMap must have exactly\r\n\t * one LogicalTable.\r\n\t * \r\n\t * @param lt\r\n\t * The LogicalTable that will be added.\r\n\t */\r\n\t@W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_LOGICAL_TABLE)\r\n\tpublic void setLogicalTable(LogicalTable lt);\r\n\r\n\t/**\r\n\t * Set the SubjectMap of this TriplesMap. A TriplesMap must have exactly one\r\n\t * SubjectMap.\r\n\t * \r\n\t * @param sm\r\n\t * The SubjectMap that will be added.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_SUBJECT_MAP)\r\n\tpublic void setSubjectMap(SubjectMap sm);\r\n\r\n\t/**\r\n\t * Adds a PredicateObjectMap to this TriplesMap. The PredicateObjectMap will\r\n\t * be added to the end of the PredicateObjectMap list. A TriplesMap can have\r\n\t * any number of PredicateObjectMaps.\r\n\t * \r\n\t * @param pom\r\n\t * The PredicateObjectMap that will be added.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_PREDICATE_OBJECT_MAP)\r\n\tpublic void addPredicateObjectMap(PredicateObjectMap pom);\r\n\t\r\n\t/**\r\n\t * Adds a collection of PredicateObjectMaps to this TriplesMap. The PredicateObjectMap will\r\n\t * be added to the end of the PredicateObjectMap list. A TriplesMap can have\r\n\t * any number of PredicateObjectMaps.\r\n\t * \r\n\t * @param poms\r\n\t * The PredicateObjectMaps that will be added.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_PREDICATE_OBJECT_MAP)\r\n\tpublic void addPredicateObjectMaps(Collection<PredicateObjectMap> poms);\r\n\r\n\t/**\r\n\t * Get the LogicalTable associated with this TriplesMap.\r\n\t * \r\n\t * @return The LogicalTable of this TriplesMap.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_LOGICAL_TABLE)\r\n\tpublic LogicalTable getLogicalTable();\r\n\r\n\t/**\r\n\t * Get the SubjectMap associated with this TriplesMap.\r\n\t * \r\n\t * @return The SubjectMap of this TriplesMap.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_SUBJECT_MAP)\r\n\tpublic SubjectMap getSubjectMap();\r\n\r\n\t/**\r\n\t * Get the PredicateObjectMap located at the given index.\r\n\t * \r\n\t * @param index\r\n\t * The index of the PredicateObjectMap.\r\n\t * @return The PredicateObjectMap located at the given index.\r\n\t * @throws IndexOutOfBoundsException\r\n\t * If the given index is out of range.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_PREDICATE_OBJECT_MAP)\r\n\tpublic PredicateObjectMap getPredicateObjectMap(int index);\r\n\r\n\t/**\r\n\t * Returns an unmodifiable view of the list of PredicateObjectMaps that have\r\n\t * been added to this TriplesMap.\r\n\t * \r\n\t * @return An unmodifiable list of PredicateObjectMaps.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_PREDICATE_OBJECT_MAP)\r\n\tpublic List<PredicateObjectMap> getPredicateObjectMaps();\r\n\r\n\t/**\r\n\t * Remove the PredicateObjectMap given by the parameter, from the\r\n\t * TriplesMap. The subsequent PredicateObjectMaps in the list will be\r\n\t * shifted left.\r\n\t * \r\n\t * @param pom\r\n\t * The PredicateObjectMap to be removed.\r\n\t */\r\n @W3C_R2RML_Recommendation(R2RMLVocabulary.PROP_PREDICATE_OBJECT_MAP)\r\n\tpublic void removePredicateObjectMap(PredicateObjectMap pom);\r\n\r\n\t\r\n\r\n}\r"
] | import eu.optique.r2rml.api.model.LogicalTable;
import eu.optique.r2rml.api.MappingFactory;
import eu.optique.r2rml.api.model.ObjectMap;
import eu.optique.r2rml.api.model.PredicateMap;
import eu.optique.r2rml.api.model.PredicateObjectMap;
import eu.optique.r2rml.api.model.SubjectMap;
import eu.optique.r2rml.api.model.Template;
import eu.optique.r2rml.api.model.TriplesMap;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import eu.optique.r2rml.api.binding.rdf4j.RDF4JR2RMLMappingManager;
import org.apache.commons.rdf.api.IRI;
import org.apache.commons.rdf.rdf4j.RDF4J;
import org.junit.Assert;
import org.junit.Test;
import org.eclipse.rdf4j.model.ValueFactory;
import org.eclipse.rdf4j.model.impl.ValueFactoryImpl;
| /*******************************************************************************
* Copyright 2013, the Optique Consortium
* 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.
*
* This first version of the R2RML API was developed jointly at the University of Oslo,
* the University of Bolzano, La Sapienza University of Rome, and fluid Operations AG,
* as part of the Optique project, www.optique-project.eu
******************************************************************************/
package rdf4jTest;
/**
* JUnit Test Cases
*
* @author Riccardo Mancini
*/
public class InMemoryStructureCreation1_Test {
@Test
public void test(){
| RDF4JR2RMLMappingManager mm = RDF4JR2RMLMappingManager.getInstance();
| 0 |
senseobservationsystems/sense-android-library | sense-android-library/src/nl/sense_os/service/ctrl/CtrlDefault.java | [
"public class SensePrefs {\r\n /**\r\n * Keys for the authentication-related preferences of the Sense Platform\r\n */\r\n public static class Auth {\r\n /**\r\n * Key for login preference for session cookie.\r\n * \r\n * @see SensePrefs#AUTH_PREFS\r\n */\r\n public static final String LOGIN_COOKIE = \"login_cookie\";\r\n /**\r\n *Key for login preference for session id.\r\n * \r\n * @see SensePrefs#AUTH_PREFS\r\n */\r\n public static final String LOGIN_SESSION_ID = \"session_id\";\r\n /**\r\n * Key for login preference for email address.\r\n * \r\n * @see SensePrefs#AUTH_PREFS\r\n */\r\n public static final String LOGIN_USERNAME = \"login_mail\";\r\n /**\r\n * Key for login preference for hashed password.\r\n * \r\n * @see SensePrefs#AUTH_PREFS\r\n */\r\n public static final String LOGIN_PASS = \"login_pass\";\r\n /**\r\n * Key for storing the online sensor list for this device (type of JSONArray).\r\n * \r\n * @see #SENSOR_LIST_COMPLETE\r\n * @see SensePrefs#AUTH_PREFS\r\n * @deprecated\r\n */\r\n public static final String SENSOR_LIST = \"sensor_list\";\r\n /**\r\n * Key for storing the online sensor list for this user (type of JSONArray).\r\n * \r\n * @see #SENSOR_LIST\r\n * @see SensePrefs#AUTH_PREFS\r\n */\r\n public static final String SENSOR_LIST_COMPLETE = \"sensor_list_complete\";\r\n /**\r\n * Key for storing the retrieval time of device's online sensor list.\r\n * \r\n * @see #SENSOR_LIST_COMPLETE_TIME\r\n * @see SensePrefs#AUTH_PREFS\r\n * @deprecated\r\n */\r\n public static final String SENSOR_LIST_TIME = \"sensor_list_timestamp\";\r\n /**\r\n * Key for storing the retrieval time of complete online sensor list.\r\n * \r\n * @see #SENSOR_LIST_TIME\r\n * @see SensePrefs#AUTH_PREFS\r\n */\r\n public static final String SENSOR_LIST_COMPLETE_TIME = \"sensor_list_complete_timestamp\";\r\n /**\r\n * Key for storing the online device id.\r\n * \r\n * @see SensePrefs#AUTH_PREFS\r\n */\r\n public static final String DEVICE_ID = \"device_id\";\r\n /**\r\n * Key for storing the retrieval time of the online device id.\r\n * \r\n * @see SensePrefs#AUTH_PREFS\r\n */\r\n public static final String DEVICE_ID_TIME = \"device_id_timestamp\";\r\n /**\r\n * Key for storing the online device type.\r\n * \r\n * @see SensePrefs#AUTH_PREFS\r\n */\r\n public static final String DEVICE_TYPE = \"device_type\";\r\n /**\r\n * Key for storing the IMEI of the phone.\r\n * \r\n * @see SensePrefs#AUTH_PREFS\r\n */\r\n public static final String PHONE_IMEI = \"phone_imei\";\r\n /**\r\n * Key for storing the type of the phone.\r\n * \r\n * @see SensePrefs#AUTH_PREFS\r\n */\r\n public static final String PHONE_TYPE = \"phone_type\";\r\n /**\r\n * Key for storing if gcm registration_id\r\n * \r\n * @see SensePrefs#AUTH_PREFS\r\n */\r\n public static final String GCM_REGISTRATION_ID = \"gcm_registration_id\";\r\n\r\n }\r\n\r\n /**\r\n * Keys for the main Sense Platform service preferences\r\n */\r\n public static class Main {\r\n\r\n public static class Advanced {\r\n /**\r\n * Key to use the development version of CommonSense.\r\n * \r\n * @see SensePrefs#AUTH_PREFS\r\n */\r\n public static final String DEV_MODE = \"devmode\";\r\n /**\r\n * Key for preference that toggles use of compression for transmission. Default is true.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String COMPRESS = \"compression\";\r\n /**\r\n * Key for preference that enables local storage, making the sensor data available to\r\n * other apps through a ContentProvider. Default is true.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n * @deprecated Local storage is always on.\r\n */\r\n public static final String LOCAL_STORAGE = \"local_storage\";\r\n /**\r\n * Key for preference that enables communication with CommonSense. Disable this to work\r\n * in local-only mode. Default is true.\r\n */\r\n public static final String USE_COMMONSENSE = \"use_commonsense\";\r\n /**\r\n * Key for preference that enables the location feedback sensor. Enable this to\r\n * participate in Pim's location feedback test. Default is false.\r\n */\r\n public static final String LOCATION_FEEDBACK = \"location_feedback\";\r\n /**\r\n * Key for preference that enables Agostino mode. Enable this to participate in\r\n * Agostino's saliency test. Default is false.\r\n */\r\n public static final String AGOSTINO = \"agostino_mode\";\r\n /**\r\n * Key for preference that enables energy saving mode when using mobile Internet. \r\n * When energy saving mode is on data will be uploaded every half an hour.\r\n * Default is true.\r\n * @see SensePrefs#MAIN_PREFS\r\n */ \r\n public static final String MOBILE_INTERNET_ENERGY_SAVING_MODE = \"mobile_internet_energy_saving_mode\";\r\n /**\r\n * Key for preference that enables data upload on wifi only.\r\n * Default is false.\r\n * @see SensePrefs#MAIN_PREFS\r\n */ \r\n public static final String WIFI_UPLOAD_ONLY = \"wifi_upload_only\";\r\n /**\r\n * Key for value of cache duration for local data in hours.\r\n * Default is 24.\r\n * @see SensePrefs#MAIN_PREFS\r\n */ \r\n public static final String RETENTION_HOURS = \"retention_hours\";\r\n /**\r\n * Key for preference that enable database encryption.\r\n * Default is false.\r\n * @see SensePrefs#MAIN_PREFS\r\n */ \r\n public static final String ENCRYPT_DATABASE = \"encrypt_database\";\r\n /**\r\n * Key for value of salt for database encryption\r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String ENCRYPT_DATABASE_SALT = \"encrypt_database_salt\";\r\n /**\r\n * Key for preference that enables encryption for credential data.\r\n * Default is false.\r\n * @see SensePrefs#MAIN_PREFS\r\n */ \r\n public static final String ENCRYPT_CREDENTIAL = \"encrypt_credential\";\r\n /**\r\n * Key for value of salt for credential encryption.\r\n * @see SensePrefs#MAIN_PREFS\r\n */ \r\n public static final String ENCRYPT_CREDENTIAL_SALT = \"encrypt_credential_salt\";\r\n }\r\n \r\n\r\n public static class Ambience {\r\n /**\r\n * Key for preference that toggles use of light sensor in ambience sensing.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String LIGHT = \"ambience_light\";\r\n /**\r\n * Key for preference that toggles use of camera light sensor in ambience sensing.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String CAMERA_LIGHT = \"ambience_camera_light\";\r\n /**\r\n * Key for preference that toggles use of the microphone in ambience sensing.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String MIC = \"ambience_mic\";\r\n /**\r\n * Key for preference that toggles audio recording ambience sensing.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String RECORD_AUDIO = \"ambience_record_audio\";\r\n /**\r\n * Key for preference that toggles use of the audio spectrum in ambience sensing.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String AUDIO_SPECTRUM = \"ambience_audio_spectrum\";\r\n /**\r\n * Key for preference that toggles use of the pressure sensor in ambience sensing.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String PRESSURE = \"ambience_pressure\";\r\n /**\r\n * Key for preference that toggles use of the temperature sensor in ambience sensing.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String TEMPERATURE = \"ambience_temperature\";\r\n /**\r\n * Key for preference that toggles use of the magnetic field sensor in ambience sensing.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String MAGNETIC_FIELD = \"ambience_magnetic_field\";\r\n /**\r\n * Key for preference that toggles use of the relative humidity sensor in ambience\r\n * sensing.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String HUMIDITY = \"ambience_humidity\";\r\n /**\r\n * Key for preference that toggles \"burst-mode\" for the noise sensor\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String BURSTMODE = \"ambience_burstmode\";\r\n /**\r\n * Key for preference that toggles whether to upload and store burst samples.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String DONT_UPLOAD_BURSTS = \"ambience_dont_upload_bursts\";\r\n /**\r\n * Key for preference that toggles whether to record one sided or two sided voice calls \r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String RECORD_TWO_SIDED_VOICE_CALL = \"record_two_sided_voice_call\";\r\n }\r\n\r\n public static class DevProx {\r\n /**\r\n * Key for preference that toggles use of Bluetooth in the Device Proximity sensor.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String BLUETOOTH = \"proximity_bt\";\r\n /**\r\n * Key for preference that toggles use of Wi-Fi in the Device Proximity sensor.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String WIFI = \"proximity_wifi\";\r\n /**\r\n * Key for preference that toggles use of NFC in the Device Proximity sensor.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String NFC = \"proximity_nfc\";\r\n }\r\n\r\n public static class External {\r\n\r\n public static class MyGlucoHealth {\r\n /**\r\n * Key for preference that toggles use of the MyGlucohealth sensor.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String MAIN = \"myglucohealth\";\r\n }\r\n\r\n public static class TanitaScale {\r\n /**\r\n * Key for preference that toggles use of the Tanita scale sensor.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String MAIN = \"tanita_scale\";\r\n }\r\n\r\n public static class ZephyrBioHarness {\r\n\r\n /**\r\n * Key for preference that toggles use of the Zephyr BioHarness.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String MAIN = \"zephyrBioHarness\";\r\n /**\r\n * Key for preference that toggles use of the Zephyr BioHarness Accelerometer.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String ACC = \"zephyrBioHarness_acc\";\r\n /**\r\n * Key for preference that toggles use of the Zephyr BioHarness Heart rate.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String HEART_RATE = \"zephyrBioHarness_heartRate\";\r\n /**\r\n * Key for preference that toggles use of the Zephyr BioHarness Temperature.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String TEMP = \"zephyrBioHarness_temp\";\r\n /**\r\n * Key for preference that toggles use of the Zephyr BioHarness Respiration rate.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String RESP = \"zephyrBioHarness_resp\";\r\n /**\r\n * Key for preference that toggles use of the Zephyr BioHarness worn status.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String WORN_STATUS = \"zephyrBioHarness_wornStatus\";\r\n /**\r\n * Key for preference that toggles use of the Zephyr BioHarness battery level.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String BATTERY = \"zephyrBioHarness_battery\";\r\n }\r\n\r\n public static class ZephyrHxM {\r\n /**\r\n * Key for preference that toggles use of the Zephyr HxM.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String MAIN = \"zephyrHxM\";\r\n /**\r\n * Key for preference that toggles use of the Zephyr HxM speed.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String SPEED = \"zephyrHxM_speed\";\r\n /**\r\n * Key for preference that toggles use of the Zephyr HxM heart rate.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String HEART_RATE = \"zephyrHxM_heartRate\";\r\n /**\r\n * Key for preference that toggles use of the Zephyr HxM battery.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String BATTERY = \"zephyrHxM_battery\";\r\n /**\r\n * Key for preference that toggles use of the Zephyr HxM distance.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String DISTANCE = \"zephyrHxM_distance\";\r\n /**\r\n * Key for preference that toggles use of the Zephyr HxM strides.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String STRIDES = \"zephyrHxM_strides\";\r\n }\r\n\r\n public static class OBD2Sensor {\r\n /**\r\n * Key for preference that toggles use of the OBD-II sensor.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String MAIN = \"obd2sensor\";\r\n }\r\n }\r\n\r\n public static class Location {\r\n /**\r\n * Key for preference that toggles use of GPS in location sensor.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n * @deprecated Selecting the location provider manually will replaced by the fused location provider.\r\n */\r\n @Deprecated\r\n public static final String GPS = \"location_gps\";\r\n /**\r\n * Key for preference that toggles use of Network in location sensor.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n * @deprecated Selecting the location provider manually will replaced by the fused location provider.\r\n */\r\n @Deprecated\r\n public static final String NETWORK = \"location_network\";\r\n /**\r\n * Key for preference that toggles use of sensor fusion to toggle the GPS usage.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n * @deprecated Selecting the GPS as provider automatically will be replaced by the fused location provider.\r\n */\r\n @Deprecated\r\n public static final String AUTO_GPS = \"automatic_gps\";\r\n /**\r\n * Key for preference that toggles use of the time zone sensor\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String TIME_ZONE = \"time_zone\";\r\n /**\r\n * Key for preference that toggles the use of the fused location provider.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String FUSED_PROVIDER = \"location_fused\";\r\n /**\r\n * Key for preference that sets the priority for the fused location provider.\r\n * By default the BALANCED priority is used.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String FUSED_PROVIDER_PRIORITY = \"location_fused_priority\";\r\n\r\n public static class FusedProviderPriority\r\n {\r\n /**\r\n * Key for preference that toggles the use of the fused location provider with a high power consumption and accuracy.\r\n * Accuracy: 1m (most precise location possible)\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String ACCURATE = \"location_fused_accurate\";\r\n /**\r\n * Key for preference that toggles the use of the fused location provider with a balance between power consumption and accuracy.\r\n * Accuracy: 100 (city block)\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String BALANCED = \"location_fused_balanced\";\r\n /**\r\n * Key for preference that toggles the use of the fused location provider with low power consumption and accuracy.\r\n * Accuracy: 10km (city level)\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String LOW_POWER = \"location_fused_low_power\";\r\n }\r\n }\r\n\r\n public static class Motion {\r\n /**\r\n * Key for preference that toggles use of Bluetooth in the DeviceProximity sensor.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String FALL_DETECT = \"motion_fall_detector\";\r\n /**\r\n * Key for preference that toggles use of Bluetooth in the DeviceProximity sensor.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String FALL_DETECT_DEMO = \"motion_fall_detector_demo\";\r\n /**\r\n * Key for preference that toggles \"epi-mode\", drastically changing motion sensing\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String EPIMODE = \"epimode\";\r\n /**\r\n * Key for preference that toggles \"burst-mode\", drastically changing motion sensing\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String BURSTMODE = \"burstmode\";\r\n /**\r\n * Key for preference that determines whether to unregister the motion sensor between\r\n * samples. Nota bene: unregistering the sensor breaks the screen rotation on some\r\n * phones (e.g. Nexus S).\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n \r\n /**\r\n * Key for preference that toggles whether to upload and store burst samples.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String DONT_UPLOAD_BURSTS = \"dont upload bursts\";\r\n \r\n /**\r\n * Key for preference that determines the burst duration. Duration is in milliseconds.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String BURST_DURATION = \"burst_duration\";\r\n \r\n public static final String UNREG = \"motion_unregister\";\r\n /**\r\n * Key for preference that toggles motion energy sensing, which measures average kinetic\r\n * energy over a sample period.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String MOTION_ENERGY = \"motion_energy\";\r\n /**\r\n * Key for preference that enables fix that re-registers the motion sensor when the\r\n * screen turns off.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String SCREENOFF_FIX = \"screenoff_fix\";\r\n /**\r\n * Key for preference that toggles the use of the gyroscope\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String GYROSCOPE = \"gyroscope\";\r\n /**\r\n * Key for preference that toggles the use of the accelerometer\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String ACCELEROMETER = \"accelerometer\";\r\n /**\r\n * Key for preference that toggles the use of the orientation sensor\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String ORIENTATION = \"orientation\";\r\n /**\r\n * Key for preference that toggles the use of the linear acceleration sensor\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String LINEAR_ACCELERATION = \"linear_acceleration\";\r\n }\r\n\r\n public static class PhoneState {\r\n /**\r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String BATTERY = \"phonestate_battery\";\r\n /**\r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String SCREEN_ACTIVITY = \"phonestate_screen_activity\";\r\n /**\r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String PROXIMITY = \"phonestate_proximity\";\r\n /**\r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String IP_ADDRESS = \"phonestate_ip\";\r\n /**\r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String DATA_CONNECTION = \"phonestate_data_connection\";\r\n /**\r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String UNREAD_MSG = \"phonestate_unread_msg\";\r\n /**\r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String SERVICE_STATE = \"phonestate_service_state\";\r\n /**\r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String SIGNAL_STRENGTH = \"phonestate_signal_strength\";\r\n /**\r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String CALL_STATE = \"phonestate_call_state\";\r\n /**\r\n * @see SensePrefs#MAIN_PREFS\r\n * */\r\n public static final String FOREGROUND_APP = \"foreground_app\";\r\n /**\r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String INSTALLED_APPS = \"installed_apps\";\r\n \r\n /**\r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n\t\t\tpublic static final String APP_INFO = \"app_info\";\r\n }\r\n\r\n public static class Quiz {\r\n /**\r\n * Key for preference that sets the interval between pop quizzes.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String RATE = \"popquiz_rate\";\r\n /**\r\n * Key for preference that sets the silent mode for pop quizzes.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String SILENT_MODE = \"popquiz_silent_mode\";\r\n /**\r\n * Key for generic preference that starts an update of the quiz questions when clicked.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String SYNC = \"popquiz_sync\";\r\n /**\r\n * Key for preference that holds the last update time of the quiz questions with\r\n * CommonSense.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String SYNC_TIME = \"popquiz_sync_time\";\r\n }\r\n\r\n public static class SampleRate {\r\n /**\r\n * Key for the preference that sets the sample interval to every 15 minutes.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String RARELY = \"1\";\r\n\r\n /**\r\n * Key for the preference that sets the sample interval to every 3 minutes.\r\n * For the Location sensors this is 5 minutes.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String BALANCED = \"2\";\r\n\r\n /**\r\n * Key for the preference that sets the sample interval to every minute.\r\n * For the Location sensors this is 5 minutes.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String NORMAL = \"0\";\r\n\r\n /**\r\n * Key for the preference that sets the sample interval to every 10 seconds.\r\n * For the Location sensors this is every 30 seconds.\r\n * For the External sensors this is every 5 seconds.\r\n * For the Motion sensors this is every 5 seconds.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String OFTEN = \"-1\";\r\n\r\n /**\r\n * Key for the preference that sets the sample interval to every second.\r\n * For the Ambience sensors this is as fast as possible.\r\n * For the Noise sensor this enabled the recording of audio files.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String REAL_TIME = \"-2\";\r\n }\r\n\r\n public static class SyncRate {\r\n /**\r\n * Key for the preference that enables data buffering and sets the upload interval to every 15 minutes.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String RARELY = \"2\";\r\n /**\r\n * Key for the preference that enables data buffering and sets the upload interval to every 30 minutes.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String ECO_MODE = \"1\";\r\n\r\n /**\r\n * Key for the preference that enables data buffering and sets the upload interval to every 5 minutes.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String NORMAL = \"0\";\r\n\r\n /**\r\n * Key for the preference that enables data buffering and sets the upload interval to every minute.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String OFTEN = \"-1\";\r\n\r\n /**\r\n * Key for the preference that disables data buffering and uploads every data point immediately.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String REAL_TIME = \"-2\";\r\n }\r\n\r\n /**\r\n * Key for preference that controls sample frequency of the sensors.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String SAMPLE_RATE = \"commonsense_rate\";\r\n /**\r\n * Key for preference that controls sync frequency with CommonSense.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String SYNC_RATE = \"sync_rate\";\r\n /**\r\n * Key for preference that saves the last running services.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String LAST_STATUS = \"last_status\";\r\n /**\r\n * Key for preference that stores a flag for first login.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String LAST_LOGGED_IN = \"never_logged_in\";\r\n /**\r\n * Key for preference that stores a timestamp for last time the sensors registration was\r\n * verified\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String LAST_VERIFIED_SENSORS = \"verified_sensors\";\r\n /**\r\n * Key for storing the application key\r\n * \r\n * @see SensePrefs#AUTH_PREFS\r\n */\r\n public static final String APPLICATION_KEY = \"application_key\";\r\n }\r\n\r\n /**\r\n * Keys for the status preferences of the Sense Platform service\r\n */\r\n public static class Status {\r\n /**\r\n * Key for the main status of the sensors. Set to <code>false</code> to disable all the\r\n * sensing components.\r\n * \r\n * @see SensePrefs#STATUS_PREFS\r\n */\r\n public static final String MAIN = \"main service status\";\r\n /**\r\n * Key for the status of the \"ambience\" sensors. Set to <code>true</code> to enable sensing.\r\n * \r\n * @see SensePrefs#STATUS_PREFS\r\n */\r\n public static final String AMBIENCE = \"ambience component status\";\r\n /**\r\n * Key for the status of the \"device proximity\" sensors. Set to <code>true</code> to enable\r\n * sensing.\r\n * \r\n * @see SensePrefs#STATUS_PREFS\r\n */\r\n public static final String DEV_PROX = \"device proximity component status\";\r\n /**\r\n * Key for the status of the external Bluetooth sensors. Set to <code>true</code> to enable\r\n * sensing.\r\n * \r\n * @see SensePrefs#STATUS_PREFS\r\n */\r\n public static final String EXTERNAL = \"external services component status\";\r\n /**\r\n * Key for the status of the location sensors. Set to <code>true</code> to enable sensing.\r\n * \r\n * @see SensePrefs#STATUS_PREFS\r\n */\r\n public static final String LOCATION = \"location component status\";\r\n /**\r\n * Key for the status of the motion sensors. Set to <code>true</code> to enable sensing.\r\n * \r\n * @see SensePrefs#STATUS_PREFS\r\n */\r\n public static final String MOTION = \"motion component status\";\r\n /**\r\n * Key for the status of the \"phone state\" sensors. Set to <code>true</code> to enable\r\n * sensing.\r\n * \r\n * @see SensePrefs#STATUS_PREFS\r\n */\r\n public static final String PHONESTATE = \"phone state component status\";\r\n /**\r\n * Key for the status of the questionnaire. Set to <code>true</code> to enable it.\r\n * \r\n * @see SensePrefs#STATUS_PREFS\r\n * @deprecated Sense does not support the questionnaire anymore\r\n */\r\n public static final String POPQUIZ = \"pop quiz component status\";\r\n /**\r\n * Key for preference to automatically start the Sense service on boot.\r\n * \r\n * @see SensePrefs#STATUS_PREFS\r\n */\r\n public static final String AUTOSTART = \"autostart\";\r\n /**\r\n * Key for preference to pause sensing until the next charge.\r\n * \r\n * @see SensePrefs#STATUS_PREFS\r\n */\r\n public static final String PAUSED_UNTIL_NEXT_CHARGE = \"paused until next charge status\";\r\n }\r\n\r\n public static class SensorSpecifics {\r\n public static class Loudness {\r\n /**\r\n * Key for learned value of total silence..\r\n */\r\n public static final String TOTAL_SILENCE = \"total_silence\";\r\n /**\r\n * Key for learned value of highest loudness.\r\n */\r\n public static final String LOUDEST = \"loudest\";\r\n }\r\n\r\n public static class AutoCalibratedNoise {\r\n /**\r\n * Key for learned value of total silence..\r\n */\r\n public static final String TOTAL_SILENCE = \"AutoCalibratedNoise.total_silence\";\r\n /**\r\n * Key for learned value of highest loudness.\r\n */\r\n public static final String LOUDEST = \"AutoCalibratedNoise.loudest\";\r\n }\r\n }\r\n\r\n /**\r\n * Name of the shared preferences file used for storing CommonSense authentication data. Use\r\n * {@link Context#MODE_PRIVATE}.\r\n * \r\n * @see #MAIN_PREFS_PREFS\r\n * @see #STATUS_PREFS\r\n */\r\n public static final String AUTH_PREFS = \"authentication\";// \"login\";\r\n /**\r\n * Name of the main preference file, used for storing the settings for the Sense service.\r\n * \r\n * @see #AUTH_PREFS\r\n * @see #STATUS_PREFS\r\n */\r\n public static final String MAIN_PREFS = \"main\";\r\n /**\r\n * Name of shared preferences file holding the desired status of the Sense service.\r\n * \r\n * @see #AUTH_PREFS\r\n * @see #MAIN_PREFS\r\n */\r\n public static final String STATUS_PREFS = \"service_status_prefs\";\r\n /**\r\n * Name of the sensor specifics file, used for storing the settings for the Sense service.\r\n * \r\n * @see #AUTH_PREFS\r\n * @see #STATUS_PREFS\r\n */\r\n public static final String SENSOR_SPECIFICS = \"sensor_specifics\";\r\n\r\n private SensePrefs() {\r\n // private constructor to prevent instantiation\r\n }\r\n}\r",
" public static class Main {\r\n\r\n public static class Advanced {\r\n /**\r\n * Key to use the development version of CommonSense.\r\n * \r\n * @see SensePrefs#AUTH_PREFS\r\n */\r\n public static final String DEV_MODE = \"devmode\";\r\n /**\r\n * Key for preference that toggles use of compression for transmission. Default is true.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String COMPRESS = \"compression\";\r\n /**\r\n * Key for preference that enables local storage, making the sensor data available to\r\n * other apps through a ContentProvider. Default is true.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n * @deprecated Local storage is always on.\r\n */\r\n public static final String LOCAL_STORAGE = \"local_storage\";\r\n /**\r\n * Key for preference that enables communication with CommonSense. Disable this to work\r\n * in local-only mode. Default is true.\r\n */\r\n public static final String USE_COMMONSENSE = \"use_commonsense\";\r\n /**\r\n * Key for preference that enables the location feedback sensor. Enable this to\r\n * participate in Pim's location feedback test. Default is false.\r\n */\r\n public static final String LOCATION_FEEDBACK = \"location_feedback\";\r\n /**\r\n * Key for preference that enables Agostino mode. Enable this to participate in\r\n * Agostino's saliency test. Default is false.\r\n */\r\n public static final String AGOSTINO = \"agostino_mode\";\r\n /**\r\n * Key for preference that enables energy saving mode when using mobile Internet. \r\n * When energy saving mode is on data will be uploaded every half an hour.\r\n * Default is true.\r\n * @see SensePrefs#MAIN_PREFS\r\n */ \r\n public static final String MOBILE_INTERNET_ENERGY_SAVING_MODE = \"mobile_internet_energy_saving_mode\";\r\n /**\r\n * Key for preference that enables data upload on wifi only.\r\n * Default is false.\r\n * @see SensePrefs#MAIN_PREFS\r\n */ \r\n public static final String WIFI_UPLOAD_ONLY = \"wifi_upload_only\";\r\n /**\r\n * Key for value of cache duration for local data in hours.\r\n * Default is 24.\r\n * @see SensePrefs#MAIN_PREFS\r\n */ \r\n public static final String RETENTION_HOURS = \"retention_hours\";\r\n /**\r\n * Key for preference that enable database encryption.\r\n * Default is false.\r\n * @see SensePrefs#MAIN_PREFS\r\n */ \r\n public static final String ENCRYPT_DATABASE = \"encrypt_database\";\r\n /**\r\n * Key for value of salt for database encryption\r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String ENCRYPT_DATABASE_SALT = \"encrypt_database_salt\";\r\n /**\r\n * Key for preference that enables encryption for credential data.\r\n * Default is false.\r\n * @see SensePrefs#MAIN_PREFS\r\n */ \r\n public static final String ENCRYPT_CREDENTIAL = \"encrypt_credential\";\r\n /**\r\n * Key for value of salt for credential encryption.\r\n * @see SensePrefs#MAIN_PREFS\r\n */ \r\n public static final String ENCRYPT_CREDENTIAL_SALT = \"encrypt_credential_salt\";\r\n }\r\n \r\n\r\n public static class Ambience {\r\n /**\r\n * Key for preference that toggles use of light sensor in ambience sensing.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String LIGHT = \"ambience_light\";\r\n /**\r\n * Key for preference that toggles use of camera light sensor in ambience sensing.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String CAMERA_LIGHT = \"ambience_camera_light\";\r\n /**\r\n * Key for preference that toggles use of the microphone in ambience sensing.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String MIC = \"ambience_mic\";\r\n /**\r\n * Key for preference that toggles audio recording ambience sensing.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String RECORD_AUDIO = \"ambience_record_audio\";\r\n /**\r\n * Key for preference that toggles use of the audio spectrum in ambience sensing.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String AUDIO_SPECTRUM = \"ambience_audio_spectrum\";\r\n /**\r\n * Key for preference that toggles use of the pressure sensor in ambience sensing.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String PRESSURE = \"ambience_pressure\";\r\n /**\r\n * Key for preference that toggles use of the temperature sensor in ambience sensing.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String TEMPERATURE = \"ambience_temperature\";\r\n /**\r\n * Key for preference that toggles use of the magnetic field sensor in ambience sensing.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String MAGNETIC_FIELD = \"ambience_magnetic_field\";\r\n /**\r\n * Key for preference that toggles use of the relative humidity sensor in ambience\r\n * sensing.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String HUMIDITY = \"ambience_humidity\";\r\n /**\r\n * Key for preference that toggles \"burst-mode\" for the noise sensor\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String BURSTMODE = \"ambience_burstmode\";\r\n /**\r\n * Key for preference that toggles whether to upload and store burst samples.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String DONT_UPLOAD_BURSTS = \"ambience_dont_upload_bursts\";\r\n /**\r\n * Key for preference that toggles whether to record one sided or two sided voice calls \r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String RECORD_TWO_SIDED_VOICE_CALL = \"record_two_sided_voice_call\";\r\n }\r\n\r\n public static class DevProx {\r\n /**\r\n * Key for preference that toggles use of Bluetooth in the Device Proximity sensor.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String BLUETOOTH = \"proximity_bt\";\r\n /**\r\n * Key for preference that toggles use of Wi-Fi in the Device Proximity sensor.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String WIFI = \"proximity_wifi\";\r\n /**\r\n * Key for preference that toggles use of NFC in the Device Proximity sensor.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String NFC = \"proximity_nfc\";\r\n }\r\n\r\n public static class External {\r\n\r\n public static class MyGlucoHealth {\r\n /**\r\n * Key for preference that toggles use of the MyGlucohealth sensor.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String MAIN = \"myglucohealth\";\r\n }\r\n\r\n public static class TanitaScale {\r\n /**\r\n * Key for preference that toggles use of the Tanita scale sensor.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String MAIN = \"tanita_scale\";\r\n }\r\n\r\n public static class ZephyrBioHarness {\r\n\r\n /**\r\n * Key for preference that toggles use of the Zephyr BioHarness.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String MAIN = \"zephyrBioHarness\";\r\n /**\r\n * Key for preference that toggles use of the Zephyr BioHarness Accelerometer.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String ACC = \"zephyrBioHarness_acc\";\r\n /**\r\n * Key for preference that toggles use of the Zephyr BioHarness Heart rate.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String HEART_RATE = \"zephyrBioHarness_heartRate\";\r\n /**\r\n * Key for preference that toggles use of the Zephyr BioHarness Temperature.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String TEMP = \"zephyrBioHarness_temp\";\r\n /**\r\n * Key for preference that toggles use of the Zephyr BioHarness Respiration rate.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String RESP = \"zephyrBioHarness_resp\";\r\n /**\r\n * Key for preference that toggles use of the Zephyr BioHarness worn status.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String WORN_STATUS = \"zephyrBioHarness_wornStatus\";\r\n /**\r\n * Key for preference that toggles use of the Zephyr BioHarness battery level.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String BATTERY = \"zephyrBioHarness_battery\";\r\n }\r\n\r\n public static class ZephyrHxM {\r\n /**\r\n * Key for preference that toggles use of the Zephyr HxM.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String MAIN = \"zephyrHxM\";\r\n /**\r\n * Key for preference that toggles use of the Zephyr HxM speed.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String SPEED = \"zephyrHxM_speed\";\r\n /**\r\n * Key for preference that toggles use of the Zephyr HxM heart rate.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String HEART_RATE = \"zephyrHxM_heartRate\";\r\n /**\r\n * Key for preference that toggles use of the Zephyr HxM battery.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String BATTERY = \"zephyrHxM_battery\";\r\n /**\r\n * Key for preference that toggles use of the Zephyr HxM distance.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String DISTANCE = \"zephyrHxM_distance\";\r\n /**\r\n * Key for preference that toggles use of the Zephyr HxM strides.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String STRIDES = \"zephyrHxM_strides\";\r\n }\r\n\r\n public static class OBD2Sensor {\r\n /**\r\n * Key for preference that toggles use of the OBD-II sensor.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String MAIN = \"obd2sensor\";\r\n }\r\n }\r\n\r\n public static class Location {\r\n /**\r\n * Key for preference that toggles use of GPS in location sensor.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n * @deprecated Selecting the location provider manually will replaced by the fused location provider.\r\n */\r\n @Deprecated\r\n public static final String GPS = \"location_gps\";\r\n /**\r\n * Key for preference that toggles use of Network in location sensor.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n * @deprecated Selecting the location provider manually will replaced by the fused location provider.\r\n */\r\n @Deprecated\r\n public static final String NETWORK = \"location_network\";\r\n /**\r\n * Key for preference that toggles use of sensor fusion to toggle the GPS usage.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n * @deprecated Selecting the GPS as provider automatically will be replaced by the fused location provider.\r\n */\r\n @Deprecated\r\n public static final String AUTO_GPS = \"automatic_gps\";\r\n /**\r\n * Key for preference that toggles use of the time zone sensor\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String TIME_ZONE = \"time_zone\";\r\n /**\r\n * Key for preference that toggles the use of the fused location provider.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String FUSED_PROVIDER = \"location_fused\";\r\n /**\r\n * Key for preference that sets the priority for the fused location provider.\r\n * By default the BALANCED priority is used.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String FUSED_PROVIDER_PRIORITY = \"location_fused_priority\";\r\n\r\n public static class FusedProviderPriority\r\n {\r\n /**\r\n * Key for preference that toggles the use of the fused location provider with a high power consumption and accuracy.\r\n * Accuracy: 1m (most precise location possible)\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String ACCURATE = \"location_fused_accurate\";\r\n /**\r\n * Key for preference that toggles the use of the fused location provider with a balance between power consumption and accuracy.\r\n * Accuracy: 100 (city block)\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String BALANCED = \"location_fused_balanced\";\r\n /**\r\n * Key for preference that toggles the use of the fused location provider with low power consumption and accuracy.\r\n * Accuracy: 10km (city level)\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String LOW_POWER = \"location_fused_low_power\";\r\n }\r\n }\r\n\r\n public static class Motion {\r\n /**\r\n * Key for preference that toggles use of Bluetooth in the DeviceProximity sensor.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String FALL_DETECT = \"motion_fall_detector\";\r\n /**\r\n * Key for preference that toggles use of Bluetooth in the DeviceProximity sensor.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String FALL_DETECT_DEMO = \"motion_fall_detector_demo\";\r\n /**\r\n * Key for preference that toggles \"epi-mode\", drastically changing motion sensing\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String EPIMODE = \"epimode\";\r\n /**\r\n * Key for preference that toggles \"burst-mode\", drastically changing motion sensing\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String BURSTMODE = \"burstmode\";\r\n /**\r\n * Key for preference that determines whether to unregister the motion sensor between\r\n * samples. Nota bene: unregistering the sensor breaks the screen rotation on some\r\n * phones (e.g. Nexus S).\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n \r\n /**\r\n * Key for preference that toggles whether to upload and store burst samples.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String DONT_UPLOAD_BURSTS = \"dont upload bursts\";\r\n \r\n /**\r\n * Key for preference that determines the burst duration. Duration is in milliseconds.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String BURST_DURATION = \"burst_duration\";\r\n \r\n public static final String UNREG = \"motion_unregister\";\r\n /**\r\n * Key for preference that toggles motion energy sensing, which measures average kinetic\r\n * energy over a sample period.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String MOTION_ENERGY = \"motion_energy\";\r\n /**\r\n * Key for preference that enables fix that re-registers the motion sensor when the\r\n * screen turns off.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String SCREENOFF_FIX = \"screenoff_fix\";\r\n /**\r\n * Key for preference that toggles the use of the gyroscope\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String GYROSCOPE = \"gyroscope\";\r\n /**\r\n * Key for preference that toggles the use of the accelerometer\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String ACCELEROMETER = \"accelerometer\";\r\n /**\r\n * Key for preference that toggles the use of the orientation sensor\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String ORIENTATION = \"orientation\";\r\n /**\r\n * Key for preference that toggles the use of the linear acceleration sensor\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String LINEAR_ACCELERATION = \"linear_acceleration\";\r\n }\r\n\r\n public static class PhoneState {\r\n /**\r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String BATTERY = \"phonestate_battery\";\r\n /**\r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String SCREEN_ACTIVITY = \"phonestate_screen_activity\";\r\n /**\r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String PROXIMITY = \"phonestate_proximity\";\r\n /**\r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String IP_ADDRESS = \"phonestate_ip\";\r\n /**\r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String DATA_CONNECTION = \"phonestate_data_connection\";\r\n /**\r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String UNREAD_MSG = \"phonestate_unread_msg\";\r\n /**\r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String SERVICE_STATE = \"phonestate_service_state\";\r\n /**\r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String SIGNAL_STRENGTH = \"phonestate_signal_strength\";\r\n /**\r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String CALL_STATE = \"phonestate_call_state\";\r\n /**\r\n * @see SensePrefs#MAIN_PREFS\r\n * */\r\n public static final String FOREGROUND_APP = \"foreground_app\";\r\n /**\r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String INSTALLED_APPS = \"installed_apps\";\r\n \r\n /**\r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\npublic static final String APP_INFO = \"app_info\";\r\n }\r\n\r\n public static class Quiz {\r\n /**\r\n * Key for preference that sets the interval between pop quizzes.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String RATE = \"popquiz_rate\";\r\n /**\r\n * Key for preference that sets the silent mode for pop quizzes.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String SILENT_MODE = \"popquiz_silent_mode\";\r\n /**\r\n * Key for generic preference that starts an update of the quiz questions when clicked.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String SYNC = \"popquiz_sync\";\r\n /**\r\n * Key for preference that holds the last update time of the quiz questions with\r\n * CommonSense.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String SYNC_TIME = \"popquiz_sync_time\";\r\n }\r\n\r\n public static class SampleRate {\r\n /**\r\n * Key for the preference that sets the sample interval to every 15 minutes.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String RARELY = \"1\";\r\n\r\n /**\r\n * Key for the preference that sets the sample interval to every 3 minutes.\r\n * For the Location sensors this is 5 minutes.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String BALANCED = \"2\";\r\n\r\n /**\r\n * Key for the preference that sets the sample interval to every minute.\r\n * For the Location sensors this is 5 minutes.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String NORMAL = \"0\";\r\n\r\n /**\r\n * Key for the preference that sets the sample interval to every 10 seconds.\r\n * For the Location sensors this is every 30 seconds.\r\n * For the External sensors this is every 5 seconds.\r\n * For the Motion sensors this is every 5 seconds.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String OFTEN = \"-1\";\r\n\r\n /**\r\n * Key for the preference that sets the sample interval to every second.\r\n * For the Ambience sensors this is as fast as possible.\r\n * For the Noise sensor this enabled the recording of audio files.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String REAL_TIME = \"-2\";\r\n }\r\n\r\n public static class SyncRate {\r\n /**\r\n * Key for the preference that enables data buffering and sets the upload interval to every 15 minutes.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String RARELY = \"2\";\r\n /**\r\n * Key for the preference that enables data buffering and sets the upload interval to every 30 minutes.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String ECO_MODE = \"1\";\r\n\r\n /**\r\n * Key for the preference that enables data buffering and sets the upload interval to every 5 minutes.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String NORMAL = \"0\";\r\n\r\n /**\r\n * Key for the preference that enables data buffering and sets the upload interval to every minute.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String OFTEN = \"-1\";\r\n\r\n /**\r\n * Key for the preference that disables data buffering and uploads every data point immediately.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String REAL_TIME = \"-2\";\r\n }\r\n\r\n /**\r\n * Key for preference that controls sample frequency of the sensors.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String SAMPLE_RATE = \"commonsense_rate\";\r\n /**\r\n * Key for preference that controls sync frequency with CommonSense.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String SYNC_RATE = \"sync_rate\";\r\n /**\r\n * Key for preference that saves the last running services.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String LAST_STATUS = \"last_status\";\r\n /**\r\n * Key for preference that stores a flag for first login.\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String LAST_LOGGED_IN = \"never_logged_in\";\r\n /**\r\n * Key for preference that stores a timestamp for last time the sensors registration was\r\n * verified\r\n * \r\n * @see SensePrefs#MAIN_PREFS\r\n */\r\n public static final String LAST_VERIFIED_SENSORS = \"verified_sensors\";\r\n /**\r\n * Key for storing the application key\r\n * \r\n * @see SensePrefs#AUTH_PREFS\r\n */\r\n public static final String APPLICATION_KEY = \"application_key\";\r\n }\r",
"public static class DataPoint implements BaseColumns {\n\n public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE\n + \"/vnd.sense_os.data_point\";\n public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE\n + \"/vnd.sense_os.data_point\";\n public static final String CONTENT_URI_PATH = \"/recent_values\";\n @Deprecated\n public static final String CONTENT_PERSISTED_URI_PATH = \"/persisted_values\";\n public static final String CONTENT_REMOTE_URI_PATH = \"/remote_values\";\n\n /**\n * The name of the sensor that generated the data point. <br>\n * <br>\n * TYPE: String\n */\n public static final String SENSOR_NAME = \"sensor_name\";\n /**\n * Description of the sensor that generated the data point. Can either be the hardware name,\n * or any other useful description. <br>\n * <br>\n * TYPE: String\n */\n public static final String SENSOR_DESCRIPTION = \"sensor_description\";\n /**\n * The data type of the data point. <br>\n * <br>\n * TYPE: String\n * \n * @see SenseDataTypes\n */\n public static final String DATA_TYPE = \"data_type\";\n /**\n * The human readable display name of the sensor that generated the data point. <br>\n * <br>\n * TYPE: String\n * \n * @see SenseDataTypes\n */\n public static final String DISPLAY_NAME = \"display_name\";\n /**\n * Time stamp for the data point, in milliseconds. <br>\n * <br>\n * TYPE: long\n */\n public static final String TIMESTAMP = \"timestamp\";\n /**\n * Data point value. <br>\n * <br>\n * TYPE: String\n */\n public static final String VALUE = \"value\";\n /**\n * Transmit state of the data point, signalling whether the point has been sent to\n * CommonSense already.<br>\n * <br>\n * TYPE: integer status code: 0 (not sent), or 1 (sent)\n */\n public static final String TRANSMIT_STATE = \"transmit_state\";\n /**\n * Device UUID of the sensor. Use this for sensors that are originated from\n * \"external sensors\", or leave <code>null</code> to use the phone as default device.<br>\n * <br>\n * TYPE: String\n */\n public static final String DEVICE_UUID = \"device_uuid\";\n\n private DataPoint() {\n // class should not be instantiated\n }\n}",
"public static class SensorNames {\n\n /**\n * Fall detector sensor. Can be a real fall or a regular free fall for demo's. Part of the\n * Motion sensors.\n */\n public static final String FALL_DETECTOR = \"fall_detector\";\n\n /** Noise level sensor. Part of the Ambience sensors. */\n public static final String NOISE = \"noise_sensor\";\n\n /** Noise level sensor (Burst-mode). Part of the Ambience sensors. */\n public static final String NOISE_BURST = \"noise_sensor (burst-mode)\";\n\n /** Audio spectrum sensor. Part of the Ambience sensors. */\n public static final String AUDIO_SPECTRUM = \"audio_spectrum\";\n\n /** Microphone output. Part of the Ambience sensors (real-time mode only). */\n public static final String MIC = \"microphone\";\n\n /** Light sensor. Part of the Ambience sensors. */\n public static final String LIGHT = \"light\";\n\n /** Camera Light sensor. Part of the Ambience sensors. */\n public static final String CAMERA_LIGHT = \"camera_light\";\n\n /** Bluetooth discovery sensor. Part of the Neighboring Devices sensors. */\n public static final String BLUETOOTH_DISCOVERY = \"bluetooth_discovery\";\n\n /** Wi-Fi scan sensor. Part of the Neighboring Devices sensors. */\n public static final String WIFI_SCAN = \"wifi scan\";\n\n /** NFC sensor. Part of the Neighboring Devices sensors. */\n public static final String NFC_SCAN = \"nfc_scan\";\n\n /** Acceleration sensor. Part of the Motion sensors, also used in Zephyr BioHarness */\n public static final String ACCELEROMETER = \"accelerometer\";\n\n /** Motion sensor. The basis for the other Motion sensors. */\n public static final String MOTION = \"motion\";\n\n /** Linear acceleration sensor name. Part of the Motion sensors. */\n public static final String LIN_ACCELERATION = \"linear acceleration\";\n\n /** Gyroscope sensor name. Part of the Motion sensors. */\n public static final String GYRO = \"gyroscope\";\n\n /** Magnetic field sensor name. Part of the Ambience sensors. */\n public static final String MAGNETIC_FIELD = \"magnetic field\";\n\n /** Orientation sensor name. Part of the Motion sensors. */\n public static final String ORIENT = \"orientation\";\n\n /** Epi-mode accelerometer sensor. Special part of the Motion sensors. */\n public static final String ACCELEROMETER_EPI = \"accelerometer (epi-mode)\";\n\n /** Burst-mode accelerometer sensor. Special part of the Motion sensors. */\n public static final String ACCELEROMETER_BURST = \"accelerometer (burst-mode)\";\n\n /** Burst-mode gyroscope sensor. Special part of the Motion sensors. */\n public static final String GYRO_BURST = \"gyroscope (burst-mode)\";\n\n /** Burst-mode linear acceleration sensor. Special part of the Motion sensors. */\n public static final String LINEAR_BURST = \"linear acceleration (burst-mode)\";\n\n /** Motion energy sensor name. Special part of the Motion sensors. */\n public static final String MOTION_ENERGY = \"motion energy\";\n\n /*** battery sensor for Zephyr BioHarness external sensor */\n public static final String BATTERY_LEVEL = \"battery level\";\n\n /** heart rate sensor for Zephyr BioHarness and HxM external sensors */\n public static final String HEART_RATE = \"heart rate\";\n\n /** respiration rate sensor for Zephyr BioHarness external sensor */\n public static final String RESPIRATION = \"respiration rate\";\n\n /** temperature sensor for Zephyr BioHarness external sensor */\n public static final String TEMPERATURE = \"temperature\";\n\n /** worn status for Zephyr BioHarness external sensor */\n public static final String WORN_STATUS = \"worn status\";\n\n /** blood pressure sensor */\n public static final String BLOOD_PRESSURE = \"blood_pressure\";\n\n /** reaction time sensor */\n public static final String REACTION_TIME = \"reaction_time\";\n\n /** speed sensor for Zephyr HxM external sensor */\n public static final String SPEED = \"speed\";\n\n /** distance sensor for Zephyr HxM external sensor */\n public static final String DISTANCE = \"distance\";\n\n /** battery sensor for Zephyr HxM external sensor */\n public static final String BATTERY_CHARGE = \"battery charge\";\n\n /** strides sensor (stappenteller) for Zephyr HxM external sensor */\n public static final String STRIDES = \"strides\";\n\n /** Location sensor. */\n public static final String LOCATION = \"position\";\n\n /** TimeZone sensor. */\n public static final String TIME_ZONE = \"time_zone\";\n\n /** Battery sensor. Part of the Phone State sensors. */\n public static final String BATTERY_SENSOR = \"battery sensor\";\n \n /** App info sensor. Part of the Phone State sensors. */\n public static final String APP_INFO_SENSOR = \"app_info\";\n\n /** Screen activity sensor. Part of the Phone State sensors. */\n public static final String SCREEN_ACTIVITY = \"screen activity\";\n\n /** Pressure sensor. Part of the Phone State sensors. */\n public static final String PRESSURE = \"pressure\";\n\n /** Proximity sensor. Part of the Phone State sensors. */\n public static final String PROXIMITY = \"proximity\";\n\n /** Call state sensor. Part of the Phone State sensors. */\n public static final String CALL_STATE = \"call state\";\n\n /** Data connection state sensor. Part of the Phone State sensors. */\n public static final String DATA_CONN = \"data connection\";\n\n /** IP address sensor. Part of the Phone State sensors. */\n public static final String IP_ADDRESS = \"ip address\";\n\n /** Mobile service state sensor. Part of the Phone State sensors. */\n public static final String SERVICE_STATE = \"service state\";\n\n /** Mobile signal strength sensor. Part of the Phone State sensors. */\n public static final String SIGNAL_STRENGTH = \"signal strength\";\n\n /** Unread messages sensor. Part of the Phone State sensors. */\n public static final String UNREAD_MSG = \"unread msg\";\n\n /** Data connection type sensor. Part of the Phone State sensors. */\n public static final String CONN_TYPE = \"connection type\";\n\n /** Monitor status since DTCs cleared. Part of the OBD-II sensors. */\n public static final String MONITOR_STATUS = \"monitor status\";\n\n /** Fuel system status. Part of the OBD-II sensors. */\n public static final String FUEL_SYSTEM_STATUS = \"fuel system status\";\n\n /** Calculated engine load. Part of the OBD-II sensors. */\n public static final String ENGINE_LOAD = \"calculated engine load value\";\n\n /** Engine coolant. Part of the OBD-II sensors. */\n public static final String ENGINE_COOLANT = \"engine coolant\";\n\n /** Short/Long term fuel trim bank 1 & 2. Part of the OBD-II sensors. */\n public static final String FUEL_TRIM = \"fuel trim\";\n\n /** Fuel Pressure. Part of the OBD-II sensors. */\n public static final String FUEL_PRESSURE = \"fuel pressure\";\n\n /** Intake manifold absolute pressure. Part of the OBD-II sensors. */\n public static final String INTAKE_PRESSURE = \"intake manifold absolute pressure\";\n\n /** Engine RPM. Part of the OBD-II sensors. */\n public static final String ENGINE_RPM = \"engine RPM\";\n\n /** Vehicle speed. Part of the OBD-II sensors. */\n public static final String VEHICLE_SPEED = \"vehicle speed\";\n\n /** Timing advance. Part of the OBD-II sensors. */\n public static final String TIMING_ADVANCE = \"timing advance\";\n\n /** Intake air temperature. Part of the OBD-II sensors. */\n public static final String INTAKE_TEMPERATURE = \"intake air temperature\";\n\n /** MAF air flow rate. Part of the OBD-II sensors. */\n public static final String MAF_AIRFLOW = \"MAF air flow rate\";\n\n /** Throttle position. Part of the OBD-II sensors. */\n public static final String THROTTLE_POSITION = \"throttle position\";\n\n /** Commanded secondary air status. Part of the OBD-II sensors. */\n public static final String AIR_STATUS = \"commanded secondary air status\";\n\n /** Oxygen sensors. Part of the OBD-II sensors. */\n public static final String OXYGEN_SENSORS = \"oxygen sensors\";\n\n /** OBD standards. Part of the OBD-II sensors. */\n public static final String OBD_STANDARDS = \"OBD standards\";\n\n /** Auxiliary input status. Part of the OBD-II sensors. */\n public static final String AUXILIARY_INPUT = \"auxiliary input status\";\n\n /** Run time since engine start. Part of the OBD-II sensors. */\n public static final String RUN_TIME = \"run time\";\n\n /** Ambient temperature sensor. Part of the ambience sensors. From API >= 14 only */\n public static final String AMBIENT_TEMPERATURE = \"ambient_temperature\";\n\n /** Relative humidity sensor. Part of the ambience sensors. From API >= 14 only */\n public static final String RELATIVE_HUMIDITY = \"relative_humidity\";\n\n /** Bluetooth number of neighbours, count sensor */\n public static final String BLUETOOTH_NEIGHBOURS_COUNT = \"bluetooth neighbours count\";\n\n /** Traveled distance for each day */\n public static final String TRAVELED_DISTANCE_24H = \"traveled distance 24h\";\n\n /** Traveled distance for each hour */\n public static final String TRAVELED_DISTANCE_1H = \"traveled distance 1h\";\n\n public static final String LOUDNESS = \"loudness\";\n\n public static final String ATTACHED_TO_MYRIANODE = \"attachedToMyriaNode\";\n\n public static final String APP_INSTALLED = \"installed_apps\";\n\n public static final String APP_FOREGROUND = \"foreground_app\";\n\n private SensorNames() {\n // class should not be instantiated\n }\n}",
"public class LocationSensor extends BaseSensor implements PeriodicPollingSensor {\n\n private class MyLocationListener implements LocationListener {\n\n @Override\n public void onLocationChanged(Location fix) {\n\n if (null != lastGpsFix) {\n if (SNTP.getInstance().getTime() - lastGpsFix.getTime() < MIN_SAMPLE_DELAY) {\n // Log.v(TAG, \"New location fix is too fast after last one\");\n return;\n }\n }\n\n // controller = Controller.getController(context);\n JSONObject json = new JSONObject();\n try {\n json.put(\"latitude\", fix.getLatitude());\n json.put(\"longitude\", fix.getLongitude());\n\n // always include all JSON fields, or we get problems with varying data_structure\n json.put(\"accuracy\", fix.hasAccuracy() ? fix.getAccuracy() : -1.0d);\n json.put(\"altitude\", fix.hasAltitude() ? fix.getAltitude() : -1.0);\n json.put(\"speed\", fix.hasSpeed() ? fix.getSpeed() : -1.0d);\n json.put(\"bearing\", fix.hasBearing() ? fix.getBearing() : -1.0d);\n json.put(\"provider\", null != fix.getProvider() ? fix.getProvider() : \"unknown\");\n\n if (fix.getProvider().equals(LocationManager.GPS_PROVIDER)) {\n lastGpsFix = fix;\n } else if (fix.getProvider().equals(LocationManager.NETWORK_PROVIDER)) {\n lastNwFix = fix;\n } else {\n // do nothing\n }\n\n } catch (JSONException e) {\n Log.e(TAG, \"JSONException in onLocationChanged\", e);\n return;\n }\n\n // use SNTP time\n long timestamp = SNTP.getInstance().getTime();\n notifySubscribers();\n SensorDataPoint dataPoint = new SensorDataPoint(json);\n dataPoint.sensorName = SensorNames.LOCATION;\n dataPoint.sensorDescription = SensorNames.LOCATION;\n dataPoint.timeStamp = timestamp;\n sendToSubscribers(dataPoint);\n\n // pass message to the MsgHandler\n Intent i = new Intent(context.getString(R.string.action_sense_new_data));\n i.putExtra(DataPoint.SENSOR_NAME, SensorNames.LOCATION);\n i.putExtra(DataPoint.VALUE, json.toString());\n i.putExtra(DataPoint.DATA_TYPE, SenseDataTypes.JSON);\n i.putExtra(DataPoint.TIMESTAMP, timestamp);\n i.setPackage(context.getPackageName());\n context.startService(i);\n\n distanceEstimator.addPoint(fix);\n }\n\n @Override\n public void onProviderDisabled(String provider) {\n controller.checkSensorSettings(isGpsAllowed, isListeningNw, isListeningGps,\n getSampleRate(), lastGpsFix, listenGpsStart, lastNwFix, listenNwStart,\n listenGpsStop, listenNwStop);\n }\n\n @Override\n public void onProviderEnabled(String provider) {\n controller.checkSensorSettings(isGpsAllowed, isListeningNw, isListeningGps,\n getSampleRate(), lastGpsFix, listenGpsStart, lastNwFix, listenNwStart,\n listenGpsStop, listenNwStop);\n }\n\n @Override\n public void onStatusChanged(String provider, int status, Bundle extras) {\n // do nothing\n }\n }\n\n private static final String TAG = \"Sense LocationSensor\";\n private static final String DISTANCE_ALARM_ACTION = \"nl.sense_os.service.LocationAlarm.distanceAlarm\";\n public static final long MIN_SAMPLE_DELAY = 5000; // 5 sec\n private static final int DISTANCE_ALARM_ID = 70;\n private static final float MIN_DISTANCE = 0;\n private static LocationSensor instance = null;\n\n /**\n * Factory method to get the singleton instance.\n * \n * @param context\n * @return instance\n */\n public static LocationSensor getInstance(Context context) {\n if (instance == null) {\n instance = new LocationSensor(context);\n }\n return instance;\n }\n\n /**\n * Receiver for periodic alarms to calculate distance values.\n */\n public final BroadcastReceiver distanceAlarmReceiver = new BroadcastReceiver() {\n\n @Override\n public void onReceive(Context context, Intent intent) {\n double distance = distanceEstimator.getTraveledDistance();\n\n notifySubscribers();\n SensorDataPoint dataPoint = new SensorDataPoint(distance);\n dataPoint.sensorName = SensorNames.TRAVELED_DISTANCE_1H;\n dataPoint.sensorDescription = SensorNames.TRAVELED_DISTANCE_1H;\n dataPoint.timeStamp = SNTP.getInstance().getTime();\n sendToSubscribers(dataPoint);\n\n // pass message to the MsgHandler\n Intent i = new Intent(context.getString(R.string.action_sense_new_data));\n i.putExtra(DataPoint.SENSOR_NAME, SensorNames.TRAVELED_DISTANCE_1H);\n i.putExtra(DataPoint.VALUE, (float) distance);\n i.putExtra(DataPoint.DATA_TYPE, SenseDataTypes.FLOAT);\n i.putExtra(DataPoint.TIMESTAMP, dataPoint.timeStamp);\n i.setPackage(context.getPackageName());\n context.startService(i);\n\n // start counting again, from the last location\n distanceEstimator.reset();\n }\n };\n\n private Controller controller;\n private Context context;\n private LocationManager locMgr;\n private final MyLocationListener gpsListener;\n private final MyLocationListener nwListener;\n private final MyLocationListener pasListener;\n private boolean isGpsAllowed;\n private boolean isNetworkAllowed;\n private boolean isListeningGps;\n private boolean isListeningNw;\n private long listenGpsStart;\n private long listenGpsStop;\n private Location lastGpsFix;\n private Location lastNwFix;\n private long listenNwStart;\n private long listenNwStop;\n private boolean active;\n private TraveledDistanceEstimator distanceEstimator;\n private PeriodicPollAlarmReceiver pollAlarmReceiver;\n\n /**\n * Constructor.\n * \n * @param context\n */\n protected LocationSensor(Context context) {\n this.context = context;\n pollAlarmReceiver = new PeriodicPollAlarmReceiver(this);\n locMgr = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);\n controller = Controller.getController(context);\n gpsListener = new MyLocationListener();\n nwListener = new MyLocationListener();\n pasListener = new MyLocationListener();\n distanceEstimator = new TraveledDistanceEstimator();\n }\n\n @Override\n public void doSample() {\n controller.checkSensorSettings(isGpsAllowed, isListeningNw, isListeningGps,\n getSampleRate(), lastGpsFix, listenGpsStart, lastNwFix, listenNwStart,\n listenGpsStop, listenNwStop);\n }\n\n /**\n * Gets the last known location fixes from the location providers, and sends it to the location\n * listener as first data point.\n */\n private void getLastKnownLocation() {\n\n // get the most recent location fixes\n Location gpsFix = locMgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);\n Location nwFix = locMgr.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);\n\n // see which provides the best recent fix\n Location bestFix = gpsFix;\n if (null != nwFix) {\n // see if network provider has better recent fix\n if (null == bestFix) {\n // gps did not provide a recent fix\n bestFix = nwFix;\n } else if (nwFix.getTime() < bestFix.getTime()\n && nwFix.getAccuracy() < bestFix.getAccuracy() + 100) {\n // network fix is more recent and pretty accurate\n bestFix = nwFix;\n }\n }\n\n // send best recent fix to location listener\n if (null != bestFix) {\n // check that the fix is not too old or from the future\n long presentTime = SNTP.getInstance().getTime();\n long oldTime = presentTime - 1000 * 60 * 5;\n if (bestFix.getTime() > oldTime && bestFix.getTime() < presentTime) {\n // use last known location as first sensor value\n gpsListener.onLocationChanged(bestFix);\n }\n }\n }\n\n @Override\n public boolean isActive() {\n return active;\n }\n\n public void notifyListeningRestarted(String msg) {\n // not used\n // TODO: clean up\n }\n\n public void notifyListeningStopped(String msg) {\n // not used\n // TODO: clean up\n }\n\n public void setGpsListening(boolean listen) {\n if (listen) {\n locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, getSampleRate(),\n MIN_DISTANCE, gpsListener);\n isListeningGps = true;\n listenGpsStart = SNTP.getInstance().getTime();\n lastGpsFix = null;\n } else {\n locMgr.removeUpdates(gpsListener);\n listenGpsStop = SNTP.getInstance().getTime();\n isListeningGps = false;\n }\n }\n\n public void setNetworkListening(boolean listen) {\n if (listen/* && isNetworkAllowed */) {\n try {\n locMgr.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, getSampleRate(),\n MIN_DISTANCE, nwListener);\n isListeningNw = true;\n listenNwStart = SNTP.getInstance().getTime();\n lastNwFix = null;\n } catch (IllegalArgumentException e) {\n Log.e(TAG, \"Failed to start listening to network provider! \" + e);\n listenNwStop = SNTP.getInstance().getTime();\n isListeningNw = false;\n }\n } else {\n locMgr.removeUpdates(nwListener);\n listenNwStop = SNTP.getInstance().getTime();\n isListeningNw = false;\n }\n }\n\n /**\n * Listens to passive location provider. Should only be called in Android versions where the\n * provider is available.\n */\n @TargetApi(Build.VERSION_CODES.FROYO)\n private void setPassiveListening(boolean listen) {\n if (listen) {\n locMgr.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, getSampleRate(),\n MIN_DISTANCE, pasListener);\n } else {\n locMgr.removeUpdates(pasListener);\n }\n }\n\n @Override\n public void setSampleRate(long sampleDelay) {\n super.setSampleRate(sampleDelay);\n stopPolling();\n startPolling();\n }\n\n private void startAlarms() {\n\n // register to receive the alarm\n context.getApplicationContext().registerReceiver(distanceAlarmReceiver,\n new IntentFilter(DISTANCE_ALARM_ACTION));\n\n AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);\n\n // start periodic for distance\n Intent distanceAlarm = new Intent(DISTANCE_ALARM_ACTION);\n PendingIntent operation2 = PendingIntent.getBroadcast(context, DISTANCE_ALARM_ID,\n distanceAlarm, 0);\n am.cancel(operation2);\n am.setRepeating(AlarmManager.RTC_WAKEUP, SNTP.getInstance().getTime(), 60L * 60 * 1000,\n operation2);\n\n /*\n * TODO: this also for 24 hours PendingIntent operation3 =\n * PendingIntent.getBroadcast(context, DISTANCE_ALARM_ID, distanceAlarm, 0);\n * am.cancel(operation3); am.setRepeating(AlarmManager.RTC_WAKEUP,\n * SNTP.getInstance().getTime(), 24L * 60 * 60 * 1000, operation3);\n */\n }\n\n /**\n * Registers for updates from the location providers.\n */\n private void startListening() {\n\n SharedPreferences mainPrefs = context.getSharedPreferences(SensePrefs.MAIN_PREFS,\n Context.MODE_PRIVATE);\n isGpsAllowed = mainPrefs.getBoolean(Main.Location.GPS, true);\n isNetworkAllowed = mainPrefs.getBoolean(Main.Location.NETWORK, true);\n\n // start listening to GPS and/or Network location\n if (isGpsAllowed) {\n setGpsListening(true);\n }\n if (isNetworkAllowed) {\n // Log.v(TAG, \"Start listening to location updates from Network\");\n setNetworkListening(true);\n }\n\n if (!isGpsAllowed && !isNetworkAllowed\n && Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {\n Log.v(TAG, \"Start passively listening to location updates for other apps\");\n setPassiveListening(true);\n }\n }\n\n /**\n * Registers for periodic polling using the scheduler.\n */\n private void startPolling() {\n // Log.v(TAG, \"start polling\");\n pollAlarmReceiver.start(context);\n }\n\n @Override\n public void startSensing(long sampleDelay) {\n setSampleRate(sampleDelay);\n active = true;\n\n startListening();\n startAlarms();\n getLastKnownLocation();\n }\n\n private void stopAlarms() {\n // unregister the receiver\n try {\n context.unregisterReceiver(distanceAlarmReceiver);\n } catch (IllegalArgumentException e) {\n // do nothing\n }\n\n // stop the alarm\n AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);\n\n Intent distanceAlarm = new Intent(DISTANCE_ALARM_ACTION);\n PendingIntent operation2 = PendingIntent.getBroadcast(context, DISTANCE_ALARM_ID,\n distanceAlarm, 0);\n am.cancel(operation2);\n }\n\n /**\n * Stops listening for location updates.\n */\n private void stopListening() {\n setGpsListening(false);\n setNetworkListening(false);\n setPassiveListening(false);\n }\n\n private void stopPolling() {\n // Log.v(TAG, \"stop polling\");\n pollAlarmReceiver.stop(context);\n }\n\n @Override\n public void stopSensing() {\n active = false;\n stopListening();\n stopAlarms();\n stopPolling();\n }\n}",
"public class SNTP {\n private static final String TAG = \"SNTP\";\n\n private static final int ORIGINATE_TIME_OFFSET = 24;\n private static final int RECEIVE_TIME_OFFSET = 32;\n private static final int TRANSMIT_TIME_OFFSET = 40;\n private static final int NTP_PACKET_SIZE = 48;\n\n private static final int NTP_PORT = 123;\n private static final int NTP_MODE_CLIENT = 3;\n private static final int NTP_VERSION = 3;\n public static final String HOST_WORLDWIDE = \"pool.ntp.org\";\n public static final String HOST_ASIA = \"asia.pool.ntp.org\";\n public static final String HOST_EUROPE = \"europe.pool.ntp.org\";\n public static final String HOST_NORTH_AMERICA = \"north-america.pool.ntp.org\";\n public static final String HOST_SOUTH_AMERICA = \"south-america.pool.ntp.org\";\n public static final String HOST_OCEANIA = \"oceania.pool.ntp.org\";\n private boolean useSimulateTime = false;\n\n // Number of seconds between Jan 1, 1900 and Jan 1, 1970\n // 70 years plus 17 leap days\n private static final long OFFSET_1900_TO_1970 = ((365L * 70L) + 17L) * 24L * 60L * 60L;\n\n // system time computed from NTP server response\n private long mNtpTime;\n\n // value of SystemClock.elapsedRealtime() corresponding to mNtpTime\n private long mNtpTimeReference;\n\n // round trip time in milliseconds\n private long mRoundTripTime;\n\n private long clockOffset = -1;\n\n private static SNTP sntp = null;\n\n /**\n * Returns whether time simulation is used\n * @return True is simulate time is being used\n */\n public boolean isSimulatingTime()\n {\n return useSimulateTime;\n }\n\n /**\n * Sets the current simulation time\n *\n * Will set the clock to the provided simulation time.<br>\n * #getTime will give the updated time based on this simulation time<br>\n * @param time The epoch time in ms to use as current time\n */\n public void setCurrentSimulationTime(long time)\n {\n clockOffset = time - System.currentTimeMillis();\n useSimulateTime = true;\n }\n\n /**\n * Disables the time simulation\n */\n public void disableTimeSimulation()\n {\n if(!useSimulateTime)\n return;\n clockOffset = -1;\n useSimulateTime = false;\n }\n /*\n * Nice singleton :)\n */\n public synchronized static SNTP getInstance() {\n if (sntp == null)\n sntp = new SNTP();\n return sntp;\n }\n\n /**\n * Sends an SNTP request to the given host and processes the response.\n * \n * @param host\n * host name of the server.\n * @param timeout\n * network timeout in milliseconds.\n * @return true if the transaction was successful.\n */\n public boolean requestTime(String host, int timeout) {\n\ttry {\n\t DatagramSocket socket = new DatagramSocket();\n\t socket.setSoTimeout(timeout);\n\t InetAddress address = InetAddress.getByName(host);\n\t byte[] buffer = new byte[NTP_PACKET_SIZE];\n\t DatagramPacket request = new DatagramPacket(buffer, buffer.length, address, NTP_PORT);\n\n\t // set mode = 3 (client) and version = 3\n\t // mode is in low 3 bits of first byte\n\t // version is in bits 3-5 of first byte\n\t buffer[0] = NTP_MODE_CLIENT | (NTP_VERSION << 3);\n\n\t // get current time and write it to the request packet\n\t long requestTime = System.currentTimeMillis();\n\t long requestTicks = SystemClock.elapsedRealtime();\n\t writeTimeStamp(buffer, TRANSMIT_TIME_OFFSET, requestTime);\n\n\t socket.send(request);\n\n\t // read the response\n\t DatagramPacket response = new DatagramPacket(buffer, buffer.length);\n\t socket.receive(response);\n\t long responseTicks = SystemClock.elapsedRealtime();\n\t long responseTime = requestTime + (responseTicks - requestTicks);\n\t socket.close();\n\n\t // extract the results\n\t long originateTime = readTimeStamp(buffer, ORIGINATE_TIME_OFFSET);\n\t long receiveTime = readTimeStamp(buffer, RECEIVE_TIME_OFFSET);\n\t long transmitTime = readTimeStamp(buffer, TRANSMIT_TIME_OFFSET);\n\t long roundTripTime = responseTicks - requestTicks - (transmitTime - receiveTime);\n\t // receiveTime = originateTime + transit + skew\n\t // responseTime = transmitTime + transit - skew\n\t // clockOffset = ((receiveTime - originateTime) + (transmitTime - responseTime))/2\n\t // = ((originateTime + transit + skew - originateTime) +\n\t // (transmitTime - (transmitTime + transit - skew)))/2\n\t // = ((transit + skew) + (transmitTime - transmitTime - transit + skew))/2\n\t // = (transit + skew - transit + skew)/2\n\t // = (2 * skew)/2 = skew\n\t clockOffset = ((receiveTime - originateTime) + (transmitTime - responseTime)) / 2;\n\t // if (Config.LOGD) Log.d(TAG, \"round trip: \" + roundTripTime + \" ms\");\n\t // if (Config.LOGD) Log.d(TAG, \"clock offset: \" + clockOffset + \" ms\");\n\n\t // save our results - use the times on this side of the network latency\n\t // (response rather than request time)\n\t mNtpTime = responseTime + clockOffset;\n\t mNtpTimeReference = responseTicks;\n\t mRoundTripTime = roundTripTime;\n\t} catch (Exception e) {\n\t Log.w(TAG, \"Request time failed: \" + e);\n\t return false;\n\t}\n\n\treturn true;\n }\n\n /**\n * Get the current time, based on NTP clockOffset if or System time\n * \n * @return the ntp time from the worldwide pool if available else the system time\n */\n public long getTime() {\n\t// get the clock offset\n\tif (clockOffset == -1) {\n\t if (requestTime(HOST_WORLDWIDE, 1000)) {\n\t\treturn getNtpTime();\n\t } else {\n\t\tclockOffset = 0;\n\t }\n\t}\n\n\treturn System.currentTimeMillis() + clockOffset;\n }\n\n /**\n * Returns the time computed from the NTP transaction.\n * \n * @return time value computed from NTP server response.\n */\n public long getNtpTime() {\n \t//Log.d(TAG,\"SNTP time requested\");\n \t//return 1412175540000l;\n \treturn mNtpTime;\n }\n\n /**\n * Returns the reference clock value (value of SystemClock.elapsedRealtime()) corresponding to\n * the NTP time.\n * \n * @return reference clock corresponding to the NTP time.\n */\n public long getNtpTimeReference() {\n\treturn mNtpTimeReference;\n }\n\n /**\n * Returns the round trip time of the NTP transaction\n * \n * @return round trip time in milliseconds.\n */\n public long getRoundTripTime() {\n\treturn mRoundTripTime;\n }\n\n /**\n * Reads an unsigned 32 bit big endian number from the given offset in the buffer.\n */\n private long read32(byte[] buffer, int offset) {\n\tbyte b0 = buffer[offset];\n\tbyte b1 = buffer[offset + 1];\n\tbyte b2 = buffer[offset + 2];\n\tbyte b3 = buffer[offset + 3];\n\n\t// convert signed bytes to unsigned values\n\tint i0 = ((b0 & 0x80) == 0x80 ? (b0 & 0x7F) + 0x80 : b0);\n\tint i1 = ((b1 & 0x80) == 0x80 ? (b1 & 0x7F) + 0x80 : b1);\n\tint i2 = ((b2 & 0x80) == 0x80 ? (b2 & 0x7F) + 0x80 : b2);\n\tint i3 = ((b3 & 0x80) == 0x80 ? (b3 & 0x7F) + 0x80 : b3);\n\n\treturn ((long) i0 << 24) + ((long) i1 << 16) + ((long) i2 << 8) + (long) i3;\n }\n\n /**\n * Reads the NTP time stamp at the given offset in the buffer and returns it as a system time\n * (milliseconds since January 1, 1970).\n */\n private long readTimeStamp(byte[] buffer, int offset) {\n\tlong seconds = read32(buffer, offset);\n\tlong fraction = read32(buffer, offset + 4);\n\treturn ((seconds - OFFSET_1900_TO_1970) * 1000) + ((fraction * 1000L) / 0x100000000L);\n }\n\n /**\n * Writes system time (milliseconds since January 1, 1970) as an NTP time stamp at the given\n * offset in the buffer.\n */\n private void writeTimeStamp(byte[] buffer, int offset, long time) {\n\tlong seconds = time / 1000L;\n\tlong milliseconds = time - seconds * 1000L;\n\tseconds += OFFSET_1900_TO_1970;\n\n\t// write seconds in big endian format\n\tbuffer[offset++] = (byte) (seconds >> 24);\n\tbuffer[offset++] = (byte) (seconds >> 16);\n\tbuffer[offset++] = (byte) (seconds >> 8);\n\tbuffer[offset++] = (byte) (seconds >> 0);\n\n\tlong fraction = milliseconds * 0x100000000L / 1000L;\n\t// write fraction in big endian format\n\tbuffer[offset++] = (byte) (fraction >> 24);\n\tbuffer[offset++] = (byte) (fraction >> 16);\n\tbuffer[offset++] = (byte) (fraction >> 8);\n\t// low order bits should be random data\n\tbuffer[offset++] = (byte) (Math.random() * 255.0);\n }\n}",
"public class LocalStorage {\n\n /**\n * Minimum time to retain data points. If data is not sent to CommonSense, it will be retained\n * longer.\n */\n private static final int DEFAULT_RETENTION_HOURS = 24;\n\n /**\n * Default projection for rows of data points\n */\n private static final String[] DEFAULT_PROJECTION = new String[] { BaseColumns._ID,\n DataPoint.SENSOR_NAME, DataPoint.DISPLAY_NAME, DataPoint.SENSOR_DESCRIPTION,\n DataPoint.DATA_TYPE, DataPoint.VALUE, DataPoint.TIMESTAMP, DataPoint.DEVICE_UUID,\n DataPoint.TRANSMIT_STATE };\n\n private static final int LOCAL_VALUES_URI = 1;\n private static final int REMOTE_VALUES_URI = 2;\n\n private static final String TAG = \"LocalStorage\";\n\n private static final int DEFAULT_LIMIT = 100;\n\n private static LocalStorage instance;\n\n /**\n * @param context\n * Context for lazy creating the LocalStorage.\n * @return Singleton instance of the LocalStorage\n */\n public static LocalStorage getInstance(Context context) {\n // Log.v(TAG, \"Get local storage instance\");\n if (null == instance) {\n instance = new LocalStorage(context.getApplicationContext());\n }\n return instance;\n }\n\n private final RemoteStorage commonSense;\n private final SQLiteStorage inMemory;\n private final SQLiteStorage persisted;\n\n private Context context;\n\n private LocalStorage(Context context) {\n Log.i(TAG, \"Construct new local storage instance\");\n this.context = context;\n persisted = new SQLiteStorage(context, true);\n inMemory = new SQLiteStorage(context, false);\n commonSense = new RemoteStorage(context);\n }\n\n public int delete(Uri uri, String where, String[] selectionArgs) {\n switch (matchUri(uri)) {\n case LOCAL_VALUES_URI:\n int nrDeleted = 0;\n nrDeleted += inMemory.delete(where, selectionArgs);\n nrDeleted += persisted.delete(where, selectionArgs);\n return nrDeleted;\n case REMOTE_VALUES_URI:\n throw new IllegalArgumentException(\"Cannot delete values from CommonSense!\");\n default:\n throw new IllegalArgumentException(\"Unknown URI \" + uri);\n }\n }\n\n /**\n * Removes old data from the persistent storage.\n * \n * @return The number of data points deleted\n */\n private int deleteOldData() {\n Log.i(TAG, \"Delete old data points from persistent storage\");\n\n\n SharedPreferences prefs = context.getSharedPreferences(SensePrefs.MAIN_PREFS,\n Context.MODE_PRIVATE);\n // set max retention time\n int retentionHours = prefs.getInt( Main.Advanced.RETENTION_HOURS, DEFAULT_RETENTION_HOURS );\n long retentionLimit = SNTP.getInstance().getTime() - getMilliSencondsOfHours( retentionHours );\n // check preferences to see if the data needs to be sent to CommonSense\n boolean useCommonSense = prefs.getBoolean(Main.Advanced.USE_COMMONSENSE, true);\n\n String where = null;\n if (useCommonSense) {\n // delete data older than maximum retention time if it had been transmitted\n where = DataPoint.TIMESTAMP + \"<\" + retentionLimit + \" AND \" + DataPoint.TRANSMIT_STATE\n + \"==1\";\n } else {\n // not using CommonSense: delete all data older than maximum retention time\n where = DataPoint.TIMESTAMP + \"<\" + retentionLimit;\n }\n int deleted = persisted.delete(where, null);\n\n return deleted;\n }\n\n public String getType(Uri uri) {\n int uriType = matchUri(uri);\n if (uriType == LOCAL_VALUES_URI || uriType == REMOTE_VALUES_URI) {\n return DataPoint.CONTENT_TYPE;\n } else {\n throw new IllegalArgumentException(\"Unknown URI \" + uri);\n }\n }\n\n public Uri insert(Uri uri, ContentValues values) {\n\n // check the URI\n switch (matchUri(uri)) {\n case LOCAL_VALUES_URI:\n // implementation below\n break;\n case REMOTE_VALUES_URI:\n throw new IllegalArgumentException(\n \"Cannot insert into CommonSense through this ContentProvider\");\n default:\n throw new IllegalArgumentException(\"Unknown URI \" + uri);\n }\n\n // insert in the in-memory database\n long rowId = 0;\n try {\n rowId = inMemory.insert(values);\n } catch (BufferOverflowException e) {\n // in-memory storage is full!\n deleteOldData();\n persistRecentData();\n\n // try again\n rowId = inMemory.insert(values);\n }\n\n // notify any listeners (does this work properly?)\n Uri contentUri = Uri.parse(\"content://\"\n + context.getString(R.string.local_storage_authority) + DataPoint.CONTENT_URI_PATH);\n Uri rowUri = ContentUris.withAppendedId(contentUri, rowId);\n context.getContentResolver().notifyChange(rowUri, null);\n\n return rowUri;\n }\n\n private int matchUri(Uri uri) {\n if (DataPoint.CONTENT_URI_PATH.equals(uri.getPath())) {\n return LOCAL_VALUES_URI;\n } else if (DataPoint.CONTENT_REMOTE_URI_PATH.equals(uri.getPath())) {\n return REMOTE_VALUES_URI;\n } else {\n return -1;\n }\n }\n\n private int persistRecentData() {\n Log.i(TAG, \"Persist recent data points from in-memory storage\");\n\n Cursor recentPoints = null;\n int nrRecentPoints = 0;\n try {\n SharedPreferences prefs = context.getSharedPreferences(SensePrefs.MAIN_PREFS, Context.MODE_PRIVATE);\n int retentionHours = prefs.getInt( Main.Advanced.RETENTION_HOURS, DEFAULT_RETENTION_HOURS );\n long retentionLimit = SNTP.getInstance().getTime() - getMilliSencondsOfHours( retentionHours );\n\n // get unsent or very recent data from the memory\n String selectUnsent = DataPoint.TRANSMIT_STATE + \"!=1\" + \" OR \" + DataPoint.TIMESTAMP\n + \">\" + retentionLimit;\n recentPoints = inMemory.query(DEFAULT_PROJECTION, selectUnsent, null, null);\n nrRecentPoints = recentPoints.getCount();\n\n // bulk insert the new data\n persisted.bulkInsert(recentPoints);\n\n // remove all the in-memory data\n inMemory.delete(null, null);\n\n } finally {\n if (null != recentPoints) {\n recentPoints.close();\n recentPoints = null;\n }\n }\n return nrRecentPoints;\n }\n\n public Cursor query(Uri uri, String[] projection, String where, String[] selectionArgs,\n String sortOrder) {\n return query(uri, projection, where, selectionArgs, DEFAULT_LIMIT, sortOrder);\n }\n\n public Cursor query(Uri uri, String[] projection, String where, String[] selectionArgs,\n int limit, String sortOrder) {\n // Log.v(TAG, \"Query data points in local storage\");\n\n // check URI\n switch (matchUri(uri)) {\n case LOCAL_VALUES_URI:\n // implementation below\n break;\n case REMOTE_VALUES_URI:\n try {\n return commonSense.query(uri, projection, where, selectionArgs, limit, sortOrder);\n } catch (Exception e) {\n Log.e(TAG, \"Failed to query the CommonSense data points\", e);\n return null;\n }\n default:\n Log.e(TAG, \"Unknown URI: \" + uri);\n throw new IllegalArgumentException(\"Unknown URI \" + uri);\n }\n\n // use default projection if needed\n if (projection == null) {\n projection = DEFAULT_PROJECTION;\n }\n\n // query both databases\n Cursor inMemoryCursor = inMemory.query(projection, where, selectionArgs, sortOrder);\n Cursor persistedCursor = persisted.query(projection, where, selectionArgs, sortOrder);\n\n if (inMemoryCursor.getCount() > 0) {\n if (persistedCursor.getCount() > 0) {\n // merge cursors\n if (sortOrder != null && sortOrder.toLowerCase(Locale.ENGLISH).contains(\"desc\")) {\n // assume that data from inMemoryCursor is newer than from persistedCursor\n return new MergeCursor(new Cursor[] { inMemoryCursor, persistedCursor });\n } else {\n // assume that data from persistedCursor is newer than from inMemoryCursor\n return new MergeCursor(new Cursor[] { persistedCursor, inMemoryCursor });\n }\n } else {\n persistedCursor.close();\n return inMemoryCursor;\n }\n\n } else {\n inMemoryCursor.close();\n return persistedCursor;\n }\n }\n\n public int update(Uri uri, ContentValues newValues, String where, String[] selectionArgs) {\n\n // check URI\n switch (matchUri(uri)) {\n case LOCAL_VALUES_URI:\n // implementation below\n break;\n case REMOTE_VALUES_URI:\n throw new IllegalArgumentException(\"Cannot update data points in CommonSense\");\n default:\n throw new IllegalArgumentException(\"Unknown URI \" + uri);\n }\n\n // persist parameter is used to initiate persisting the volatile data\n boolean persist = \"true\".equals(uri.getQueryParameter(\"persist\"));\n\n int result = 0;\n if (!persist) {\n // Log.v(TAG, \"Update data points in local storage\");\n int updated = 0;\n updated += inMemory.update(newValues, where, selectionArgs);\n updated += persisted.update(newValues, where, selectionArgs);\n return updated;\n } else {\n deleteOldData();\n persistRecentData();\n }\n\n // notify content observers\n context.getContentResolver().notifyChange(uri, null);\n\n return result;\n }\n \n public static long getMilliSencondsOfHours(int hours){\n return 1000l* 60 * 60 * hours;\n }\n\n}"
] | import nl.sense_os.service.R;
import nl.sense_os.service.constants.SensePrefs;
import nl.sense_os.service.constants.SensePrefs.Main;
import nl.sense_os.service.constants.SensorData.DataPoint;
import nl.sense_os.service.constants.SensorData.SensorNames;
import nl.sense_os.service.location.LocationSensor;
import nl.sense_os.service.provider.SNTP;
import nl.sense_os.service.storage.LocalStorage;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.util.Log; | package nl.sense_os.service.ctrl;
/**
* Implements the default behavior of the Location Sensor and DataTransmitter
*/
public class CtrlDefault extends Controller {
private static final String TAG = "CtrlDefault";
private Context mContext;
public CtrlDefault(Context context) {
super(context);
Log.i(TAG, "Creating default controller");
mContext = context;
}
@Override
public void checkLightSensor(float value) {
// not implemented in this controller
}
@Override
public void checkNoiseSensor(double dB) {
// not implemented in this controller
}
@Override
public void checkSensorSettings(boolean isGpsAllowed, boolean isListeningNw,
boolean isListeningGps, long time, Location lastGpsFix, long listenGpsStart,
Location lastNwFix, long listenNwStart, long listenGpsStop, long listenNwStop) {
//Log.v(TAG, "Do sample");
SharedPreferences mainPrefs = mContext.getSharedPreferences(SensePrefs.MAIN_PREFS,
Context.MODE_PRIVATE);
boolean selfAwareMode = isGpsAllowed && mainPrefs.getBoolean(Main.Location.AUTO_GPS, true);
if (selfAwareMode) {
Log.v(TAG, "Check location sensor settings...");
LocationSensor locListener = LocationSensor.getInstance(mContext);
if (isListeningGps) {
if (!isGpsProductive(isListeningGps, time, lastGpsFix, listenGpsStart)) {
// switch off
locListener.setGpsListening(false);
locListener.notifyListeningStopped("not productive");
} else {
// we're fine
}
} else {
if (isAccelerating()) {
// switch on
locListener.setGpsListening(true);
locListener.notifyListeningRestarted("moved");
} else if (isPositionChanged()) {
// switch on
locListener.setGpsListening(true);
locListener.notifyListeningRestarted("position changed");
} else if (isSwitchedOffTooLong(isListeningGps, listenGpsStop)) {
// switch on
locListener.setGpsListening(true);
locListener.notifyListeningRestarted("timeout");
} else {
// we're fine
}
}
}
}
private boolean isAccelerating() {
Log.v(TAG, "Check if device was accelerating recently");
boolean moving = true;
Cursor data = null;
try {
// get linear acceleration data
long timerange = 1000 * 60 * 15; // 15 minutes
Uri uri = Uri.parse("content://" + mContext.getString(R.string.local_storage_authority)
+ DataPoint.CONTENT_URI_PATH);
String[] projection = new String[] { DataPoint.SENSOR_NAME, DataPoint.TIMESTAMP,
DataPoint.VALUE }; | String selection = DataPoint.SENSOR_NAME + "='" + SensorNames.LIN_ACCELERATION + "'" | 3 |
coopernurse/barrister-java | conform/src/main/java/com/bitmechanic/barrister/conform/Client.java | [
"public class RpcRequest {\n\n private static final Object[] EMPTY_PARAM = new Object[0];\n\n private String id;\n private MethodParser method;\n private Object[] params;\n\n /**\n * Creates a new RpcRequest\n *\n * @param id ID of this request\n * @param method Method to invoke on the server. Barrister uses a dotted method\n * \"interface-name.function-name\"\n * @param params Parameters to pass to the function. If null, an empty list is sent.\n */\n public RpcRequest(String id, String method, Object params) {\n this.id = id;\n this.method = new MethodParser(method);\n\n if (params == null) {\n this.params = EMPTY_PARAM;\n }\n else if (params instanceof List) {\n this.params = ((List)params).toArray();\n }\n else if (params.getClass().isArray()) {\n this.params = (Object[])params;\n }\n else {\n this.params = new Object[] { params };\n }\n }\n\n /**\n * Creates a new RpcRequest using Map input.\n * Keys: 'id', 'method', 'params'\n */\n public RpcRequest(Map map) {\n this((String)map.get(\"id\"), (String)map.get(\"method\"), map.get(\"params\"));\n }\n\n /**\n * Returns the ID of this request. Used to correlated responses with requests.\n */\n public String getId() {\n return id;\n }\n\n /**\n * Returns the method for this request.\n */\n public String getMethod() {\n return method.getMethod();\n }\n\n /**\n * Returns the Barrister Function name expressed by the method\n */\n public String getFunc() {\n return method.getFunc();\n }\n\n /**\n * Returns the Barrister Interface name expressed by the method\n */\n public String getIface() {\n return method.getIface();\n }\n\n /**\n * Returns the parameters to the function for this request\n */\n public Object[] getParams() {\n return params;\n }\n\n /**\n * Marshals this request to a Map that can be serialized and sent over the wire.\n * Uses the Contract to resolve the Function associated with the method.\n *\n * @param contract Contract to use to resolve Function\n * @return JSON-RPC formatted Map based on the request id, method, and params\n */\n @SuppressWarnings(\"unchecked\") \n public Map marshal(Contract contract) throws RpcException {\n Map map = new HashMap();\n map.put(\"jsonrpc\", \"2.0\");\n\n if (id != null)\n map.put(\"id\", id);\n\n map.put(\"method\", method.getMethod());\n\n if (params != null && params.length > 0) {\n Function f = contract.getFunction(getIface(), getFunc());\n map.put(\"params\", f.marshalParams(this));\n }\n\n return map;\n }\n\n}",
"public class RpcResponse {\n\n private String id;\n private Object result;\n private RpcException error;\n\n /**\n * Creates a new RpcRequest and unmarshals the result/error fields based on the\n * map.\n *\n * @param req RpcRequest that this response correlates with\n * @param contract Contract that this request is associated with. Used to validate the\n * response result.\n * @param map JSON-RPC representation of RpcResponse with possible keys: 'id', 'result', 'error'\n */\n public RpcResponse(RpcRequest req, Contract contract, Map map) throws RpcException {\n unmarshal(contract.getFunction(req.getIface(), req.getFunc()), map);\n }\n\n /**\n * Creates a new RpcResponse associated with the given request and result object. This \n * represents a \"successful\" call.\n *\n * @param req RpcRequest that this response correlates with\n * @param result Java result from the request method invocation. This object should be the \n * native Java type, not the marshaled representation.\n */\n public RpcResponse(RpcRequest req, Object result) {\n setId(req);\n this.result = result;\n }\n\n /**\n * Creates a new RpcResponse that failed\n *\n * @param req RpcRequest that this response correlates with\n * @param error RpcException that describes the error that occurred when processing this request\n */\n public RpcResponse(RpcRequest req, RpcException error) {\n setId(req);\n this.error = error;\n }\n\n private void setId(RpcRequest req) {\n if (req != null)\n id = req.getId();\n }\n\n /**\n * Returns the id associated with this response. It is derived from the RpcRequest passed\n * to the constructor\n */\n public String getId() {\n return id;\n }\n\n /**\n * Returns the result associated with this response. This is the unmarshaled native\n * Java type\n */\n public Object getResult() {\n return result;\n }\n\n /**\n * Returns the RpcException associated with this response.\n */\n public RpcException getError() {\n return error;\n }\n\n /**\n * Marshals this response to a Map that can be serialized\n */\n @SuppressWarnings(\"unchecked\") \n public Map marshal() {\n HashMap map = new HashMap();\n map.put(\"jsonrpc\", \"2.0\");\n if (id != null)\n map.put(\"id\", id);\n if (error != null)\n map.put(\"error\", error.toMap());\n else\n map.put(\"result\", result);\n return map;\n }\n\n private void unmarshal(Function func, Map map) throws RpcException {\n id = (String)map.get(\"id\");\n \n Object res = map.get(\"result\");\n if (res != null) {\n result = func.unmarshalResult(res);\n }\n \n Object err = map.get(\"error\");\n if (err != null) {\n if (err instanceof Map) {\n Map errMap = (Map)err;\n int code = RpcException.Error.UNKNOWN.getCode();\n try { code = Integer.parseInt(String.valueOf(errMap.get(\"code\"))); }\n catch (Exception e) { }\n error = new RpcException(code, (String)errMap.get(\"message\"), errMap.get(\"data\"));\n }\n else {\n String msg = \"Invalid error in response. Expected Map. Got: \" + \n err.getClass().getName();\n throw RpcException.Error.INVALID_RESP.exc(msg);\n }\n }\n }\n\n @Override\n public String toString() {\n return \"RpcResponse: id=\" + id + \" error=\" + error + \" result=\" + result;\n }\n\n}",
"public class HttpTransport implements Transport {\n\n private String endpoint;\n private Serializer serializer;\n private Contract contract;\n private Map<String,String> headers;\n\n /**\n * Creates a new HttpTransport using an empty header list and the JacksonSerializer.\n *\n * @param endpoint URL of the Barrister server to consume\n * @throws IOException If there is a problem loading the IDL from the endpoint\n */\n public HttpTransport(String endpoint) throws IOException {\n this(endpoint, null, new JacksonSerializer());\n }\n\n /**\n * Creates a new HttpTransport. When this constructor is called, the Contract for the\n * given endpoint URL will be immediately requested.\n *\n * @param endpoint URL of the Barrister server to consume\n * @param headers HTTP headers to add to requests against this transport. For example,\n * \"Authorization\"\n * @param serializer Serializer to use with this transport\n * @throws IOException If there is a problem loading the IDL from the endpoint\n */\n public HttpTransport(String endpoint, Map<String,String> headers, Serializer serializer) \n throws IOException {\n\n this(endpoint, headers, serializer, null);\n }\n\n /**\n * Creates a new HttpTransport. When this constructor is called, the Contract for the\n * given endpoint URL will be immediately requested.\n *\n * @param endpoint URL of the Barrister server to consume\n * @param headers HTTP headers to add to requests against this transport. For example,\n * \"Authorization\"\n * @param serializer Serializer to use with this transport\n * @throws IOException If contract is null and there is a problem loading the IDL from the endpoint\n */\n public HttpTransport(String endpoint, Map<String,String> headers, Serializer serializer, Contract contract) \n throws IOException {\n\n if (headers == null) {\n headers = new HashMap<String,String>();\n }\n\n this.endpoint = endpoint;\n this.serializer = serializer;\n this.contract = contract;\n this.headers = headers;\n this.headers.put(\"Content-Type\", \"application/json\");\n\n if (contract == null) {\n loadContract();\n }\n }\n\n /**\n * Returns the HTTP headers associated with this HttpTransport. \n * This returns an immutable copy of the headers map, so its\n * contents may not be modified.\n */\n public Map<String,String> getHeaders() {\n return Collections.unmodifiableMap(headers);\n }\n\n /**\n * Returns the endpoint associated with this HttpTransport\n */\n public String getEndpoint() {\n return this.endpoint;\n }\n\n /**\n * Returns the Serializer associated with this HttpTransport\n */\n public Serializer getSerializer() {\n return this.serializer;\n }\n\n @SuppressWarnings(\"unchecked\")\n private void loadContract() throws IOException {\n InputStream is = null;\n try {\n RpcRequest req = new RpcRequest(\"1\", \"barrister-idl\", null);\n\n ByteArrayOutputStream bos = new ByteArrayOutputStream();\n serializer.write(req.marshal(contract), bos);\n bos.close();\n byte[] data = bos.toByteArray();\n\n is = requestRaw(data);\n Map map = serializer.readMap(is);\n if (map.get(\"error\") != null) {\n throw new IOException(\"Unable to load IDL from \" + endpoint + \" - \" +\n map.get(\"error\"));\n } \n else if (map.get(\"result\") == null) {\n throw new IOException(\"Unable to load IDL from \" + endpoint + \" - \" +\n \"result is null\");\n }\n else {\n this.contract = new Contract((java.util.List)map.get(\"result\"));\n }\n }\n catch (RpcException e) {\n throw new IOException(\"Unable to load IDL from \" + endpoint + \" - \" +\n e.getMessage());\n }\n finally {\n closeQuietly(is);\n }\n }\n\n /**\n * Returns the Contract associated with this transport. This is loaded\n * from the server endpoint in the constructor.\n */\n public Contract getContract() {\n return contract;\n }\n\n /**\n * Makes a RPC call via HTTP(S) to the remote server\n */\n public RpcResponse request(RpcRequest req) {\n InputStream is = null;\n try {\n ByteArrayOutputStream bos = new ByteArrayOutputStream();\n serializer.write(req.marshal(contract), bos);\n bos.close();\n byte[] data = bos.toByteArray();\n\n is = requestRaw(data);\n return unmarshal(req, serializer.readMap(is));\n }\n catch (RpcException e) {\n return new RpcResponse(req, e);\n }\n catch (IOException e) {\n String msg = \"IOException requesting \" + req.getMethod() + \n \" from: \" + endpoint + \" - \" + e.getMessage();\n RpcException exc = RpcException.Error.INTERNAL.exc(msg);\n return new RpcResponse(req, exc);\n }\n finally {\n closeQuietly(is);\n }\n }\n\n /**\n * Makes JSON-RPC batch request against the remote server as a single HTTP request.\n */\n @SuppressWarnings(\"unchecked\")\n public List<RpcResponse> request(List<RpcRequest> reqList) {\n List<RpcResponse> respList = new ArrayList<RpcResponse>();\n\n List<Map> marshaledReqs = new ArrayList<Map>();\n Map<String,RpcRequest> byReqId = new HashMap<String,RpcRequest>();\n for (RpcRequest req : reqList) {\n try {\n marshaledReqs.add(req.marshal(contract));\n byReqId.put(req.getId(), req);\n }\n catch (RpcException e) {\n respList.add(new RpcResponse(req, e));\n }\n }\n\n InputStream is = null;\n try {\n ByteArrayOutputStream bos = new ByteArrayOutputStream();\n serializer.write(marshaledReqs, bos);\n bos.close();\n byte[] data = bos.toByteArray();\n \n is = requestRaw(data);\n List<Map> responses = serializer.readList(is);\n for (Map map : responses) {\n String id = (String)map.get(\"id\");\n if (id != null) {\n RpcRequest req = byReqId.get(id);\n if (req == null) {\n // TODO: ?? log error?\n }\n else {\n byReqId.remove(id);\n respList.add(unmarshal(req, map));\n }\n }\n else {\n // TODO: ?? log error?\n }\n }\n\n if (byReqId.size() > 0) {\n for (RpcRequest req : byReqId.values()) {\n String msg = \"No response in batch for request \" + req.getId();\n RpcException exc = RpcException.Error.INVALID_RESP.exc(msg);\n RpcResponse resp = new RpcResponse(req, exc);\n respList.add(resp);\n }\n }\n }\n catch (IOException e) {\n String msg = \"IOException requesting batch \" +\n \" from: \" + endpoint + \" - \" + e.getMessage();\n RpcException exc = RpcException.Error.INTERNAL.exc(msg);\n respList.add(new RpcResponse(null, exc));\n }\n finally {\n closeQuietly(is);\n }\n \n return respList;\n }\n\n\t/**\n\t * Returns an URLConnection for the given URL. Subclasses may\n\t * override this and customize the connection with custom timeouts,\n\t * headers, etc.\n\t *\n\t * Headers passed into the constructor, and the Content-Length header,\n\t * will be added after this method is called.\n\t */\n\tpublic URLConnection createURLConnection(URL url) throws IOException {\n URLConnection conn = url.openConnection();\n\t\treturn conn;\n\t}\n\n private RpcResponse unmarshal(RpcRequest req, Map map) {\n try {\n return new RpcResponse(req, contract, map);\n }\n catch (RpcException e) {\n return new RpcResponse(req, e);\n }\n }\n\n private InputStream requestRaw(byte[] data) throws IOException {\n URL url = new URL(this.endpoint);\n URLConnection conn = createURLConnection(url);\n conn.setDoOutput(true);\n\n for (String key : headers.keySet()) {\n conn.addRequestProperty(key, headers.get(key));\n }\n\n conn.addRequestProperty(\"Content-Length\", String.valueOf(data.length));\n\n OutputStream os = null;\n try {\n os = conn.getOutputStream();\n os.write(data);\n os.flush();\n\n return conn.getInputStream();\n }\n finally {\n closeQuietly(os);\n }\n }\n\n private void closeQuietly(InputStream is) {\n if (is != null) {\n try {\n is.close();\n }\n catch (Exception e) { }\n }\n }\n\n private void closeQuietly(OutputStream os) {\n if (os != null) {\n try {\n os.close();\n }\n catch (Exception e) { }\n }\n }\n\n}",
"public class Contract extends BaseEntity {\n\n /**\n * Loads the IDL JSON file, parses it, and returns a Contract.\n * Uses the JacksonSerializer.\n *\n * @param idlJson Barrister IDL JSON file to load\n * @return Contract based on the IDL JSON file\n * @throws IOException If there is a problem reading the file, or if JSON \n * deserialization fails\n */\n public static Contract load(File idlJson) throws IOException {\n FileInputStream fis = new FileInputStream(idlJson);\n Contract c = load(fis);\n fis.close();\n return c;\n }\n\n /**\n * Loads the IDL JSON from the given stream, parses it, and returns a Contract.\n * Uses the JacksonSerializer.\n *\n * @param idlJson InputStream of the IDL JSON to parse\n * @return Contract based on the IDL JSON stream\n * @throws IOException if there is a problem reading the stream, or if JSON\n * deserialization fails\n */\n public static Contract load(InputStream idlJson) throws IOException {\n return load(idlJson, new JacksonSerializer());\n }\n\n /**\n * Loads the IDL from the given stream using an arbitrary serializer and returns\n * a Contract.\n *\n * @param idlJson Stream containing serialized IDL\n * @param ser Serializer implementation to use\n * @return Contract based on the IDL stream\n * @throws IOException if there is a problem reading the stream, or if deserialization fails\n */\n @SuppressWarnings(\"unchecked\")\n public static Contract load(InputStream idlJson, Serializer ser) throws IOException {\n return new Contract(ser.readList(idlJson));\n }\n\n //////////////////////////////\n\n private Map<String, Interface> interfaces;\n private Map<String, Struct> structs;\n private Map<String, Enum> enums;\n private Map<String, Object> meta;\n\n private List<Map<String,Object>> idl;\n\n private String packageName;\n private String nsPackageName;\n\n public Contract() {\n interfaces = new HashMap<String, Interface>();\n structs = new HashMap<String, Struct>();\n enums = new HashMap<String, Enum>();\n meta = new HashMap<String, Object>();\n }\n\n /**\n * Creates a new Contract based on the Map representation of the IDL\n */\n public Contract(List<Map<String,Object>> idl) {\n this();\n this.idl = idl;\n this.meta = new HashMap<String, Object>();\n\n for (Map<String,Object> e : idl) {\n String type = String.valueOf(e.get(\"type\"));\n if (type.equals(\"interface\")) {\n Interface i = new Interface(e);\n i.setContract(this);\n interfaces.put(i.getName(), i);\n }\n else if (type.equals(\"struct\")) {\n Struct s = new Struct(e);\n s.setContract(this);\n structs.put(s.getName(), s);\n }\n else if (type.equals(\"enum\")) {\n Enum en = new Enum(e);\n en.setContract(this);\n enums.put(en.getName(), en);\n }\n else if (type.equals(\"meta\")) {\n for (Object key : e.keySet()) {\n if (!key.toString().equals(\"type\")) {\n meta.put(key.toString(), e.get(key));\n }\n }\n }\n }\n }\n\n /**\n * Sets the Java package associated with this Contract. This is \n * used to resolve full generated Java class names when unmarshaling data\n * from requests.\n */\n public void setPackage(String pkgName) {\n this.packageName = pkgName;\n }\n \n /**\n * Returns the Java package associated with this Contract\n */\n public String getPackage() {\n return packageName;\n }\n\n /**\n * Sets the base Java package for namespaced entities associated with this Contract. \n * This is used instead of getPackage() for entities that are namespaced. \n */\n public void setNsPackage(String pkgName) {\n this.nsPackageName = pkgName;\n }\n \n /**\n * Returns the base Java package for namespaced entities associated with this Contract.\n * If no nsPackage is set, this method returns the same value as getPackage().\n */\n public String getNsPackage() {\n return (nsPackageName == null) ? getPackage() : nsPackageName;\n }\n\n /**\n * Returns a fully qualified class name for the given struct/enum/interface\n * name. If the name is namespaced, nsPackage is used. Otherise package is\n * used to prefix the name.\n */\n public String getClassNameForEntity(String name) {\n if (name.indexOf(\".\") > -1)\n return getNsPackage() + \".\" + name;\n else\n return getPackage() + \".\" + name;\n }\n\n /**\n * Returns the IDL associated with this Contract as passed to the constructor.\n */\n public List<Map<String,Object>> getIdl() {\n return idl;\n }\n\n /**\n * Returns values from the IDL \"meta\" element\n */\n public Map<String, Object> getMeta() {\n return meta;\n }\n\n /**\n * Returns the interfaces associated with this Contract. \n * Keys: interface name from IDL. Value: Interface instance.\n */\n public Map<String, Interface> getInterfaces() {\n return interfaces;\n }\n\n /**\n * Returns the structs associated with this Contract. \n * Keys: struct name from IDL. Value: Struct instance.\n */\n public Map<String, Struct> getStructs() {\n return structs;\n }\n\n /**\n * Returns all Structs that extend this Struct, and their\n * descendatnts, recursively.\n */\n public List<Struct> getStructDescendants(Struct struct) {\n return getStructDescendants(struct, new ArrayList<Struct>());\n }\n\n private List<Struct> getStructDescendants(Struct struct, List<Struct> list) {\n for (Struct s : structs.values()) {\n if (s.getExtends() != null && s.getExtends().equals(struct.getName())) {\n list.add(s);\n getStructDescendants(s, list);\n }\n }\n\n return list;\n }\n\n /**\n * Returns the enums associated with this Contract. \n * Keys: enum name from IDL. Value: Enum instance.\n */\n public Map<String, Enum> getEnums() {\n return enums;\n }\n\n /**\n * Returns the Function associated with the given interface and function name.\n *\n * @param iface Interface name\n * @param func Function name in the interface\n * @return Function that matches iface and func on this Contract\n * @throws RpcException If no Function matches\n */\n public Function getFunction(String iface, String func) throws RpcException {\n Interface i = interfaces.get(iface);\n if (i == null) {\n String msg = \"Interface '\" + iface + \"' not found\";\n throw RpcException.Error.METHOD_NOT_FOUND.exc(msg);\n }\n\n Function f = i.getFunction(func);\n if (f == null) {\n String msg = \"Function '\" + iface + \".\" + func + \"' not found\";\n throw RpcException.Error.METHOD_NOT_FOUND.exc(msg);\n }\n\n return f;\n }\n\n}",
"public class RpcException extends Exception {\n\n /**\n * Enum of JSON-RPC standard error types. Used to generate internal\n * errors.\n */\n public enum Error {\n INVALID_REQ(-32600), PARSE(-32700), METHOD_NOT_FOUND(-32601),\n INVALID_PARAMS(-32602), INTERNAL(-32603), \n UNKNOWN(-32000), INVALID_RESP(-32001);\n\n /////\n\n private int code;\n \n Error(int code) {\n this.code = code;\n }\n\n public int getCode() {\n return this.code;\n }\n\n public RpcException exc(String msg) {\n return new RpcException(code, msg);\n }\n\n }\n\n\n private int code;\n private String message;\n private Object data;\n\n /**\n * Creates a new RpcException\n *\n * @param code Error code\n * @param message Error message\n */\n public RpcException(int code, String message) {\n this(code, message, null);\n }\n\n /**\n * Creates a new RpcException\n *\n * @param code Error code\n * @param message Error message\n * @param data Additional error information. Please use primitives or Maps/Lists of \n * primitives\n */\n public RpcException(int code, String message, Object data) {\n this.code = code;\n this.message = message;\n this.data = data;\n }\n\n /**\n * Returns the error code\n */\n public int getCode() {\n return code;\n }\n\n /**\n * Returns the error message\n */\n public String getMessage() {\n return message;\n }\n\n /**\n * Returns the optional data \n */\n public Object getData() {\n return data;\n }\n\n /**\n * Used to marshal this exception to a Map suiteable for serialization to JSON\n */\n @SuppressWarnings(\"unchecked\")\n public Map toMap() {\n HashMap map = new HashMap();\n map.put(\"code\", code);\n map.put(\"message\", message);\n if (data != null)\n map.put(\"data\", data);\n return map;\n }\n\n @Override\n public String toString() {\n return \"RpcException: code=\" + code + \" message=\" + message +\n \" data=\" + data;\n }\n}",
"public class Batch implements Transport {\n\n private Transport child;\n private List<RpcRequest> reqList;\n private boolean sent;\n\n /**\n * Creates a new Batch\n *\n * @param child Underlying transport to send request with\n */\n public Batch(Transport child) {\n this.child = child;\n this.reqList = new ArrayList<RpcRequest>();\n this.sent = false;\n }\n\n /**\n * Returns contract associated with child Transport\n */\n public Contract getContract() {\n return child.getContract();\n }\n\n /**\n * Adds req to internal request list\n * \n * @param req Request to add to call batch\n * @return Always returns null\n * @throws IllegalStateException if batch has already been sent\n */\n public RpcResponse request(RpcRequest req) {\n checkSent();\n reqList.add(req);\n return null;\n }\n\n /**\n * Adds all requests in reqList to internal request list\n *\n * @param reqList Requests to add to call batch\n * @return Always returns null\n * @throws IllegalStateException if batch has already been sent\n */\n public List<RpcResponse> request(List<RpcRequest> reqList) {\n for (RpcRequest req : reqList) {\n this.reqList.add(req);\n }\n\n return null;\n }\n\n /**\n * Sends the batch request using the child Transport and returns\n * the responses. Responses will be in the same order as the requests they\n * correspond to.\n *\n * @return List of responses correlated to the requests in the batch\n * @throws IllegalStateException if batch has already been sent\n */\n public List<RpcResponse> send() {\n checkSent();\n sent = true;\n return child.request(reqList);\n }\n\n private void checkSent() {\n if (sent) {\n throw new IllegalStateException(\"Batch already sent!\");\n }\n }\n\n}"
] | import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.util.UUID;
import java.util.Map;
import java.util.HashMap;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonFactory;
import com.bitmechanic.barrister.RpcRequest;
import com.bitmechanic.barrister.RpcResponse;
import com.bitmechanic.barrister.HttpTransport;
import com.bitmechanic.barrister.Contract;
import com.bitmechanic.barrister.RpcException;
import com.bitmechanic.barrister.Batch; | package com.bitmechanic.barrister.conform;
public class Client {
// Usage:
//
// java com.bitmechanic.barrister.conform.Client path_to_conform.json output.file
//
public static void main(String argv[]) throws Exception {
new Client(argv[0], argv[1]);
}
PrintWriter out;
ObjectMapper mapper;
JsonFactory jsonFactory;
HttpTransport trans; | Contract con; | 3 |
SerCeMan/jnr-fuse | src/main/java/ru/serce/jnrfuse/FuseStubFS.java | [
"public class FileStat extends Struct {\n public static final int S_IFIFO = 0010000; // named pipe (fifo)\n public static final int S_IFCHR = 0020000; // character special\n public static final int S_IFDIR = 0040000; // directory\n public static final int S_IFBLK = 0060000; // block special\n public static final int S_IFREG = 0100000; // regular\n public static final int S_IFLNK = 0120000; // symbolic link\n public static final int S_IFSOCK = 0140000; // socket\n public static final int S_IFMT = 0170000; // file mask for type checks\n public static final int S_ISUID = 0004000; // set user id on execution\n public static final int S_ISGID = 0002000; // set group id on execution\n public static final int S_ISVTX = 0001000; // save swapped text even after use\n public static final int S_IRUSR = 0000400; // read permission, owner\n public static final int S_IWUSR = 0000200; // write permission, owner\n public static final int S_IXUSR = 0000100; // execute/search permission, owner\n public static final int S_IRGRP = 0000040; // read permission, group\n public static final int S_IWGRP = 0000020; // write permission, group\n public static final int S_IXGRP = 0000010; // execute/search permission, group\n public static final int S_IROTH = 0000004; // read permission, other\n public static final int S_IWOTH = 0000002; // write permission, other\n public static final int S_IXOTH = 0000001; // execute permission, other\n\n public static final int ALL_READ = S_IRUSR | S_IRGRP | S_IROTH;\n public static final int ALL_WRITE = S_IWUSR | S_IWGRP | S_IWOTH;\n public static final int S_IXUGO = S_IXUSR | S_IXGRP | S_IXOTH;\n\n public static boolean S_ISTYPE(int mode, int mask) {\n return (mode & S_IFMT) == mask;\n }\n\n public static boolean S_ISDIR(int mode) {\n return S_ISTYPE(mode, S_IFDIR);\n }\n\n public static boolean S_ISCHR(int mode) {\n return S_ISTYPE(mode, S_IFCHR);\n }\n\n public static boolean S_ISBLK(int mode) {\n return S_ISTYPE(mode, S_IFBLK);\n }\n\n public static boolean S_ISREG(int mode) {\n return S_ISTYPE(mode, S_IFREG);\n }\n\n public static boolean S_ISFIFO(int mode) {\n return S_ISTYPE(mode, S_IFIFO);\n }\n\n public static boolean S_ISLNK(int mode) {\n return S_ISTYPE(mode, S_IFLNK);\n }\n\n public FileStat(Runtime runtime) {\n super(runtime);\n if(Platform.IS_MAC) {\n// typedef __uint64_t\t__darwin_ino64_t;\t/* [???] Used for 64 bit inodes */\n// #define __DARWIN_STRUCT_STAT64 { \\\n// dev_t\t\tst_dev;\t\t\t/* [XSI] ID of device containing file */ \\\n// mode_t\t\tst_mode;\t\t/* [XSI] Mode of file (see below) */ \\\n// nlink_t\t\tst_nlink;\t\t/* [XSI] Number of hard links */ \\\n// __darwin_ino64_t st_ino;\t\t/* [XSI] File serial number */ \\\n// uid_t\t\tst_uid;\t\t\t/* [XSI] User ID of the file */ \\\n// gid_t\t\tst_gid;\t\t\t/* [XSI] Group ID of the file */ \\\n// dev_t\t\tst_rdev;\t\t/* [XSI] Device ID */ \\\n// __DARWIN_STRUCT_STAT64_TIMES \\\n// off_t\t\tst_size;\t\t/* [XSI] file size, in bytes */ \\\n// blkcnt_t\tst_blocks;\t\t/* [XSI] blocks allocated for file */ \\\n// blksize_t\tst_blksize;\t\t/* [XSI] optimal blocksize for I/O */ \\\n// __uint32_t\tst_flags;\t\t/* user defined flags for file */ \\\n// __uint32_t\tst_gen;\t\t\t/* file generation number */ \\\n// __int32_t\tst_lspare;\t\t/* RESERVED: DO NOT USE! */ \\\n// __int64_t\tst_qspare[2];\t\t/* RESERVED: DO NOT USE! */ \\\n// }\n// #define __DARWIN_STRUCT_STAT64_TIMES \\\n// struct timespec st_atimespec;\t\t/* time of last access */ \\\n// struct timespec st_mtimespec;\t\t/* time of last data modification */ \\\n// struct timespec st_ctimespec;\t\t/* time of last status change */ \\\n// struct timespec st_birthtime;\t/* time of file creation(birth) */\n st_dev = new dev_t();\n st_mode = new mode_t();\n st_nlink = new nlink_t();\n st_ino = new u_int64_t();\n st_uid = new uid_t();\n st_gid = new gid_t();\n st_rdev = new dev_t();\n st_atim = inner(new Timespec(getRuntime()));\n st_mtim = inner(new Timespec(getRuntime()));\n st_ctim = inner(new Timespec(getRuntime()));\n st_birthtime = inner(new Timespec(getRuntime()));\n st_size = new off_t();\n st_blocks = new blkcnt_t();\n st_blksize = new blksize_t();\n st_flags = new u_int32_t();\n st_gen = new u_int32_t();\n new int32_t();\n new int64_t();\n new int64_t();\n\n //graveyard\n pad1 = null;\n pad2 = null;\n __unused4 = null;\n __unused5 = null;\n __unused6 = null;\n } else if (Platform.IS_WINDOWS) {\n st_dev = new dev_t();\n st_ino = new u_int64_t();\n st_mode = new Signed32();\n st_nlink = new Signed16();\n st_uid = new uid_t();\n st_gid = new gid_t();\n st_rdev = new dev_t();\n st_size = new off_t();\n st_atim = inner(new Timespec(getRuntime()));\n st_mtim = inner(new Timespec(getRuntime()));\n st_ctim = inner(new Timespec(getRuntime()));\n st_blksize = new blksize_t();\n st_blocks = new Signed64();\n st_birthtime = inner(new Timespec(getRuntime()));\n\n // graveyard\n pad1 = null;\n pad2 = null;\n __unused4 = null;\n __unused5 = null;\n __unused6 = null;\n st_flags = null;\n st_gen = null;\n } else {\n st_dev = new dev_t();\n pad1 = IS_32_BIT ? new Unsigned16() : null;\n st_ino = new UnsignedLong();\n if (IS_32_BIT) {\n st_mode = new mode_t();\n st_nlink = new nlink_t();\n } else {\n st_nlink = new nlink_t();\n st_mode = new mode_t();\n }\n st_uid = new uid_t();\n st_gid = new gid_t();\n st_rdev = new dev_t();\n pad2 = IS_32_BIT ? new Unsigned16() : null;\n st_size = new SignedLong();\n st_blksize = new blksize_t();\n st_blocks = new blkcnt_t();\n st_atim = inner(new Timespec(getRuntime()));\n st_mtim = inner(new Timespec(getRuntime()));\n st_ctim = inner(new Timespec(getRuntime()));\n __unused4 = IS_64_BIT ? new Signed64() : null;\n __unused5 = IS_64_BIT ? new Signed64() : null;\n __unused6 = new Signed64();\n\n //graveyard\n st_birthtime = null;\n st_flags = null;\n st_gen = null;\n }\n }\n\n public final dev_t st_dev; /* Device. */\n private final Unsigned16 pad1;\n public final NumberField st_ino; /* File serial number.\t*/\n public final NumberField st_nlink; /* Link count. */\n public final NumberField st_mode; /* File mode. */\n public final uid_t st_uid; /* User ID of the file's owner.\t*/\n public final gid_t st_gid; /* Group ID of the file's group.*/\n public final dev_t st_rdev; /* Device number, if device. */\n private final Unsigned16 pad2;\n public final NumberField st_size; /* Size of file, in bytes. */\n public final blksize_t st_blksize; /* Optimal block size for I/O. */\n public final NumberField st_blocks; /* Number 512-byte blocks allocated. */\n public final Timespec st_atim; /* Time of last access. */\n public final Timespec st_mtim; /* Time of last modification. */\n public final Timespec st_ctim; /* Time of last status change. */\n public final Timespec st_birthtime;/* Time of file creation(birth) */\n\n public final Signed64 __unused4;\n public final Signed64 __unused5;\n public final Signed64 __unused6;\n\n /** MacOS specific */\n public final u_int32_t st_flags;\n public final u_int32_t st_gen;\n\n\n public static FileStat of(jnr.ffi.Pointer memory) {\n FileStat stat = new FileStat(Runtime.getSystemRuntime());\n stat.useMemory(memory);\n return stat;\n }\n}",
"public class Flock extends BaseStruct {\n\n public static final int LOCK_SH = 1; /* Shared lock. */\n public static final int LOCK_EX = 2; /* Exclusive lock. */\n public static final int LOCK_UN = 8; /* Unlock. */\n\n // lock types\n public static final int F_RDLCK = 0;\t/* Read lock. */\n public static final int F_WRLCK = 1;\t/* Write lock.\t*/\n public static final int F_UNLCK = 2;\t/* Remove lock.\t */\n\n protected Flock(jnr.ffi.Runtime runtime) {\n super(runtime);\n if (Platform.IS_MAC) {\n// struct flock {\n// off_t\tl_start;\t/* starting offset */\n// off_t\tl_len;\t\t/* len = 0 means until end of file */\n// pid_t\tl_pid;\t\t/* lock owner */\n// short\tl_type;\t\t/* lock type: read/write, etc. */\n// short\tl_whence;\t/* type of l_start */\n// };\n l_start = new __off64_t();\n l_len = new __off64_t();\n l_pid = new pid_t();\n l_type = new Signed16();\n l_whence = new Signed16();\n pad = null;\n } else if (Platform.IS_WINDOWS) {\n l_type = new Signed16();\n l_whence = new Signed16();\n l_start = new __off64_t();\n l_len = new __off64_t();\n l_pid = new pid_t();\n pad = null;\n } else {\n l_type = new Signed16();\n l_whence = new Signed16();\n l_start = new __off64_t();\n l_len = new __off64_t();\n l_pid = new pid_t();\n pad = Platform.IS_64_BIT ? new Padding(NativeType.UCHAR, 4) : null;\n }\n\n }\n\n public final Signed16 l_type; /* Type of lock: F_RDLCK, F_WRLCK, or F_UNLCK.\t*/\n public final Signed16 l_whence; /* Where `l_start' is relative to (like `lseek'). */\n public final __off64_t l_start; /* Offset where the lock begins. */\n public final __off64_t l_len; /* Size of the locked area; zero means until EOF. */\n public final pid_t l_pid; /* Process holding the lock. */\n private final Padding pad; // for alighnment to 32\n\n public static Flock of(jnr.ffi.Pointer pointer) {\n Flock flock = new Flock(jnr.ffi.Runtime.getSystemRuntime());\n flock.useMemory(pointer);\n return flock;\n }\n}",
"public class FuseBuf extends BaseStruct {\n protected FuseBuf(jnr.ffi.Runtime runtime) {\n super(runtime);\n }\n\n /**\n * Size of data in bytes\n */\n public final size_t size = new size_t();\n\n /**\n * Buffer flags\n */\n public final Enum<FuseBufFlags> flags = new Enum<>(FuseBufFlags.class);\n\n /**\n * Memory pointer\n * <p>\n * Used unless FUSE_BUF_IS_FD flag is set.\n */\n public final Pointer mem = new Pointer();\n\n /**\n * File descriptor\n * <p>\n * Used if FUSE_BUF_IS_FD flag is set.\n */\n public final Signed32 fd = new Signed32();\n\n /**\n * File position\n * <p>\n * Used if FUSE_BUF_FD_SEEK flag is set.\n */\n public final off_t pos = new off_t();\n\n public static FuseBuf of(jnr.ffi.Pointer pointer) {\n FuseBuf buf = new FuseBuf(jnr.ffi.Runtime.getSystemRuntime());\n buf.useMemory(pointer);\n return buf;\n }\n}",
"public enum FuseBufFlags implements EnumMapper.IntegerEnum {\n /**\n * Buffer contains a file descriptor\n * <p>\n * If this flag is set, the .fd field is valid, otherwise the\n * .mem fields is valid.\n */\n FUSE_BUF_IS_FD(1 << 1),\n\n /**\n * Seek on the file descriptor\n * <p>\n * If this flag is set then the .pos field is valid and is\n * used to seek to the given offset before performing\n * operation on file descriptor.\n */\n FUSE_BUF_FD_SEEK(1 << 2),\n\n /**\n * Retry operation on file descriptor\n * <p>\n * If this flag is set then retry operation on file descriptor\n * until .size bytes have been copied or an error or EOF is\n * detected.\n */\n FUSE_BUF_FD_RETRY(1 << 3),\n\n /**\n * JNR does not work without null value enum\n */\n NULL_VALUE(0);\n\n private final int value;\n\n FuseBufFlags(int value) {\n this.value = value;\n }\n\n /**\n * Special JNR method, see jnr.ffi.util.EnumMapper#getNumberValueMethod(java.lang.Class, java.lang.Class)\n */\n @Override\n public int intValue() {\n return value;\n }\n}",
"public class FuseFileInfo extends Struct {\n // TODO: padding seems to be broken, it must be bitfield-ed instead of char by char\n protected FuseFileInfo(jnr.ffi.Runtime runtime) {\n super(runtime);\n if(!Platform.IS_WINDOWS) {\n flags = new Signed32();\n fh_old = new UnsignedLong();\n direct_io = new Padding(NativeType.UCHAR, 1);\n keep_cache = new Padding(NativeType.UCHAR, 1);\n flush = new Padding(NativeType.UCHAR, 1);\n nonseekable = new Padding(NativeType.UCHAR, 1);\n flock_release = new Padding(NativeType.UCHAR, 1);\n padding = new Padding(NativeType.UCHAR, 3);\n fh = new u_int64_t();\n lock_owner = new u_int64_t();\n } else {\n flags = new Signed32();\n fh_old = new Unsigned32();\n new Signed32(); // writepage\n direct_io = new Padding(NativeType.UCHAR, 1);\n keep_cache = new Padding(NativeType.UCHAR, 1);\n flush = new Padding(NativeType.UCHAR, 1);\n nonseekable = new Padding(NativeType.UCHAR, 1);\n flock_release = new Padding(NativeType.UCHAR, 0);\n padding = new Padding(NativeType.UCHAR, 0);\n fh = new u_int64_t();\n lock_owner = new u_int64_t();\n }\n }\n\n /**\n * Open flags.\t Available in open() and release()\n *\n * @see jnr.constants.platform.OpenFlags\n */\n public final Signed32 flags;\n /**\n * Old file handle, don't use\n */\n public final NumberField fh_old;\n /**\n * Can be filled in by open, to use direct I/O on this file.\n */\n public final Padding direct_io;\n /**\n * Can be filled in by open, to indicate, that cached file data\n * need not be invalidated.\n */\n public final Padding keep_cache;\n /**\n * Indicates a flush operation. Set in flush operation, also\n * maybe set in highlevel lock operation and lowlevel release\n * operation.\n */\n public final Padding flush;\n\n /**\n * Can be filled in by open, to indicate that the file is not\n * seekable. Introduced in version 2.8\n */\n public final Padding nonseekable;\n /**\n * Indicates that flock locks for this file should be\n * released. If set, lock_owner shall contain a valid value.\n * May only be set in ->release(). Introduced in version\n * 2.9\n */\n public final Padding flock_release;\n /**\n * Padding. Do not use\n */\n public final Padding padding; // 27\n /**\n * File handle. May be filled in by filesystem in open().\n * Available in all other file operations\n */\n public final u_int64_t fh;\n /**\n * Lock owner id. Available in locking operations and flush\n */\n public final u_int64_t lock_owner;\n\n public static FuseFileInfo of(jnr.ffi.Pointer pointer) {\n FuseFileInfo fi = new FuseFileInfo(jnr.ffi.Runtime.getSystemRuntime());\n fi.useMemory(pointer);\n return fi;\n }\n}",
"public class FusePollhandle extends BaseStruct {\n protected FusePollhandle(jnr.ffi.Runtime runtime) {\n super(runtime);\n }\n\n public final Unsigned64 kh = new Unsigned64();\n // TODO struct fuse_chan *ch;\n public final Pointer ch = new Pointer();\n // TODO struct fuse_ll *f;\n public final Pointer f = new Pointer();\n\n public static FusePollhandle of(jnr.ffi.Pointer pointer) {\n FusePollhandle ph = new FusePollhandle(jnr.ffi.Runtime.getSystemRuntime());\n ph.useMemory(pointer);\n return ph;\n }\n}",
"public class Statvfs extends BaseStruct {\n /* Definitions for the flag in `f_flag'.*/\n public static final int ST_RDONLY = 1;\t\t/* Mount read-only. */\n public static final int ST_NOSUID = 2;\t\t/* Ignore suid and sgid bits. */\n public static final int ST_NODEV = 4;\t\t/* Disallow access to device special files. */\n public static final int ST_NOEXEC = 8;\t\t/* Disallow program execution. */\n public static final int ST_SYNCHRONOUS = 16;/* Writes are synced at once. */\n public static final int ST_MANDLOCK = 64;\t/* Allow mandatory locks on an FS. */\n public static final int ST_WRITE = 128;\t\t/* Write on file/directory/symlink. */\n public static final int ST_APPEND = 256;\t/* Append-only file. */\n public static final int ST_IMMUTABLE = 512;\t/* Immutable file. */\n public static final int ST_NOATIME = 1024;\t/* Do not update access times. */\n public static final int ST_NODIRATIME = 2048;/* Do not update directory access times. */\n public static final int ST_RELATIME = 4096;\t/* Update atime relative to mtime/ctime. */\n\n\n public Statvfs(jnr.ffi.Runtime runtime) {\n super(runtime);\n if (Platform.IS_WINDOWS) {\n f_bsize = new u_int64_t();\n f_frsize = new u_int64_t();\n f_blocks = new fsblkcnt64_t();\n f_bfree = new fsblkcnt64_t();\n f_bavail = new fsblkcnt64_t();\n f_files = new fsfilcnt64_t();\n f_ffree = new fsfilcnt64_t();\n f_favail = new fsfilcnt64_t();\n f_fsid = new u_int64_t();\n f_flag = new u_int64_t();\n f_namemax = new u_int64_t();\n f_unused = null;\n __f_spare = null;\n } else {\n f_bsize = new UnsignedLong();\n f_frsize = new UnsignedLong();\n f_blocks = new fsblkcnt64_t();\n f_bfree = new fsblkcnt64_t();\n f_bavail = new fsblkcnt64_t();\n f_files = new fsfilcnt64_t();\n f_ffree = new fsfilcnt64_t();\n f_favail = new fsfilcnt64_t();\n f_fsid = new UnsignedLong();\n f_unused = Platform.IS_32_BIT ? new Signed32() : null;\n f_flag = new UnsignedLong();\n f_namemax = new UnsignedLong();\n __f_spare = Platform.IS_MAC ? null : array(new Signed32[6]);\n }\n }\n\n public final NumberField f_bsize; /* file system block size */\n public final NumberField f_frsize; /* fragment size */\n public final fsblkcnt64_t f_blocks; /* size of fs in f_frsize units */\n public final fsblkcnt64_t f_bfree; /* # free blocks */\n public final fsblkcnt64_t f_bavail; /* # free blocks for non-root */\n public final fsfilcnt64_t f_files; /* # inodes */\n public final fsfilcnt64_t f_ffree; /* # free inodes */\n public final fsfilcnt64_t f_favail; /* # free inodes for non-root */\n public final NumberField f_fsid; /* file system ID */\n public final Signed32 f_unused;\n public final NumberField f_flag; /* mount flags */\n public final NumberField f_namemax; /* maximum filename length */\n public final Signed32[] __f_spare;\n\n\n public static Statvfs of(jnr.ffi.Pointer pointer) {\n Statvfs statvfs = new Statvfs(jnr.ffi.Runtime.getSystemRuntime());\n statvfs.useMemory(pointer);\n return statvfs;\n }\n}",
"public class Timespec extends BaseStruct {\n protected Timespec(jnr.ffi.Runtime runtime) {\n super(runtime);\n tv_sec = new time_t();\n if(!Platform.IS_WINDOWS) {\n tv_nsec = new SignedLong();\n } else {\n tv_nsec = new Signed64();\n }\n }\n\n public final time_t tv_sec; /* seconds */\n public final NumberField tv_nsec; /* nanoseconds */\n\n public static Timespec of(jnr.ffi.Pointer pointer) {\n Timespec timespec = new Timespec(jnr.ffi.Runtime.getSystemRuntime());\n timespec.useMemory(pointer);\n return timespec;\n }\n}"
] | import com.kenai.jffi.MemoryIO;
import jnr.ffi.*;
import jnr.ffi.Runtime;
import jnr.ffi.types.dev_t;
import jnr.ffi.types.gid_t;
import jnr.ffi.types.mode_t;
import jnr.ffi.types.off_t;
import jnr.ffi.types.size_t;
import jnr.ffi.types.u_int32_t;
import jnr.ffi.types.uid_t;
import ru.serce.jnrfuse.struct.FileStat;
import ru.serce.jnrfuse.struct.Flock;
import ru.serce.jnrfuse.struct.FuseBuf;
import ru.serce.jnrfuse.flags.FuseBufFlags;
import ru.serce.jnrfuse.struct.FuseBufvec;
import ru.serce.jnrfuse.struct.FuseFileInfo;
import ru.serce.jnrfuse.struct.FusePollhandle;
import ru.serce.jnrfuse.struct.Statvfs;
import ru.serce.jnrfuse.struct.Timespec; | @NotImplemented
public int write(String path, Pointer buf, @size_t long size, @off_t long offset, FuseFileInfo fi) {
return 0;
}
@Override
@NotImplemented
public int statfs(String path, Statvfs stbuf) {
return 0;
}
@Override
@NotImplemented
public int flush(String path, FuseFileInfo fi) {
return 0;
}
@Override
@NotImplemented
public int release(String path, FuseFileInfo fi) {
return 0;
}
@Override
@NotImplemented
public int fsync(String path, int isdatasync, FuseFileInfo fi) {
return 0;
}
@Override
@NotImplemented
public int setxattr(String path, String name, Pointer value, @size_t long size, int flags) {
return 0;
}
@Override
@NotImplemented
public int getxattr(String path, String name, Pointer value, @size_t long size) {
return 0;
}
@Override
@NotImplemented
public int listxattr(String path, Pointer list, @size_t long size) {
return 0;
}
@Override
@NotImplemented
public int removexattr(String path, String name) {
return 0;
}
@Override
@NotImplemented
public int opendir(String path, FuseFileInfo fi) {
return 0;
}
@Override
@NotImplemented
public int readdir(String path, Pointer buf, FuseFillDir filter, @off_t long offset, FuseFileInfo fi) {
return 0;
}
@Override
@NotImplemented
public int releasedir(String path, FuseFileInfo fi) {
return 0;
}
@Override
@NotImplemented
public int fsyncdir(String path, FuseFileInfo fi) {
return 0;
}
@Override
@NotImplemented
public Pointer init(Pointer conn) {
return null;
}
@Override
@NotImplemented
public void destroy(Pointer initResult) {
}
@Override
@NotImplemented
public int access(String path, int mask) {
return 0;
}
@Override
@NotImplemented
public int create(String path, @mode_t long mode, FuseFileInfo fi) {
return -ErrorCodes.ENOSYS();
}
@Override
@NotImplemented
public int ftruncate(String path, @off_t long size, FuseFileInfo fi) {
return truncate(path, size);
}
@Override
@NotImplemented
public int fgetattr(String path, FileStat stbuf, FuseFileInfo fi) {
return getattr(path, stbuf);
}
@Override
@NotImplemented
public int lock(String path, FuseFileInfo fi, int cmd, Flock flock) {
return -ErrorCodes.ENOSYS();
}
@Override
@NotImplemented | public int utimens(String path, Timespec[] timespec) { | 7 |
abego/treelayout | org.abego.treelayout.demo/src/main/java/org/abego/treelayout/demo/svg/SVGForTextInBoxTree.java | [
"public static String doc(String content) {\n\treturn String\n\t\t\t.format(\"<?xml version=\\\"1.0\\\" standalone=\\\"no\\\" ?>\\n\"\n\t\t\t\t\t+ \"<!DOCTYPE svg PUBLIC \\\"-//W3C//DTD SVG 20010904//EN\\\" \\\"http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd\\\">\\n\"\n\t\t\t\t\t+ \"%s\\n\", content);\n}",
"public static String line(String x1, String y1, String x2, String y2,\n\t\tString style) {\n\treturn String\n\t\t\t.format(\"<line x1=\\\"%s\\\" y1=\\\"%s\\\" x2=\\\"%s\\\" y2=\\\"%s\\\" style=\\\"%s\\\" />\\n\",\n\t\t\t\t\tx1, y1, x2, y2, style);\n}",
"public static String rect(String x, String y, String width, String height,\n\t\tString style, String extraAttributes) {\n\treturn String\n\t\t\t.format(\"<rect x=\\\"%s\\\" y=\\\"%s\\\" width=\\\"%s\\\" height=\\\"%s\\\" style=\\\"%s\\\" %s/>\\n\",\n\t\t\t\t\tx, y, width, height, style, extraAttributes);\n}",
"public static String svg(String width, String height, String content) {\n\treturn String\n\t\t\t.format(\"<svg width=\\\"%s\\\" height=\\\"%s\\\" xmlns=\\\"http://www.w3.org/2000/svg\\\" xmlns:xlink=\\\"http://www.w3.org/1999/xlink\\\">\\n\"\n\t\t\t\t\t+ \"%s\" + \"</svg>\\n\", width, height, content);\n}",
"public static String text(String x, String y, String style, String text) {\n\treturn String.format(\n\t\t\t\"<text x=\\\"%s\\\" y=\\\"%s\\\" style=\\\"%s\\\">\\n%s\\n</text>\\n\", x, y,\n\t\t\tstyle, text);\n}",
"public interface TreeForTreeLayout<TreeNode> {\n\n\t/**\n\t * Returns the the root of the tree.\n\t * <p>\n\t * Time Complexity: O(1)\n\t * \n\t * @return the root of the tree\n\t */\n\tTreeNode getRoot();\n\n\t/**\n\t * Tells if a node is a leaf in the tree.\n\t * <p>\n\t * Time Complexity: O(1)\n\t * \n\t * @param node \n\t * @return true iff node is a leaf in the tree, i.e. has no children.\n\t */\n\tboolean isLeaf(TreeNode node);\n\n\t/**\n\t * Tells if a node is a child of a given parentNode.\n\t * <p>\n\t * Time Complexity: O(1)\n\t * \n\t * @param node \n\t * @param parentNode \n\t * @return true iff the node is a child of the given parentNode\n\t */\n\tboolean isChildOfParent(TreeNode node, TreeNode parentNode);\n\n\t/**\n\t * Returns the children of a parent node.\n\t * <p>\n\t * Time Complexity: O(1)\n\t * \n\t * @param parentNode\n\t * [!isLeaf(parentNode)]\n\t * @return the children of the given parentNode, from first to last\n\t */\n\tIterable<TreeNode> getChildren(TreeNode parentNode);\n\n\t/**\n\t * Returns the children of a parent node, in reverse order.\n\t * <p>\n\t * Time Complexity: O(1)\n\t * \n\t * @param parentNode\n\t * [!isLeaf(parentNode)]\n\t * @return the children of given parentNode, from last to first\n\t */\n\tIterable<TreeNode> getChildrenReverse(TreeNode parentNode);\n\n\t/**\n\t * Returns the first child of a parent node.\n\t * <p>\n\t * Time Complexity: O(1)\n\t * \n\t * @param parentNode\n\t * [!isLeaf(parentNode)]\n\t * @return the first child of the parentNode\n\t */\n\tTreeNode getFirstChild(TreeNode parentNode);\n\n\t/**\n\t * Returns the last child of a parent node.\n\t * <p>\n\t * \n\t * Time Complexity: O(1)\n\t * \n\t * @param parentNode\n\t * [!isLeaf(parentNode)]\n\t * @return the last child of the parentNode\n\t */\n\tTreeNode getLastChild(TreeNode parentNode);\n}",
"public class TreeLayout<TreeNode> {\n\t/*\n\t * Differences between this implementation and original algorithm\n\t * --------------------------------------------------------------\n\t * \n\t * For easier reference the same names (or at least similar names) as in the\n\t * paper of Buchheim, Jünger, and Leipert are used in this\n\t * implementation. However in the external interface \"first\" and \"last\" are\n\t * used instead of \"left most\" and \"right most\". The implementation also\n\t * supports tree layouts with the root at the left (or right) side. In that\n\t * case using \"left most\" would refer to the \"top\" child, i.e. using \"first\"\n\t * is less confusing.\n\t * \n\t * Also the y coordinate is not the level but directly refers the y\n\t * coordinate of a level, taking node's height and gapBetweenLevels into\n\t * account. When the root is at the left or right side the y coordinate\n\t * actually becomes an x coordinate.\n\t * \n\t * Instead of just using a constant \"distance\" to calculate the position to\n\t * the next node we refer to the \"size\" (width or height) of the node and a\n\t * \"gapBetweenNodes\".\n\t */\n\n\t// ------------------------------------------------------------------------\n\t// tree\n\n\tprivate final TreeForTreeLayout<TreeNode> tree;\n\n\t/**\n\t * Returns the Tree the layout is created for.\n\t * \n\t * @return the Tree the layout is created for\n\t */\n\tpublic TreeForTreeLayout<TreeNode> getTree() {\n\t\treturn tree;\n\t}\n\n\t// ------------------------------------------------------------------------\n\t// nodeExtentProvider\n\n\tprivate final NodeExtentProvider<TreeNode> nodeExtentProvider;\n\n\t/**\n\t * Returns the {@link NodeExtentProvider} used by this {@link TreeLayout}.\n\t * \n\t * @return the {@link NodeExtentProvider} used by this {@link TreeLayout}\n\t */\n\tpublic NodeExtentProvider<TreeNode> getNodeExtentProvider() {\n\t\treturn nodeExtentProvider;\n\t}\n\n\tprivate double getNodeHeight(TreeNode node) {\n\t\treturn nodeExtentProvider.getHeight(node);\n\t}\n\n\tprivate double getNodeWidth(TreeNode node) {\n\t\treturn nodeExtentProvider.getWidth(node);\n\t}\n\n\tprivate double getWidthOrHeightOfNode(TreeNode treeNode, boolean returnWidth) {\n\t\treturn returnWidth ? getNodeWidth(treeNode) : getNodeHeight(treeNode);\n\t}\n\n\t/**\n\t * When the level changes in Y-axis (i.e. root location Top or Bottom) the\n\t * height of a node is its thickness, otherwise the node's width is its\n\t * thickness.\n\t * <p>\n\t * The thickness of a node is used when calculating the locations of the\n\t * levels.\n\t * \n\t * @param treeNode\n\t * @return\n\t */\n\tprivate double getNodeThickness(TreeNode treeNode) {\n\t\treturn getWidthOrHeightOfNode(treeNode, !isLevelChangeInYAxis());\n\t}\n\n\t/**\n\t * When the level changes in Y-axis (i.e. root location Top or Bottom) the\n\t * width of a node is its size, otherwise the node's height is its size.\n\t * <p>\n\t * The size of a node is used when calculating the distance between two\n\t * nodes.\n\t * \n\t * @param treeNode\n\t * @return\n\t */\n\tprivate double getNodeSize(TreeNode treeNode) {\n\t\treturn getWidthOrHeightOfNode(treeNode, isLevelChangeInYAxis());\n\t}\n\n\t// ------------------------------------------------------------------------\n\t// configuration\n\n\tprivate final Configuration<TreeNode> configuration;\n\n\t/**\n\t * Returns the Configuration used by this {@link TreeLayout}.\n\t * \n\t * @return the Configuration used by this {@link TreeLayout}\n\t */\n\tpublic Configuration<TreeNode> getConfiguration() {\n\t\treturn configuration;\n\t}\n\n\tprivate boolean isLevelChangeInYAxis() {\n\t\tLocation rootLocation = configuration.getRootLocation();\n\t\treturn rootLocation == Location.Top || rootLocation == Location.Bottom;\n\t}\n\n\tprivate int getLevelChangeSign() {\n\t\tLocation rootLocation = configuration.getRootLocation();\n\t\treturn rootLocation == Location.Bottom\n\t\t\t\t|| rootLocation == Location.Right ? -1 : 1;\n\t}\n\n\t// ------------------------------------------------------------------------\n\t// bounds\n\n\tprivate double boundsLeft = Double.MAX_VALUE;\n\tprivate double boundsRight = Double.MIN_VALUE;\n\tprivate double boundsTop = Double.MAX_VALUE;\n\tprivate double boundsBottom = Double.MIN_VALUE;\n\n\tprivate void updateBounds(TreeNode node, double centerX, double centerY) {\n\t\tdouble width = getNodeWidth(node);\n\t\tdouble height = getNodeHeight(node);\n\t\tdouble left = centerX - width / 2;\n\t\tdouble right = centerX + width / 2;\n\t\tdouble top = centerY - height / 2;\n\t\tdouble bottom = centerY + height / 2;\n\t\tif (boundsLeft > left) {\n\t\t\tboundsLeft = left;\n\t\t}\n\t\tif (boundsRight < right) {\n\t\t\tboundsRight = right;\n\t\t}\n\t\tif (boundsTop > top) {\n\t\t\tboundsTop = top;\n\t\t}\n\t\tif (boundsBottom < bottom) {\n\t\t\tboundsBottom = bottom;\n\t\t}\n\t}\n\n\t/**\n\t * Returns the bounds of the tree layout.\n\t * <p>\n\t * The bounds of a TreeLayout is the smallest rectangle containing the\n\t * bounds of all nodes in the layout. It always starts at (0,0).\n\t * \n\t * @return the bounds of the tree layout\n\t */\n\tpublic Rectangle2D getBounds() {\n\t\treturn new Rectangle2D.Double(0, 0, boundsRight - boundsLeft,\n\t\t\t\tboundsBottom - boundsTop);\n\t}\n\n\t// ------------------------------------------------------------------------\n\t// size of level\n\n\tprivate final List<Double> sizeOfLevel = new ArrayList<Double>();\n\n\tprivate void calcSizeOfLevels(TreeNode node, int level) {\n\t\tdouble oldSize;\n\t\tif (sizeOfLevel.size() <= level) {\n\t\t\tsizeOfLevel.add(Double.valueOf(0));\n\t\t\toldSize = 0;\n\t\t} else {\n\t\t\toldSize = sizeOfLevel.get(level);\n\t\t}\n\n\t\tdouble size = getNodeThickness(node);\n\t\tif (oldSize < size) {\n\t\t\tsizeOfLevel.set(level, size);\n\t\t}\n\n\t\tif (!tree.isLeaf(node)) {\n\t\t\tfor (TreeNode child : tree.getChildren(node)) {\n\t\t\t\tcalcSizeOfLevels(child, level + 1);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Returns the number of levels of the tree.\n\t * \n\t * @return [level > 0]\n\t */\n\tpublic int getLevelCount() {\n\t\treturn sizeOfLevel.size();\n\t}\n\n\t/**\n\t * Returns the size of a level.\n\t * <p>\n\t * When the root is located at the top or bottom the size of a level is the\n\t * maximal height of the nodes of that level. When the root is located at\n\t * the left or right the size of a level is the maximal width of the nodes\n\t * of that level.\n\t * \n\t * @param level \n\t * @return the size of the level [level >= 0 && level < levelCount]\n\t */\n\tpublic double getSizeOfLevel(int level) {\n\t\tcheckArg(level >= 0, \"level must be >= 0\");\n\t\tcheckArg(level < getLevelCount(), \"level must be < levelCount\");\n\n\t\treturn sizeOfLevel.get(level);\n\t}\n\n\t// ------------------------------------------------------------------------\n\t// NormalizedPosition\n\n\t/**\n\t * The algorithm calculates the position starting with the root at 0. I.e.\n\t * the left children will get negative positions. However we want the result\n\t * to be normalized to (0,0).\n\t * <p>\n\t * {@link NormalizedPosition} will normalize the position (given relative to\n\t * the root position), taking the current bounds into account. This way the\n\t * left most node bounds will start at x = 0, the top most node bounds at y\n\t * = 0.\n\t */\n\tprivate class NormalizedPosition extends Point2D {\n\t\tprivate double x_relativeToRoot;\n\t\tprivate double y_relativeToRoot;\n\n\t\tpublic NormalizedPosition(double x_relativeToRoot,\n\t\t\t\tdouble y_relativeToRoot) {\n\t\t\tsetLocation(x_relativeToRoot, y_relativeToRoot);\n\t\t}\n\n\t\t@Override\n\t\tpublic double getX() {\n\t\t\treturn x_relativeToRoot - boundsLeft;\n\t\t}\n\n\t\t@Override\n\t\tpublic double getY() {\n\t\t\treturn y_relativeToRoot - boundsTop;\n\t\t}\n\n\t\t@Override\n\t\t// never called from outside\n\t\tpublic void setLocation(double x_relativeToRoot, double y_relativeToRoot) {\n\t\t\tthis.x_relativeToRoot = x_relativeToRoot;\n\t\t\tthis.y_relativeToRoot = y_relativeToRoot;\n\t\t}\n\t}\n\n\t// ------------------------------------------------------------------------\n\t// The Algorithm\n\t\n\tprivate final boolean useIdentity;\n\n\tprivate final Map<TreeNode, Double> mod;\n\tprivate final Map<TreeNode, TreeNode> thread;\n\tprivate final Map<TreeNode, Double> prelim;\n\tprivate final Map<TreeNode, Double> change;\n\tprivate final Map<TreeNode, Double> shift;\n\tprivate final Map<TreeNode, TreeNode> ancestor;\n\tprivate final Map<TreeNode, Integer> number;\n\tprivate final Map<TreeNode, Point2D> positions;\n\n\tprivate double getMod(TreeNode node) {\n\t\tDouble d = mod.get(node);\n\t\treturn d != null ? d.doubleValue() : 0;\n\t}\n\n\tprivate void setMod(TreeNode node, double d) {\n\t\tmod.put(node, d);\n\t}\n\n\tprivate TreeNode getThread(TreeNode node) {\n\t\tTreeNode n = thread.get(node);\n\t\treturn n != null ? n : null;\n\t}\n\n\tprivate void setThread(TreeNode node, TreeNode thread) {\n\t\tthis.thread.put(node, thread);\n\t}\n\n\tprivate TreeNode getAncestor(TreeNode node) {\n\t\tTreeNode n = ancestor.get(node);\n\t\treturn n != null ? n : node;\n\t}\n\n\tprivate void setAncestor(TreeNode node, TreeNode ancestor) {\n\t\tthis.ancestor.put(node, ancestor);\n\t}\n\n\tprivate double getPrelim(TreeNode node) {\n\t\tDouble d = prelim.get(node);\n\t\treturn d != null ? d.doubleValue() : 0;\n\t}\n\n\tprivate void setPrelim(TreeNode node, double d) {\n\t\tprelim.put(node, d);\n\t}\n\n\tprivate double getChange(TreeNode node) {\n\t\tDouble d = change.get(node);\n\t\treturn d != null ? d.doubleValue() : 0;\n\t}\n\n\tprivate void setChange(TreeNode node, double d) {\n\t\tchange.put(node, d);\n\t}\n\n\tprivate double getShift(TreeNode node) {\n\t\tDouble d = shift.get(node);\n\t\treturn d != null ? d.doubleValue() : 0;\n\t}\n\n\tprivate void setShift(TreeNode node, double d) {\n\t\tshift.put(node, d);\n\t}\n\n\t/**\n\t * The distance of two nodes is the distance of the centers of both noded.\n\t * <p>\n\t * I.e. the distance includes the gap between the nodes and half of the\n\t * sizes of the nodes.\n\t * \n\t * @param v\n\t * @param w\n\t * @return the distance between node v and w\n\t */\n\tprivate double getDistance(TreeNode v, TreeNode w) {\n\t\tdouble sizeOfNodes = getNodeSize(v) + getNodeSize(w);\n\n\t\tdouble distance = sizeOfNodes / 2\n\t\t\t\t+ configuration.getGapBetweenNodes(v, w);\n\t\treturn distance;\n\t}\n\n\tprivate TreeNode nextLeft(TreeNode v) {\n\t\treturn tree.isLeaf(v) ? getThread(v) : tree.getFirstChild(v);\n\t}\n\n\tprivate TreeNode nextRight(TreeNode v) {\n\t\treturn tree.isLeaf(v) ? getThread(v) : tree.getLastChild(v);\n\t}\n\n\t/**\n\t * \n\t * @param node\n\t * [tree.isChildOfParent(node, parentNode)]\n\t * @param parentNode\n\t * parent of node\n\t * @return\n\t */\n\tprivate int getNumber(TreeNode node, TreeNode parentNode) {\n\t\tInteger n = number.get(node);\n\t\tif (n == null) {\n\t\t\tint i = 1;\n\t\t\tfor (TreeNode child : tree.getChildren(parentNode)) {\n\t\t\t\tnumber.put(child, i++);\n\t\t\t}\n\t\t\tn = number.get(node);\n\t\t}\n\n\t\treturn n.intValue();\n\t}\n\n\t/**\n\t * \n\t * @param vIMinus\n\t * @param v\n\t * @param parentOfV\n\t * @param defaultAncestor\n\t * @return the greatest distinct ancestor of vIMinus and its right neighbor\n\t * v\n\t */\n\tprivate TreeNode ancestor(TreeNode vIMinus, @SuppressWarnings(\"unused\") TreeNode v, TreeNode parentOfV,\n\t\t\tTreeNode defaultAncestor) {\n\t\tTreeNode ancestor = getAncestor(vIMinus);\n\n\t\t// when the ancestor of vIMinus is a sibling of v (i.e. has the same\n\t\t// parent as v) it is also the greatest distinct ancestor vIMinus and\n\t\t// v. Otherwise it is the defaultAncestor\n\n\t\treturn tree.isChildOfParent(ancestor, parentOfV) ? ancestor\n\t\t\t\t: defaultAncestor;\n\t}\n\n\tprivate void moveSubtree(TreeNode wMinus, TreeNode wPlus, TreeNode parent,\n\t\t\tdouble shift) {\n\n\t\tint subtrees = getNumber(wPlus, parent) - getNumber(wMinus, parent);\n\t\tsetChange(wPlus, getChange(wPlus) - shift / subtrees);\n\t\tsetShift(wPlus, getShift(wPlus) + shift);\n\t\tsetChange(wMinus, getChange(wMinus) + shift / subtrees);\n\t\tsetPrelim(wPlus, getPrelim(wPlus) + shift);\n\t\tsetMod(wPlus, getMod(wPlus) + shift);\n\t}\n\n\t/**\n\t * In difference to the original algorithm we also pass in the leftSibling\n\t * and the parent of v.\n\t * <p>\n\t * <b>Why adding the parameter 'parent of v' (parentOfV) ?</b>\n\t * <p>\n\t * In this method we need access to the parent of v. Not every tree\n\t * implementation may support efficient (i.e. constant time) access to it.\n\t * On the other hand the (only) caller of this method can provide this\n\t * information with only constant extra time.\n\t * <p>\n\t * Also we need access to the \"left most sibling\" of v. Not every tree\n\t * implementation may support efficient (i.e. constant time) access to it.\n\t * On the other hand the \"left most sibling\" of v is also the \"first child\"\n\t * of the parent of v. The first child of a parent node we can get in\n\t * constant time. As we got the parent of v we can so also get the\n\t * \"left most sibling\" of v in constant time.\n\t * <p>\n\t * <b>Why adding the parameter 'leftSibling' ?</b>\n\t * <p>\n\t * In this method we need access to the \"left sibling\" of v. Not every tree\n\t * implementation may support efficient (i.e. constant time) access to it.\n\t * However it is easy for the caller of this method to provide this\n\t * information with only constant extra time.\n\t * <p>\n\t * <p>\n\t * <p>\n\t * In addition these extra parameters avoid the need for\n\t * {@link TreeForTreeLayout} to include extra methods \"getParent\",\n\t * \"getLeftSibling\", or \"getLeftMostSibling\". This keeps the interface\n\t * {@link TreeForTreeLayout} small and avoids redundant implementations.\n\t * \n\t * @param v\n\t * @param defaultAncestor\n\t * @param leftSibling\n\t * [nullable] the left sibling v, if there is any\n\t * @param parentOfV\n\t * the parent of v\n\t * @return the (possibly changes) defaultAncestor\n\t */\n\tprivate TreeNode apportion(TreeNode v, TreeNode defaultAncestor,\n\t\t\tTreeNode leftSibling, TreeNode parentOfV) {\n\t\tTreeNode w = leftSibling;\n\t\tif (w == null) {\n\t\t\t// v has no left sibling\n\t\t\treturn defaultAncestor;\n\t\t}\n\t\t// v has left sibling w\n\n\t\t// The following variables \"v...\" are used to traverse the contours to\n\t\t// the subtrees. \"Minus\" refers to the left, \"Plus\" to the right\n\t\t// subtree. \"I\" refers to the \"inside\" and \"O\" to the outside contour.\n\t\tTreeNode vOPlus = v;\n\t\tTreeNode vIPlus = v;\n\t\tTreeNode vIMinus = w;\n\t\t// get leftmost sibling of vIPlus, i.e. get the leftmost sibling of\n\t\t// v, i.e. the leftmost child of the parent of v (which is passed\n\t\t// in)\n\t\tTreeNode vOMinus = tree.getFirstChild(parentOfV);\n\n\t\tDouble sIPlus = getMod(vIPlus);\n\t\tDouble sOPlus = getMod(vOPlus);\n\t\tDouble sIMinus = getMod(vIMinus);\n\t\tDouble sOMinus = getMod(vOMinus);\n\n\t\tTreeNode nextRightVIMinus = nextRight(vIMinus);\n\t\tTreeNode nextLeftVIPlus = nextLeft(vIPlus);\n\n\t\twhile (nextRightVIMinus != null && nextLeftVIPlus != null) {\n\t\t\tvIMinus = nextRightVIMinus;\n\t\t\tvIPlus = nextLeftVIPlus;\n\t\t\tvOMinus = nextLeft(vOMinus);\n\t\t\tvOPlus = nextRight(vOPlus);\n\t\t\tsetAncestor(vOPlus, v);\n\t\t\tdouble shift = (getPrelim(vIMinus) + sIMinus)\n\t\t\t\t\t- (getPrelim(vIPlus) + sIPlus)\n\t\t\t\t\t+ getDistance(vIMinus, vIPlus);\n\n\t\t\tif (shift > 0) {\n\t\t\t\tmoveSubtree(ancestor(vIMinus, v, parentOfV, defaultAncestor),\n\t\t\t\t\t\tv, parentOfV, shift);\n\t\t\t\tsIPlus = sIPlus + shift;\n\t\t\t\tsOPlus = sOPlus + shift;\n\t\t\t}\n\t\t\tsIMinus = sIMinus + getMod(vIMinus);\n\t\t\tsIPlus = sIPlus + getMod(vIPlus);\n\t\t\tsOMinus = sOMinus + getMod(vOMinus);\n\t\t\tsOPlus = sOPlus + getMod(vOPlus);\n\n\t\t\tnextRightVIMinus = nextRight(vIMinus);\n\t\t\tnextLeftVIPlus = nextLeft(vIPlus);\n\t\t}\n\n\t\tif (nextRightVIMinus != null && nextRight(vOPlus) == null) {\n\t\t\tsetThread(vOPlus, nextRightVIMinus);\n\t\t\tsetMod(vOPlus, getMod(vOPlus) + sIMinus - sOPlus);\n\t\t}\n\n\t\tif (nextLeftVIPlus != null && nextLeft(vOMinus) == null) {\n\t\t\tsetThread(vOMinus, nextLeftVIPlus);\n\t\t\tsetMod(vOMinus, getMod(vOMinus) + sIPlus - sOMinus);\n\t\t\tdefaultAncestor = v;\n\t\t}\n\t\treturn defaultAncestor;\n\t}\n\n\t/**\n\t * \n\t * @param v\n\t * [!tree.isLeaf(v)]\n\t */\n\tprivate void executeShifts(TreeNode v) {\n\t\tdouble shift = 0;\n\t\tdouble change = 0;\n\t\tfor (TreeNode w : tree.getChildrenReverse(v)) {\n\t\t\tchange = change + getChange(w);\n\t\t\tsetPrelim(w, getPrelim(w) + shift);\n\t\t\tsetMod(w, getMod(w) + shift);\n\t\t\tshift = shift + getShift(w) + change;\n\t\t}\n\t}\n\n\t/**\n\t * In difference to the original algorithm we also pass in the leftSibling\n\t * (see {@link #apportion(Object, Object, Object, Object)} for a\n\t * motivation).\n\t * \n\t * @param v\n\t * @param leftSibling\n\t * [nullable] the left sibling v, if there is any\n\t */\n\tprivate void firstWalk(TreeNode v, TreeNode leftSibling) {\n\t\tif (tree.isLeaf(v)) {\n\t\t\t// No need to set prelim(v) to 0 as the getter takes care of this.\n\n\t\t\tTreeNode w = leftSibling;\n\t\t\tif (w != null) {\n\t\t\t\t// v has left sibling\n\n\t\t\t\tsetPrelim(v, getPrelim(w) + getDistance(v, w));\n\t\t\t}\n\n\t\t} else {\n\t\t\t// v is not a leaf\n\n\t\t\tTreeNode defaultAncestor = tree.getFirstChild(v);\n\t\t\tTreeNode previousChild = null;\n\t\t\tfor (TreeNode w : tree.getChildren(v)) {\n\t\t\t\tfirstWalk(w, previousChild);\n\t\t\t\tdefaultAncestor = apportion(w, defaultAncestor, previousChild,\n\t\t\t\t\t\tv);\n\t\t\t\tpreviousChild = w;\n\t\t\t}\n\t\t\texecuteShifts(v);\n\t\t\tdouble midpoint = (getPrelim(tree.getFirstChild(v)) + getPrelim(tree\n\t\t\t\t\t.getLastChild(v))) / 2.0;\n\t\t\tTreeNode w = leftSibling;\n\t\t\tif (w != null) {\n\t\t\t\t// v has left sibling\n\n\t\t\t\tsetPrelim(v, getPrelim(w) + getDistance(v, w));\n\t\t\t\tsetMod(v, getPrelim(v) - midpoint);\n\n\t\t\t} else {\n\t\t\t\t// v has no left sibling\n\n\t\t\t\tsetPrelim(v, midpoint);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * In difference to the original algorithm we also pass in extra level\n\t * information.\n\t * \n\t * @param v\n\t * @param m\n\t * @param level\n\t * @param levelStart\n\t */\n\tprivate void secondWalk(TreeNode v, double m, int level, double levelStart) {\n\t\t// construct the position from the prelim and the level information\n\n\t\t// The rootLocation affects the way how x and y are changed and in what\n\t\t// direction.\n\t\tdouble levelChangeSign = getLevelChangeSign();\n\t\tboolean levelChangeOnYAxis = isLevelChangeInYAxis();\n\t\tdouble levelSize = getSizeOfLevel(level);\n\n\t\tdouble x = getPrelim(v) + m;\n\n\t\tdouble y;\n\t\tAlignmentInLevel alignment = configuration.getAlignmentInLevel();\n\t\tif (alignment == AlignmentInLevel.Center) {\n\t\t\ty = levelStart + levelChangeSign * (levelSize / 2);\n\t\t} else if (alignment == AlignmentInLevel.TowardsRoot) {\n\t\t\ty = levelStart + levelChangeSign * (getNodeThickness(v) / 2);\n\t\t} else {\n\t\t\ty = levelStart + levelSize - levelChangeSign\n\t\t\t\t\t* (getNodeThickness(v) / 2);\n\t\t}\n\n\t\tif (!levelChangeOnYAxis) {\n\t\t\tdouble t = x;\n\t\t\tx = y;\n\t\t\ty = t;\n\t\t}\n\n\t\tpositions.put(v, new NormalizedPosition(x, y));\n\n\t\t// update the bounds\n\t\tupdateBounds(v, x, y);\n\n\t\t// recurse\n\t\tif (!tree.isLeaf(v)) {\n\t\t\tdouble nextLevelStart = levelStart\n\t\t\t\t\t+ (levelSize + configuration.getGapBetweenLevels(level + 1))\n\t\t\t\t\t* levelChangeSign;\n\t\t\tfor (TreeNode w : tree.getChildren(v)) {\n\t\t\t\tsecondWalk(w, m + getMod(v), level + 1, nextLevelStart);\n\t\t\t}\n\t\t}\n\t}\n\n\t// ------------------------------------------------------------------------\n\t// nodeBounds\n\n\tprivate Map<TreeNode, Rectangle2D.Double> nodeBounds;\n\n\t/**\n\t * Returns the layout of the tree nodes by mapping each node of the tree to\n\t * its bounds (position and size).\n\t * <p>\n\t * For each rectangle x and y will be >= 0. At least one rectangle will have\n\t * an x == 0 and at least one rectangle will have an y == 0.\n\t * \n\t * @return maps each node of the tree to its bounds (position and size).\n\t */\n\tpublic Map<TreeNode, Rectangle2D.Double> getNodeBounds() {\n\t\tif (nodeBounds == null) {\n\t\t\tnodeBounds = this.useIdentity ? new IdentityHashMap<TreeNode, Rectangle2D.Double>()\n\t\t\t\t\t: new HashMap<TreeNode, Rectangle2D.Double>();\n\t\t\tfor (Entry<TreeNode, Point2D> entry : positions.entrySet()) {\n\t\t\t\tTreeNode node = entry.getKey();\n\t\t\t\tPoint2D pos = entry.getValue();\n\t\t\t\tdouble w = getNodeWidth(node);\n\t\t\t\tdouble h = getNodeHeight(node);\n\t\t\t\tdouble x = pos.getX() - w / 2;\n\t\t\t\tdouble y = pos.getY() - h / 2;\n\t\t\t\tnodeBounds.put(node, new Rectangle2D.Double(x, y, w, h));\n\t\t\t}\n\t\t}\n\t\treturn nodeBounds;\n\t}\n\n\t// ------------------------------------------------------------------------\n\t// constructor\n\n\t/**\n\t * Creates a TreeLayout for a given tree.\n\t * <p>\n\t * In addition to the tree the {@link NodeExtentProvider} and the\n\t * {@link Configuration} must be given.\n\t * \n * @param tree \n * @param nodeExtentProvider \n * @param configuration \n * @param useIdentity\n\t * [default: false] when true, identity (\"==\") is used instead of\n\t * equality (\"equals(...)\") when checking nodes. Within a tree\n\t * each node must only exist once (using this check).\n\t */\n\tpublic TreeLayout(TreeForTreeLayout<TreeNode> tree,\n\t\t\tNodeExtentProvider<TreeNode> nodeExtentProvider,\n\t\t\tConfiguration<TreeNode> configuration, boolean useIdentity) {\n\t\tthis.tree = tree;\n\t\tthis.nodeExtentProvider = nodeExtentProvider;\n\t\tthis.configuration = configuration;\n\t\tthis.useIdentity = useIdentity;\n\n\t\tif (this.useIdentity) {\n\t\t\tthis.mod = new IdentityHashMap<TreeNode, Double>();\n\t\t\tthis.thread = new IdentityHashMap<TreeNode, TreeNode>();\n\t\t\tthis.prelim = new IdentityHashMap<TreeNode, Double>();\n\t\t\tthis.change = new IdentityHashMap<TreeNode, Double>();\n\t\t\tthis.shift = new IdentityHashMap<TreeNode, Double>();\n\t\t\tthis.ancestor = new IdentityHashMap<TreeNode, TreeNode>();\n\t\t\tthis.number = new IdentityHashMap<TreeNode, Integer>();\n\t\t\tthis.positions = new IdentityHashMap<TreeNode, Point2D>();\n\t\t} else {\n\t\t\tthis.mod = new HashMap<TreeNode, Double>();\n\t\t\tthis.thread = new HashMap<TreeNode, TreeNode>();\n\t\t\tthis.prelim = new HashMap<TreeNode, Double>();\n\t\t\tthis.change = new HashMap<TreeNode, Double>();\n\t\t\tthis.shift = new HashMap<TreeNode, Double>();\n\t\t\tthis.ancestor = new HashMap<TreeNode, TreeNode>();\n\t\t\tthis.number = new HashMap<TreeNode, Integer>();\n\t\t\tthis.positions = new HashMap<TreeNode, Point2D>();\n\t\t}\n\t\t\n\t\t// No need to explicitly set mod, thread and ancestor as their getters\n\t\t// are taking care of the initial values. This avoids a full tree walk\n\t\t// through and saves some memory as no entries are added for\n\t\t// \"initial values\".\n\n\t\tTreeNode r = tree.getRoot();\n\t\tfirstWalk(r, null);\n\t\tcalcSizeOfLevels(r, 0);\n\t\tsecondWalk(r, -getPrelim(r), 0, 0);\n\t}\n\t\n\tpublic TreeLayout(TreeForTreeLayout<TreeNode> tree,\n\t\t\tNodeExtentProvider<TreeNode> nodeExtentProvider,\n\t\t\tConfiguration<TreeNode> configuration) {\n\t\tthis(tree, nodeExtentProvider, configuration, false);\n\t}\n\t\n\t// ------------------------------------------------------------------------\n\t// checkTree\n\n\tprivate void addUniqueNodes(Map<TreeNode,TreeNode> nodes, TreeNode newNode) {\n\t\tif (nodes.put(newNode,newNode) != null) {\n\t\t\tthrow new RuntimeException(String.format(\n\t\t\t\t\t\"Node used more than once in tree: %s\", newNode));\n\t\t}\n\t\tfor (TreeNode n : tree.getChildren(newNode)) {\n\t\t\taddUniqueNodes(nodes,n);\n\t\t}\n\t}\n\n\t/**\n\t * Check if the tree is a \"valid\" tree.\n\t * <p>\n\t * Typically you will use this method during development when you get an\n\t * unexpected layout from your trees.\n\t * <p>\n\t * The following checks are performed:\n\t * <ul>\n\t * <li>Each node must only occur once in the tree.</li>\n\t * </ul>\n\t */\n\tpublic void checkTree() {\n\t\tMap<TreeNode, TreeNode> nodes = this.useIdentity ? new IdentityHashMap<TreeNode, TreeNode>()\n\t\t\t\t:new HashMap<TreeNode,TreeNode>();\n\t\t\n\t\t// Traverse the tree and check if each node is only used once.\n\t\taddUniqueNodes(nodes,tree.getRoot());\n\t}\n\n\t// ------------------------------------------------------------------------\n\t// dumpTree\n\n\tprivate void dumpTree(PrintStream output, TreeNode node, int indent,\n\t\t\tDumpConfiguration dumpConfiguration) {\n\t\tStringBuilder sb = new StringBuilder();\n\t\tfor (int i = 0; i < indent; i++) {\n\t\t\tsb.append(dumpConfiguration.indent);\n\t\t}\n\n\t\tif (dumpConfiguration.includeObjectToString) {\n\t\t\tsb.append(\"[\");\n\t\t\tsb.append(node.getClass().getName() + \"@\"\n\t\t\t\t\t+ Integer.toHexString(node.hashCode()));\n\t\t\tif (node.hashCode() != System.identityHashCode(node)) {\n\t\t\t\tsb.append(\"/identityHashCode:\");\n\t\t\t\tsb.append(Integer.toHexString(System.identityHashCode(node)));\n\t\t\t}\n\t\t\tsb.append(\"]\");\n\t\t}\n\t\t\n\t\tsb.append(StringUtil.quote(node != null ? node.toString() : null));\n\t\t\n\t\tif (dumpConfiguration.includeNodeSize) {\n\t\t\tsb.append(\" (size: \");\n\t\t\tsb.append(getNodeWidth(node));\n\t\t\tsb.append(\"x\");\n\t\t\tsb.append(getNodeHeight(node));\n\t\t\tsb.append(\")\");\n\t\t}\n\t\t\n\t\toutput.println(sb.toString());\n\t\t\n\t\tfor (TreeNode n : tree.getChildren(node)) {\n\t\t\tdumpTree(output, n, indent + 1, dumpConfiguration);\n\t\t}\n\t}\n\n\tpublic static class DumpConfiguration {\n\t\t/**\n\t\t * The text used to indent the output per level.\n\t\t */\n\t\tpublic final String indent;\n\t\t/**\n\t\t * When true the dump also includes the size of each node, otherwise\n\t\t * not.\n\t\t */\n\t\tpublic final boolean includeNodeSize;\n\t\t/**\n\t\t * When true, the text as returned by {@link Object#toString()}, is\n\t\t * included in the dump, in addition to the text returned by the\n\t\t * possibly overridden toString method of the node. When the hashCode\n\t\t * method is overridden the output will also include the\n\t\t * \"identityHashCode\".\n\t\t */\n\t\tpublic final boolean includeObjectToString;\n\n\t\t/**\n\t\t * \n\t\t * @param indent [default: \" \"]\n\t\t * @param includeNodeSize [default: false]\n\t\t * @param includePointer [default: false]\n\t\t */\n\t\tpublic DumpConfiguration(String indent, boolean includeNodeSize,\n\t\t\t\tboolean includePointer) {\n\t\t\tthis.indent = indent;\n\t\t\tthis.includeNodeSize = includeNodeSize;\n\t\t\tthis.includeObjectToString = includePointer;\n\t\t}\n\t\t\n\t\tpublic DumpConfiguration() {\n\t\t\tthis(\" \",false,false);\n\t\t}\n\t}\n\t\n\t/**\n\t * Prints a dump of the tree to the given printStream, using the node's\n\t * \"toString\" method.\n\t * \n\t * @param printStream \n\t * @param dumpConfiguration\n\t * [default: new DumpConfiguration()]\n\t */\n\tpublic void dumpTree(PrintStream printStream, DumpConfiguration dumpConfiguration) {\n\t\tdumpTree(printStream,tree.getRoot(),0, dumpConfiguration);\n\t}\n\n\tpublic void dumpTree(PrintStream printStream) {\n\t\tdumpTree(printStream,new DumpConfiguration());\n\t}\n}",
"public class TextInBox {\n\n\tpublic final String text;\n\tpublic final int height;\n\tpublic final int width;\n\n\tpublic TextInBox(String text, int width, int height) {\n\t\tthis.text = text;\n\t\tthis.width = width;\n\t\tthis.height = height;\n\t}\n}"
] | import static org.abego.treelayout.demo.svg.SVGUtil.line;
import static org.abego.treelayout.demo.svg.SVGUtil.rect;
import static org.abego.treelayout.demo.svg.SVGUtil.svg;
import static org.abego.treelayout.demo.svg.SVGUtil.text;
import java.awt.Dimension;
import java.awt.geom.Rectangle2D;
import org.abego.treelayout.TreeForTreeLayout;
import org.abego.treelayout.TreeLayout;
import org.abego.treelayout.demo.TextInBox;
import static org.abego.treelayout.demo.svg.SVGUtil.doc; | /*
* [The "BSD license"]
* Copyright (c) 2011, abego Software GmbH, Germany (http://www.abego.org)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the abego Software GmbH nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package org.abego.treelayout.demo.svg;
/**
* Generates SVG for a given {@link TreeLayout} of {@link TextInBox} nodes.
* <p>
*
* @author Udo Borkowski ([email protected])
*/
public class SVGForTextInBoxTree {
private final TreeLayout<TextInBox> treeLayout;
private String svgText;
private TreeForTreeLayout<TextInBox> getTree() {
return treeLayout.getTree();
}
private Iterable<TextInBox> getChildren(TextInBox parent) {
return getTree().getChildren(parent);
}
private Rectangle2D.Double getBoundsOfNode(TextInBox node) {
return treeLayout.getNodeBounds().get(node);
}
/**
* @param treeLayout the {@link TreeLayout} to be rendered as SVG
*/
public SVGForTextInBoxTree(TreeLayout<TextInBox> treeLayout) {
this.treeLayout = treeLayout;
}
// -------------------------------------------------------------------
// generating
private void generateEdges(StringBuilder result, TextInBox parent) {
if (!getTree().isLeaf(parent)) {
Rectangle2D.Double b1 = getBoundsOfNode(parent);
double x1 = b1.getCenterX();
double y1 = b1.getCenterY();
for (TextInBox child : getChildren(parent)) {
Rectangle2D.Double b2 = getBoundsOfNode(child); | result.append(line(x1, y1, b2.getCenterX(), b2.getCenterY(), | 1 |
jjhesk/LoyalNativeSlider | testApp/src/main/java/com/hkm/loyalns/demos/ExampleClassic.java | [
"public class DataProvider {\n public static HashMap<String, Integer> getFileSrcHorizontal() {\n HashMap<String, Integer> file_maps = new HashMap<String, Integer>();\n file_maps.put(\"Hannibal\", R.drawable.hannibal);\n file_maps.put(\"Big Bang Theory\", R.drawable.bigbang);\n file_maps.put(\"House of Cards\", R.drawable.house);\n file_maps.put(\"Game of Thrones\", R.drawable.game_of_thrones);\n return file_maps;\n }\n\n public static HashMap<String, String> getDataUrlSource() {\n HashMap<String, String> url_maps = new HashMap<String, String>();\n url_maps.put(\"Hannibal\", \"http://static2.hypable.com/wp-content/uploads/2013/12/hannibal-season-2-release-date.jpg\");\n url_maps.put(\"Big Bang Theory\", \"http://tvfiles.alphacoders.com/100/hdclearart-10.png\");\n url_maps.put(\"House of Cards\", \"http://cdn3.nflximg.net/images/3093/2043093.jpg\");\n url_maps.put(\"Game of Thrones\", \"http://images.boomsbeat.com/data/images/full/19640/game-of-thrones-season-4-jpg.jpg\");\n return url_maps;\n }\n\n public static HashMap<String, String> getVerticalDataSrc() {\n\n HashMap<String, String> file_maps = new HashMap<String, String>();\n file_maps.put(\"Choro Q N64\", \"file:///android_asset/q65.jpg\");\n file_maps.put(\"Choro 4 HQ PS2\", \"file:///android_asset/q66.jpg\");\n file_maps.put(\"Choro Rainbow Wings\", \"file:///android_asset/q67.jpg\");\n file_maps.put(\"Choro Q Boat Race\", \"file:///android_asset/q68.jpg\");\n return file_maps;\n\n }\n\n public static HashMap<String, String> getSingle() {\n HashMap<String, String> file_maps = new HashMap<String, String>();\n file_maps.put(\"Big Bang Theory\", \"http://tvfiles.alphacoders.com/100/hdclearart-10.png\");\n return file_maps;\n\n }\n\n public static Map.Entry<String, String> getRandomSingle() {\n int total = getVerticalDataSrc().size();\n Random n = new Random();\n int out = n.nextInt(total);\n LinkedHashMap<String, String> f = new LinkedHashMap<>(getVerticalDataSrc());\n final Map.Entry<String, String>[] test = new Map.Entry[total];\n f.entrySet().toArray(test);\n return test[out];\n }\n\n}",
"public abstract class BaseApp extends AppCompatActivity implements BaseSliderView.OnSliderClickListener, ViewPagerEx.OnPageChangeListener {\n @Override\n protected void onStop() {\n // To prevent a memory leak on rotation, make sure to call stopAutoCycle() on the slider before activity or fragment is destroyed\n mDemoSlider.stopAutoCycle();\n super.onStop();\n }\n\n protected SliderLayout mDemoSlider;\n protected RelativeLayout mFrameMain;\n protected boolean numbered = false;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(getActivityMainLayoutId());\n mDemoSlider = (SliderLayout) findViewById(R.id.slider);\n mFrameMain = (RelativeLayout) findViewById(R.id.sliderframe);\n setupSlider();\n }\n\n @LayoutRes\n protected int getActivityMainLayoutId() {\n return R.layout.main_slider;\n }\n\n protected abstract void setupSlider();\n\n @Override\n public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {\n }\n\n @Override\n public void onPageSelected(int position) {\n Log.d(\"Slider Demo\", \"Page Changed: \" + position);\n }\n\n @Override\n public void onPageScrollStateChanged(int state) {\n }\n}",
"public class CustomNumberView extends AdvancedTextSliderView<TextView, ImageView> {\n\n public CustomNumberView(Context context) {\n super(context);\n }\n\n @Override\n protected int renderedLayoutTextBanner() {\n return R.layout.item_slide_feature_banner;\n }\n}",
"public class NumZero extends NumContainer<TextView> {\n public NumZero(Context c) {\n super(c, R.layout.numfield);\n }\n}",
"public class TransformerAdapter extends BaseAdapter{\n private Context mContext;\n public TransformerAdapter(Context context) {\n mContext = context;\n }\n\n @Override\n public int getCount() {\n return TransformerL.values().length;\n }\n\n @Override\n public Object getItem(int position) {\n return TransformerL.values()[position].toString();\n }\n\n @Override\n public long getItemId(int position) {\n return position;\n }\n\n @Override\n public View getView(int position, View convertView, ViewGroup parent) {\n TextView t = (TextView)LayoutInflater.from(mContext).inflate(R.layout.item,null);\n t.setText(getItem(position).toString());\n return t;\n }\n}",
"public class DescriptionAnimation implements BaseAnimationInterface {\n\n private int time_threadhold = 400;\n private TimeInterpolator animation_behavior;\n private Handler handler = new Handler();\n\n /**\n * @param animation_behavior the interpolator behavior\n */\n @TargetApi(Build.VERSION_CODES.LOLLIPOP_MR1)\n public DescriptionAnimation(BaseInterpolator animation_behavior) {\n this.animation_behavior = animation_behavior;\n }\n\n /**\n * @param min_sec additional setting minute second that controls the time threadhold between each slide\n * @param animation_behavior the interpolator behavior\n */\n @TargetApi(Build.VERSION_CODES.LOLLIPOP_MR1)\n public DescriptionAnimation(int min_sec, BaseInterpolator animation_behavior) {\n this.time_threadhold = min_sec;\n this.animation_behavior = animation_behavior;\n }\n\n /**\n * @param min_sec additional setting minute second that controls the time threadhold between each slide\n */\n public DescriptionAnimation(int min_sec) {\n this.time_threadhold = min_sec;\n }\n\n public DescriptionAnimation() {\n\n }\n\n @Override\n public void onPrepareCurrentItemLeaveScreen(View current) {\n frame_disappear(current);\n }\n\n /**\n * When next item is coming to show, let's hide the description layout.\n *\n * @param next view\n */\n @Override\n public void onPrepareNextItemShowInScreen(final View next) {\n frame_disappear(next);\n }\n\n protected void frame_disappear(View next) {\n int startm = layoutCounts(next);\n if (startm == 1) {\n View descriptionLayout = next.findViewById(R.id.ns_desc_frame);\n if (descriptionLayout != null) descriptionLayout.setVisibility(View.INVISIBLE);\n } else {\n for (int n = 1; n < startm; n++) {\n getFrameLayoutDescriptionView(next, n).setVisibility(View.INVISIBLE);\n }\n }\n }\n\n @Override\n public void onCurrentItemDisappear(View view) {\n\n }\n\n /**\n * When next item show in ViewPagerEx, let's make an animation to show the\n * description layout.\n *\n * @param view view\n */\n @TargetApi(Build.VERSION_CODES.HONEYCOMB)\n @Override\n public void onNextItemAppear(final View view) {\n int startm = layoutCounts(view);\n if (startm == 1) {\n View descriptionLayout = view.findViewById(R.id.ns_desc_frame);\n workOnTarget(descriptionLayout);\n } else {\n for (int n = 1; n < startm; n++) {\n final int h = n;\n handler.postDelayed(new Runnable() {\n @Override\n public void run() {\n workOnTarget(getFrameLayoutDescriptionView(view, h));\n }\n }, getDelayThreadHold(n - 1));\n }\n }\n\n }\n\n private int layoutCounts(View view) {\n int startm = 1;\n while (hasFrame(view, startm)) {\n startm++;\n }\n\n return startm;\n }\n\n private int getDelayThreadHold(int i) {\n return i * time_threadhold;\n }\n\n protected boolean hasFrame(View view, int i) {\n int Id = view.getContext().getResources().getIdentifier(\"ns_display_i_s\" + i, \"id\", view.getContext().getPackageName());\n return view.findViewById(Id) != null;\n }\n\n protected View getFrameLayoutDescriptionView(View view, int i) {\n int Id = view.getContext().getResources().getIdentifier(\"ns_display_i_s\" + i, \"id\", view.getContext().getPackageName());\n View descriptionLayout = view.findViewById(Id).findViewById(R.id.ns_desc_frame);\n return descriptionLayout;\n }\n\n @TargetApi(Build.VERSION_CODES.HONEYCOMB)\n protected void workOnTarget(@Nullable View descriptionLayout) {\n if (descriptionLayout == null) return;\n float layoutY = ViewCompat.getY(descriptionLayout);\n descriptionLayout.setVisibility(View.VISIBLE);\n ValueAnimator animator = ObjectAnimator.ofFloat(\n descriptionLayout,\n \"y\",\n (float) (layoutY + descriptionLayout.getHeight()),\n layoutY)\n .setDuration(500);\n\n if (animation_behavior != null) {\n animator.setInterpolator(animation_behavior);\n }\n animator.start();\n }\n}",
"public class PagerIndicator extends LinearLayout implements ViewPagerEx.OnPageChangeListener {\n\n private Context mContext;\n\n /**\n * bind this Indicator with {@link com.hkm.slider.Tricks.ViewPagerEx}\n */\n private ViewPagerEx mPager;\n\n /**\n * Variable to remember the previous selected indicator.\n */\n private ImageView mPreviousSelectedIndicator;\n\n /**\n * Previous selected indicator position.\n */\n private int mPreviousSelectedPosition;\n\n /**\n * Custom selected indicator style resource id.\n */\n private int mUserSetUnSelectedIndicatorResId;\n\n\n /**\n * Custom unselected indicator style resource id.\n */\n private int mUserSetSelectedIndicatorResId;\n\n private Drawable mSelectedDrawable;\n private Drawable mUnselectedDrawable;\n\n /**\n * This value is from {@link SliderAdapter} getRealCount() represent\n * /\n * the indicator count that we should draw.\n */\n private int mItemCount = 0;\n\n private Shape mIndicatorShape = Shape.Oval;\n\n private IndicatorVisibility mVisibility = IndicatorVisibility.Visible;\n\n private int mDefaultSelectedColor;\n private int mDefaultUnSelectedColor;\n\n private float mDefaultSelectedWidth;\n private float mDefaultSelectedHeight;\n\n private float mDefaultUnSelectedWidth;\n private float mDefaultUnSelectedHeight;\n\n public enum IndicatorVisibility {\n Visible,\n Invisible\n }\n\n private GradientDrawable mUnSelectedGradientDrawable;\n private GradientDrawable mSelectedGradientDrawable;\n\n private LayerDrawable mSelectedLayerDrawable;\n private LayerDrawable mUnSelectedLayerDrawable;\n\n private float mPadding_left;\n private float mPadding_right;\n private float mPadding_top;\n private float mPadding_bottom;\n\n private float mSelectedPadding_Left;\n private float mSelectedPadding_Right;\n private float mSelectedPadding_Top;\n private float mSelectedPadding_Bottom;\n\n private float mUnSelectedPadding_Left;\n private float mUnSelectedPadding_Right;\n private float mUnSelectedPadding_Top;\n private float mUnSelectedPadding_Bottom;\n\n /**\n * Put all the indicators into a ArrayList, so we can remove them easily.\n */\n private ArrayList<ImageView> mIndicators = new ArrayList<ImageView>();\n\n\n public PagerIndicator(Context context) {\n this(context, null);\n }\n\n public PagerIndicator(Context context, AttributeSet attrs) {\n super(context, attrs);\n\n mContext = context;\n\n final TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.PagerIndicator, 0, 0);\n\n int visibility = attributes.getInt(R.styleable.PagerIndicator_visibility, IndicatorVisibility.Visible.ordinal());\n\n for (IndicatorVisibility v : IndicatorVisibility.values()) {\n if (v.ordinal() == visibility) {\n mVisibility = v;\n break;\n }\n }\n\n int shape = attributes.getInt(R.styleable.PagerIndicator_shape, Shape.Oval.ordinal());\n for (Shape s : Shape.values()) {\n if (s.ordinal() == shape) {\n mIndicatorShape = s;\n break;\n }\n }\n\n mUserSetSelectedIndicatorResId = attributes.getResourceId(R.styleable.PagerIndicator_selected_drawable,\n 0);\n mUserSetUnSelectedIndicatorResId = attributes.getResourceId(R.styleable.PagerIndicator_unselected_drawable,\n 0);\n\n mDefaultSelectedColor = attributes.getColor(R.styleable.PagerIndicator_selected_color,\n ContextCompat.getColor(mContext, R.color.default_nsl_light));\n mDefaultUnSelectedColor = attributes.getColor(R.styleable.PagerIndicator_unselected_color,\n ContextCompat.getColor(mContext, R.color.default_nsl_dark));\n\n mDefaultSelectedWidth = attributes.getDimension(R.styleable.PagerIndicator_selected_width, (int) pxFromDp(6));\n mDefaultSelectedHeight = attributes.getDimensionPixelSize(R.styleable.PagerIndicator_selected_height, (int) pxFromDp(6));\n\n mDefaultUnSelectedWidth = attributes.getDimensionPixelSize(R.styleable.PagerIndicator_unselected_width, (int) pxFromDp(6));\n mDefaultUnSelectedHeight = attributes.getDimensionPixelSize(R.styleable.PagerIndicator_unselected_height, (int) pxFromDp(6));\n\n mSelectedGradientDrawable = new GradientDrawable();\n mUnSelectedGradientDrawable = new GradientDrawable();\n\n mPadding_left = attributes.getDimensionPixelSize(R.styleable.PagerIndicator_padding_left, (int) pxFromDp(3));\n mPadding_right = attributes.getDimensionPixelSize(R.styleable.PagerIndicator_padding_right, (int) pxFromDp(3));\n mPadding_top = attributes.getDimensionPixelSize(R.styleable.PagerIndicator_padding_top, (int) pxFromDp(0));\n mPadding_bottom = attributes.getDimensionPixelSize(R.styleable.PagerIndicator_padding_bottom, (int) pxFromDp(0));\n\n mSelectedPadding_Left = attributes.getDimensionPixelSize(R.styleable.PagerIndicator_selected_padding_left, (int) mPadding_left);\n mSelectedPadding_Right = attributes.getDimensionPixelSize(R.styleable.PagerIndicator_selected_padding_right, (int) mPadding_right);\n mSelectedPadding_Top = attributes.getDimensionPixelSize(R.styleable.PagerIndicator_selected_padding_top, (int) mPadding_top);\n mSelectedPadding_Bottom = attributes.getDimensionPixelSize(R.styleable.PagerIndicator_selected_padding_bottom, (int) mPadding_bottom);\n\n mUnSelectedPadding_Left = attributes.getDimensionPixelSize(R.styleable.PagerIndicator_unselected_padding_left, (int) mPadding_left);\n mUnSelectedPadding_Right = attributes.getDimensionPixelSize(R.styleable.PagerIndicator_unselected_padding_right, (int) mPadding_right);\n mUnSelectedPadding_Top = attributes.getDimensionPixelSize(R.styleable.PagerIndicator_unselected_padding_top, (int) mPadding_top);\n mUnSelectedPadding_Bottom = attributes.getDimensionPixelSize(R.styleable.PagerIndicator_unselected_padding_bottom, (int) mPadding_bottom);\n\n mSelectedLayerDrawable = new LayerDrawable(new Drawable[]{mSelectedGradientDrawable});\n mUnSelectedLayerDrawable = new LayerDrawable(new Drawable[]{mUnSelectedGradientDrawable});\n\n\n setIndicatorStyleResource(mUserSetSelectedIndicatorResId, mUserSetUnSelectedIndicatorResId);\n setDefaultIndicatorShape(mIndicatorShape);\n setDefaultSelectedIndicatorSize(mDefaultSelectedWidth, mDefaultSelectedHeight, Unit.Px);\n setDefaultUnselectedIndicatorSize(mDefaultUnSelectedWidth, mDefaultUnSelectedHeight, Unit.Px);\n setDefaultIndicatorColor(mDefaultSelectedColor, mDefaultUnSelectedColor);\n setIndicatorVisibility(mVisibility);\n setDefaultSelectedPadding(mSelectedPadding_Left, mSelectedPadding_Top, mSelectedPadding_Right, mSelectedPadding_Bottom, Unit.Px);\n setDefaultUnSelectedPadding(mUnSelectedPadding_Left, mUnSelectedPadding_Top, mUnSelectedPadding_Right, mUnSelectedPadding_Bottom, Unit.Px);\n attributes.recycle();\n }\n\n public enum Shape {\n Oval, Rectangle\n }\n\n public void setDefaultPadding(float left, float top, float right, float bottom, Unit unit) {\n setDefaultSelectedPadding(left, top, right, bottom, unit);\n setDefaultUnSelectedPadding(left, top, right, bottom, unit);\n }\n\n public void setDefaultSelectedPadding(float left, float top, float right, float bottom, Unit unit) {\n if (unit == Unit.DP) {\n mSelectedLayerDrawable.setLayerInset(0,\n (int) pxFromDp(left), (int) pxFromDp(top),\n (int) pxFromDp(right), (int) pxFromDp(bottom));\n } else {\n mSelectedLayerDrawable.setLayerInset(0,\n (int) left, (int) top,\n (int) right, (int) bottom);\n\n }\n }\n\n public void setDefaultUnSelectedPadding(float left, float top, float right, float bottom, Unit unit) {\n if (unit == Unit.DP) {\n mUnSelectedLayerDrawable.setLayerInset(0,\n (int) pxFromDp(left), (int) pxFromDp(top),\n (int) pxFromDp(right), (int) pxFromDp(bottom));\n\n } else {\n mUnSelectedLayerDrawable.setLayerInset(0,\n (int) left, (int) top,\n (int) right, (int) bottom);\n\n }\n }\n\n /**\n * if you are using the default indicator, this method will help you to set the shape of\n * indicator, there are two kind of shapes you can set, oval and rect.\n *\n * @param shape Shape enum\n */\n public void setDefaultIndicatorShape(Shape shape) {\n if (mUserSetSelectedIndicatorResId == 0) {\n if (shape == Shape.Oval) {\n mSelectedGradientDrawable.setShape(GradientDrawable.OVAL);\n } else {\n mSelectedGradientDrawable.setShape(GradientDrawable.RECTANGLE);\n }\n }\n if (mUserSetUnSelectedIndicatorResId == 0) {\n if (shape == Shape.Oval) {\n mUnSelectedGradientDrawable.setShape(GradientDrawable.OVAL);\n } else {\n mUnSelectedGradientDrawable.setShape(GradientDrawable.RECTANGLE);\n }\n }\n resetDrawable();\n }\n\n\n /**\n * Set Indicator style.\n *\n * @param selected page selected drawable\n * @param unselected page unselected drawable\n */\n public void setIndicatorStyleResource(@DrawableRes int selected, @DrawableRes int unselected) {\n mUserSetSelectedIndicatorResId = selected;\n mUserSetUnSelectedIndicatorResId = unselected;\n if (selected == 0) {\n mSelectedDrawable = mSelectedLayerDrawable;\n } else {\n mSelectedDrawable = ContextCompat.getDrawable(mContext, mUserSetSelectedIndicatorResId);\n // mSelectedDrawable = mContext.getResources().getDrawable(mUserSetSelectedIndicatorResId);\n }\n if (unselected == 0) {\n mUnselectedDrawable = mUnSelectedLayerDrawable;\n } else {\n mUnselectedDrawable = ContextCompat.getDrawable(mContext, mUserSetUnSelectedIndicatorResId);\n // mUnselectedDrawable = mContext.getResources().getDrawable(mUserSetUnSelectedIndicatorResId);\n }\n\n resetDrawable();\n }\n\n /**\n * if you are using the default indicator , this method will help you to set the selected status and\n * the unselected status color.\n *\n * @param selectedColor color in packet int\n * @param unselectedColor color in packed int\n */\n public void setDefaultIndicatorColor(@ColorInt final int selectedColor, @ColorInt final int unselectedColor) {\n if (mUserSetSelectedIndicatorResId == 0) {\n mSelectedGradientDrawable.setColor(selectedColor);\n }\n if (mUserSetUnSelectedIndicatorResId == 0) {\n mUnSelectedGradientDrawable.setColor(unselectedColor);\n }\n resetDrawable();\n }\n\n /**\n * if you are using the default indicator , this method will help you to set the selected status and\n * the unselected status color.\n *\n * @param selectedColor color in resource id\n * @param unselectedColor color in resource id\n */\n public void setDefaultIndicatorColorRes(@ColorRes final int selectedColor, @ColorRes final int unselectedColor) {\n setDefaultIndicatorColor(ContextCompat.getColor(mContext, selectedColor),\n ContextCompat.getColor(mContext, unselectedColor));\n }\n\n public enum Unit {\n DP, Px\n }\n\n public void setDefaultSelectedIndicatorSize(float width, float height, Unit unit) {\n if (mUserSetSelectedIndicatorResId == 0) {\n float w = width;\n float h = height;\n if (unit == Unit.DP) {\n w = pxFromDp(width);\n h = pxFromDp(height);\n }\n mSelectedGradientDrawable.setSize((int) w, (int) h);\n resetDrawable();\n }\n }\n\n public void setDefaultUnselectedIndicatorSize(float width, float height, Unit unit) {\n if (mUserSetUnSelectedIndicatorResId == 0) {\n float w = width;\n float h = height;\n if (unit == Unit.DP) {\n w = pxFromDp(width);\n h = pxFromDp(height);\n }\n mUnSelectedGradientDrawable.setSize((int) w, (int) h);\n resetDrawable();\n }\n }\n\n public void setDefaultIndicatorSize(float width, float height, Unit unit) {\n setDefaultSelectedIndicatorSize(width, height, unit);\n setDefaultUnselectedIndicatorSize(width, height, unit);\n }\n\n private float dpFromPx(float px) {\n return px / this.getContext().getResources().getDisplayMetrics().density;\n }\n\n private float pxFromDp(float dp) {\n return dp * this.getContext().getResources().getDisplayMetrics().density;\n }\n\n /**\n * set the visibility of indicator.\n *\n * @param visibility IndicatorVisibility defined by visibility\n */\n public void setIndicatorVisibility(IndicatorVisibility visibility) {\n if (visibility == IndicatorVisibility.Visible) {\n setVisibility(View.VISIBLE);\n } else {\n setVisibility(View.INVISIBLE);\n }\n resetDrawable();\n }\n\n /**\n * clear self means unregister the dataset observer and remove all the child views(indicators).\n */\n public void destroySelf() {\n if (mPager == null || mPager.getAdapter() == null) {\n return;\n }\n InfinitePagerAdapter wrapper = (InfinitePagerAdapter) mPager.getAdapter();\n PagerAdapter adapter = wrapper.getRealAdapter();\n if (adapter != null) {\n adapter.unregisterDataSetObserver(dataChangeObserver);\n }\n removeAllViews();\n ShapeDrawable shapeDrawable;\n\n }\n\n /**\n * bind indicator with viewpagerEx.\n *\n * @param pager ViewPagerEx based on ViewPage support V4 object\n */\n public void setViewPager(ViewPagerEx pager) {\n if (pager.getAdapter() == null) {\n throw new IllegalStateException(\"Viewpager does not have adapter instance\");\n }\n mPager = pager;\n mPager.addOnPageChangeListener(this);\n ((InfinitePagerAdapter) mPager.getAdapter()).getRealAdapter().registerDataSetObserver(dataChangeObserver);\n }\n\n\n private void resetDrawable() {\n for (View i : mIndicators) {\n if (mPreviousSelectedIndicator != null && mPreviousSelectedIndicator.equals(i)) {\n ((ImageView) i).setImageDrawable(mSelectedDrawable);\n } else {\n ((ImageView) i).setImageDrawable(mUnselectedDrawable);\n }\n }\n }\n\n /**\n * redraw the indicators.\n */\n public void redraw() {\n mItemCount = getShouldDrawCount();\n mPreviousSelectedIndicator = null;\n\n for (View i : mIndicators) {\n removeView(i);\n }\n\n for (int i = 0; i < mItemCount; i++) {\n ImageView indicator = new ImageView(mContext);\n indicator.setImageDrawable(mUnselectedDrawable);\n addView(indicator);\n mIndicators.add(indicator);\n }\n setItemAsSelected(mPreviousSelectedPosition);\n }\n\n /**\n * since we used a adapter wrapper, so we can't getCount directly from wrapper.\n *\n * @return the integer\n */\n private int getShouldDrawCount() {\n if (mPager.getAdapter() instanceof InfinitePagerAdapter) {\n return ((InfinitePagerAdapter) mPager.getAdapter()).getRealCount();\n } else {\n return mPager.getAdapter().getCount();\n }\n }\n\n private DataSetObserver dataChangeObserver = new DataSetObserver() {\n @Override\n public void onChanged() {\n PagerAdapter adapter = mPager.getAdapter();\n int count = 0;\n if (adapter instanceof InfinitePagerAdapter) {\n count = ((InfinitePagerAdapter) adapter).getRealCount();\n } else {\n count = adapter.getCount();\n }\n if (count > mItemCount) {\n for (int i = 0; i < count - mItemCount; i++) {\n ImageView indicator = new ImageView(mContext);\n indicator.setImageDrawable(mUnselectedDrawable);\n addView(indicator);\n mIndicators.add(indicator);\n }\n } else if (count < mItemCount) {\n for (int i = 0; i < mItemCount - count; i++) {\n removeView(mIndicators.get(0));\n mIndicators.remove(0);\n }\n }\n mItemCount = count;\n mPager.setCurrentItem(mItemCount * 20 + mPager.getCurrentItem(), true);\n }\n\n @Override\n public void onInvalidated() {\n super.onInvalidated();\n redraw();\n }\n };\n\n private void setItemAsSelected(int position) {\n if (mPreviousSelectedIndicator != null) {\n mPreviousSelectedIndicator.setImageDrawable(mUnselectedDrawable);\n }\n ImageView currentSelected = (ImageView) getChildAt(position + 1);\n if (currentSelected != null) {\n currentSelected.setImageDrawable(mSelectedDrawable);\n mPreviousSelectedIndicator = currentSelected;\n }\n mPreviousSelectedPosition = position;\n }\n\n @Override\n public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {\n if (mItemCount == 0) {\n return;\n }\n int n = position % mItemCount;\n setItemAsSelected(n - 1);\n }\n\n public IndicatorVisibility getIndicatorVisibility() {\n return mVisibility;\n }\n\n @Override\n public void onPageSelected(int position) {\n\n }\n\n @Override\n public void onPageScrollStateChanged(int state) {\n\n }\n\n public int getSelectedIndicatorResId() {\n return mUserSetSelectedIndicatorResId;\n }\n\n public int getUnSelectedIndicatorResId() {\n return mUserSetUnSelectedIndicatorResId;\n }\n\n}",
"public class SliderLayout extends RelativeLayout {\n public static final int\n ZOOMABLE = 1, NONZOOMABLE = 0;\n\n @Retention(RetentionPolicy.SOURCE)\n @IntDef({ZOOMABLE, NONZOOMABLE})\n public @interface SliderLayoutType {\n }\n\n public Activity activity;\n public Context mContext;\n /**\n * InfiniteViewPager is extended from ViewPagerEx. As the name says, it can scroll without bounder.\n */\n private InfiniteViewPager mViewPager;\n /**\n * multiViewPager\n */\n private MultiViewPager mMViewPager;\n /**\n * InfiniteViewPager adapter.\n */\n private SliderAdapter mSliderAdapter;\n\n /**\n * {@link com.hkm.slider.Tricks.ViewPagerEx} indicator.\n */\n private PagerIndicator mIndicator;\n\n /**\n * A timer and a TimerTask using to cycle the {@link com.hkm.slider.Tricks.ViewPagerEx}.\n */\n private Timer mCycleTimer;\n private TimerTask mCycleTask;\n\n /**\n * For resuming the cycle, after user touch or click the {@link com.hkm.slider.Tricks.ViewPagerEx}.\n */\n private Timer mResumingTimer;\n private TimerTask mResumingTask;\n\n @SliderLayoutType\n private int pagerType = NONZOOMABLE;\n /**\n * If {@link com.hkm.slider.Tricks.ViewPagerEx} is Cycling\n */\n private boolean mCycling;\n private boolean sidebuttons;\n private boolean mDisabledSlider = false;\n private boolean mAutoAdjustSliderHeight = false;\n /**\n * Determine if auto recover after user touch the {@link com.hkm.slider.Tricks.ViewPagerEx}\n */\n private boolean mAutoRecover = true;\n\n private int mTransformerId;\n private int mSliderIndicatorPresentations;\n /**\n * {@link com.hkm.slider.Tricks.ViewPagerEx} transformer time span.\n */\n private int mTransformerSpan = 1100;\n\n private boolean mAutoCycle;\n\n private boolean mIsShuffle = false;\n\n /**\n * the duration between animation.\n */\n private long mSliderDuration = 4000;\n private long mTransitionAnimation = 1000;\n /**\n * Visibility of {@link com.hkm.slider.Indicators.PagerIndicator}\n */\n private PagerIndicator.IndicatorVisibility mIndicatorVisibility = PagerIndicator.IndicatorVisibility.Visible;\n\n /**\n * {@link com.hkm.slider.Tricks.ViewPagerEx} 's transformer\n */\n private BaseTransformer mViewPagerTransformer;\n\n /**\n * @see com.hkm.slider.Animations.BaseAnimationInterface\n */\n private BaseAnimationInterface mCustomAnimation;\n\n /**\n * the margin for setting the view pager margin distance\n */\n private int mPagerMargin;\n private int buttondr, buttondl;\n private int frame_width, frame_height;\n /**\n * this is the limit for switching from dot types into the page number type\n */\n private int slideDotLimit;\n\n /**\n * hold number specific\n */\n private RelativeLayout holderNum;\n\n /**\n * callback from the measurement collection\n */\n private OnViewConfigurationDetected mViewSizeMonitor;\n\n /**\n * callback will be triggered only when the {@link []}\n */\n private OnImageLoadWithAdjustableHeight mOnImageLoadWithAdjustableHeight;\n\n /**\n * {@link com.hkm.slider.Indicators.PagerIndicator} shape, rect or oval.\n *\n * @param context context\n */\n public SliderLayout(Context context) {\n this(context, null);\n }\n\n public SliderLayout(Context context, AttributeSet attrs) {\n this(context, attrs, R.attr.SliderStyle);\n }\n\n public SliderLayout(Context context, AttributeSet attrs, int defStyle) {\n super(context, attrs, defStyle);\n mContext = context;\n LayoutInflater.from(context).inflate(R.layout.slider_layout, this, true);\n final TypedArray attributes = context.getTheme().obtainStyledAttributes(attrs, R.styleable.SliderLayout, defStyle, 0);\n mTransformerSpan = attributes.getInteger(R.styleable.SliderLayout_pager_animation_span, 1100);\n mTransformerId = attributes.getInt(R.styleable.SliderLayout_pager_animation, TransformerL.Default.ordinal());\n mSliderIndicatorPresentations = attributes.getInt(R.styleable.SliderLayout_lns_use_presentation, Smart.ordinal());\n buttondl = attributes.getResourceId(R.styleable.SliderLayout_image_button_l, R.drawable.arrow_l);\n buttondr = attributes.getResourceId(R.styleable.SliderLayout_image_button_r, R.drawable.arrow_r);\n button_side_function_flip = attributes.getBoolean(R.styleable.SliderLayout_slider_side_buttons_function_flip, false);\n mAutoCycle = attributes.getBoolean(R.styleable.SliderLayout_auto_cycle, true);\n sidebuttons = attributes.getBoolean(R.styleable.SliderLayout_slider_side_buttons, false);\n slideDotLimit = attributes.getInt(R.styleable.SliderLayout_slide_dot_limit, 5);\n int visibility = attributes.getInt(R.styleable.SliderLayout_indicator_visibility, 0);\n checkVisibility(visibility);\n pagerSetup();\n attributes.recycle();\n setPresetIndicator(PresetIndicators.Center_Bottom);\n setPresetTransformer(mTransformerId);\n setSliderTransformDuration(mTransformerSpan, null);\n setIndicatorVisibility(mIndicatorVisibility);\n if (mAutoCycle) {\n startAutoCycle();\n }\n start_detect_frame_size();\n navigation_button_initialization();\n }\n\n private void checkVisibility(int xml_config) {\n for (PagerIndicator.IndicatorVisibility v : PagerIndicator.IndicatorVisibility.values()) {\n if (v.ordinal() == xml_config) {\n mIndicatorVisibility = v;\n break;\n }\n }\n }\n\n private void start_detect_frame_size() {\n ViewTreeObserver vto = this.getViewTreeObserver();\n vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {\n @Override\n public boolean onPreDraw() {\n getViewTreeObserver().removeOnPreDrawListener(this);\n frame_width = getMeasuredWidth();\n frame_height = getMeasuredHeight();\n return false;\n }\n });\n }\n\n private DataSetObserver sliderDataObserver = new DataSetObserver() {\n @Override\n public void onChanged() {\n if (mSliderAdapter.getCount() <= 1) {\n pauseAutoCycle();\n } else {\n recoverCycle();\n }\n }\n };\n private Handler postHandler = new Handler();\n private ImageView mButtonLeft, mButtonRight;\n private int mLWidthB, mRWidthB;\n private boolean mLopen, mRopen, button_side_function_flip = false;\n private ArrowControl arrow_instance;\n\n private void navigation_button_initialization() {\n mButtonLeft = (ImageView) findViewById(R.id.arrow_l);\n mButtonRight = (ImageView) findViewById(R.id.arrow_r);\n mButtonLeft.setImageResource(buttondl);\n mButtonRight.setImageResource(buttondr);\n arrow_instance = new ArrowControl(mButtonLeft, mButtonRight);\n mLWidthB = mButtonLeft.getDrawable().getIntrinsicWidth();\n mRWidthB = mButtonRight.getDrawable().getIntrinsicWidth();\n if (!sidebuttons) {\n arrow_instance.noSlideButtons();\n } else {\n arrow_instance.setListeners(\n new OnClickListener() {\n @Override\n public void onClick(View v) {\n if (!button_side_function_flip)\n moveNextPosition(true);\n else movePrevPosition(true);\n }\n },\n new OnClickListener() {\n @Override\n public void onClick(View v) {\n if (!button_side_function_flip)\n movePrevPosition(true);\n else moveNextPosition(true);\n }\n }\n );\n }\n mLopen = mRopen = true;\n }\n\n private void notify_navigation_buttons() {\n arrow_instance.setTotal(mSliderAdapter.getCount());\n int count = mSliderAdapter.getCount();\n\n //DisplayMetrics m = getResources().getDisplayMetrics();\n // final int width = m.widthPixels;\n final int end_close_left = -mLWidthB;\n final int end_close_right = mRWidthB;\n final int open_left = 0;\n final int open_right = 0;\n\n if (count <= 1) {\n postHandler.postDelayed(new Runnable() {\n @Override\n public void run() {\n if (mButtonLeft != null && mLopen) {\n mButtonLeft.animate().translationX(end_close_left);\n mLopen = false;\n }\n if (mButtonRight != null && mRopen) {\n mButtonRight.animate().translationX(end_close_right);\n mRopen = false;\n }\n }\n }, mTransitionAnimation);\n } else {\n postHandler.postDelayed(new Runnable() {\n @Override\n public void run() {\n if (mButtonLeft != null && !mLopen) {\n mButtonLeft.animate().translationX(open_left);\n mLopen = true;\n }\n if (mButtonRight != null && !mRopen) {\n mButtonRight.animate().translationX(open_right);\n mRopen = true;\n }\n }\n }, mTransitionAnimation);\n }\n }\n\n public SliderLayout setType(final @SliderLayoutType int t) {\n pagerType = t;\n return this;\n }\n\n public SliderLayout setActivity(final Activity t) {\n activity = t;\n return this;\n }\n\n private void pagerSetup() {\n mSliderAdapter = new SliderAdapter(mContext);\n if (pagerType == NONZOOMABLE) {\n PagerAdapter wrappedAdapter = new InfinitePagerAdapter(mSliderAdapter);\n mViewPager = (InfiniteViewPager) findViewById(R.id.daimajia_slider_viewpager);\n if (mPagerMargin > -1) {\n mViewPager.setMargin(mPagerMargin);\n }\n mViewPager.setOnTouchListener(new OnTouchListener() {\n @Override\n public boolean onTouch(View v, MotionEvent event) {\n int action = event.getAction();\n switch (action) {\n case MotionEvent.ACTION_UP:\n recoverCycle();\n break;\n }\n return false;\n }\n });\n mViewPager.setAdapter(wrappedAdapter);\n } else if (pagerType == ZOOMABLE) {\n\n }\n mSliderAdapter.registerDataSetObserver(sliderDataObserver);\n }\n\n public <TN extends NumContainer> void setNumLayout(final TN container) {\n holderNum = (RelativeLayout) findViewById(R.id.number_count_layout);\n // final RelativeLayout mSmallBox = (RelativeLayout) findViewById(R.id.subcontainer);\n container\n .withView(holderNum)\n .setViewPager(mViewPager)\n .build();\n }\n\n /**\n * set the current slider\n *\n * @param position the insert position\n * @param smooth if that is smooth or not\n */\n private void setCurrentPosition(int position, boolean smooth) {\n if (getRealAdapter() == null)\n throw new IllegalStateException(\"You did not set a slider adapter\");\n if (position >= getRealAdapter().getCount()) {\n throw new IllegalStateException(\"Item position is not exist\");\n }\n int p = mViewPager.getCurrentItem() % getRealAdapter().getCount();\n int n = (position - p) + mViewPager.getCurrentItem();\n mViewPager.setCurrentItem(n, smooth);\n }\n\n /**\n * this function will be removed soon in the next release. see {@link #setCurrentPositionAnim} with detail\n *\n * @param position number\n */\n @Deprecated\n public final void setCurrentPosition(int position) {\n setCurrentPositionAnim(position);\n }\n\n /**\n * set the current position with animation\n *\n * @param position the int of the slide position\n */\n public final void setCurrentPositionAnim(int position) {\n setCurrentPosition(position, true);\n }\n\n /**\n * set current position without animation\n *\n * @param position the int of the slide position\n */\n public final void setCurrentPositionStatic(int position) {\n setCurrentPosition(position, false);\n }\n\n /**\n * {@link ViewPagerEx#setOffscreenPageLimit(int)} open ViewPager API.\n *\n * @param limit How many pages will be kept offscreen in an idle state.\n */\n public final void setOffscreenPageLimit(int limit) {\n mViewPager.setOffscreenPageLimit(limit);\n }\n\n /**\n * set the custom indicator\n *\n * @param indicator the indicator type\n */\n public final void setCustomIndicator(PagerIndicator indicator) {\n if (mIndicator != null) {\n mIndicator.destroySelf();\n }\n mIndicator = indicator;\n mIndicator.setIndicatorVisibility(mIndicatorVisibility);\n mIndicator.setViewPager(mViewPager);\n mIndicator.redraw();\n }\n\n public final <T extends BaseSliderView> void addSlider(T slide) {\n mSliderAdapter.addSlider(slide);\n autoDetermineLayoutDecoration();\n notify_navigation_buttons();\n AnimationHelper.notify_component(mIndicator, mSliderAdapter, postHandler);\n }\n\n public final <T extends BaseSliderView> void addSliderList(List<T> slide_sequence) {\n if (mViewSizeMonitor != null) {\n mSliderAdapter.setOnInitiateViewListener(mViewSizeMonitor);\n }\n mSliderAdapter.addSliders(slide_sequence);\n afterLoadSliders();\n }\n\n\n /**\n * this is for internal use when each item is instaniated from the adapter\n */\n public interface OnViewConfigurationDetected {\n void onLayoutGenerated(final SparseArray<Integer> data);\n }\n\n public interface OnViewConfigurationFinalized {\n void onDeterminedMaxHeight(final int height);\n }\n\n public interface OnImageLoadWithAdjustableHeight {\n void onNotified(final int new_height, boolean isFullScreenHeight);\n }\n\n private int total_length = 0;\n\n public final <T extends BaseSliderView> void loadSliderList(List<T> slide_sequence) {\n mSliderAdapter.removeAllSliders();\n if (mViewSizeMonitor != null) {\n total_length = slide_sequence.size();\n mSliderAdapter.setOnInitiateViewListener(mViewSizeMonitor);\n }\n if (isAutoAdjustSlideHeightInternal()) {\n mSliderAdapter.setSliderContainerInternal(this);\n }\n mSliderAdapter.loadSliders(slide_sequence);\n afterLoadSliders();\n }\n\n\n public final void afterLoadSliders() {\n autoDetermineLayoutDecoration();\n notify_navigation_buttons();\n if (!mDisabledSlider) {\n AnimationHelper.notify_component(mIndicator, mSliderAdapter, postHandler);\n } else {\n mIndicator.setIndicatorVisibility(PagerIndicator.IndicatorVisibility.Invisible);\n }\n }\n\n public void setDisablePageIndicator() {\n mDisabledSlider = true;\n }\n\n /**\n * boardcast the height changes from the slider layout\n *\n * @param setFinal OnViewConfigurationFinalized\n */\n public final void setEnableMaxHeightFromAllSliders(final OnViewConfigurationFinalized setFinal) {\n\n mViewSizeMonitor = new OnViewConfigurationDetected() {\n @Override\n public void onLayoutGenerated(SparseArray<Integer> data) {\n if (total_length == data.size()) {\n List<Integer> arrayList = new ArrayList<>(data.size());\n for (int i = 0; i < data.size(); i++) {\n arrayList.add(data.valueAt(i));\n }\n mSliderAdapter.endLayoutObserver();\n setFinal.onDeterminedMaxHeight(Collections.max(arrayList));\n }\n }\n };\n }\n\n /**\n * after slider has been defined\n *\n * @param enabled bool\n */\n public final void setRemoveItemOnFailureToLoad(boolean enabled) {\n mSliderAdapter.setRemoveItemOnFailureToLoad(enabled);\n }\n\n private void autoDetermineLayoutDecoration() {\n final boolean over_limit = mSliderAdapter.getCount() > slideDotLimit;\n switch (byVal(mSliderIndicatorPresentations)) {\n case Smart:\n presentation(over_limit ? Numbers : Dots);\n break;\n case Dots:\n break;\n case Numbers:\n break;\n }\n }\n\n /**\n * move to the next slide\n *\n * @param smooth bool\n */\n public void moveNextPosition(boolean smooth) {\n\n if (getRealAdapter() == null)\n throw new IllegalStateException(\"You did not set a slider adapter\");\n\n mViewPager.setCurrentItem(mViewPager.getCurrentItem() + 1, smooth);\n if (mIsShuffle) {\n setPagerTransformer(true, getShuffleTransformer());\n }\n\n }\n\n public void moveNextPosition() {\n moveNextPosition(true);\n }\n\n public void presentation(PresentationConfig pc) {\n // usingPresentation = pc.ordinal();\n if (pc == Dots) {\n if (mIndicator != null)\n mIndicator.setVisibility(View.VISIBLE);\n if (holderNum != null)\n holderNum.setVisibility(View.GONE);\n } else if (pc == Numbers) {\n if (mIndicator != null)\n mIndicator.setVisibility(View.GONE);\n if (holderNum != null)\n holderNum.setVisibility(View.VISIBLE);\n }\n }\n\n /**\n * move to prev slide.\n *\n * @param smooth bool\n */\n public void movePrevPosition(boolean smooth) {\n if (getRealAdapter() == null)\n throw new IllegalStateException(\"You did not set a slider adapter\");\n mViewPager.setCurrentItem(mViewPager.getCurrentItem() - 1, smooth);\n }\n\n public void movePrevPosition() {\n movePrevPosition(true);\n }\n\n public void slideToNextItem() {\n mViewPager.nextItem();\n }\n\n public void slideToPreviousItem() {\n mViewPager.beforeItem();\n }\n\n private android.os.Handler mh = new android.os.Handler() {\n @Override\n public void handleMessage(Message msg) {\n super.handleMessage(msg);\n mViewPager.nextItem();\n }\n };\n\n public void startAutoCycle() {\n startAutoCycle(1000, mSliderDuration, mAutoRecover);\n }\n\n /**\n * start auto cycle.\n *\n * @param delay delay time\n * @param duration animation duration time.\n * @param autoRecover if recover after user touches the slider.\n */\n public void startAutoCycle(long delay, long duration, boolean autoRecover) {\n if (mCycleTimer != null) mCycleTimer.cancel();\n if (mCycleTask != null) mCycleTask.cancel();\n if (mResumingTask != null) mResumingTask.cancel();\n if (mResumingTimer != null) mResumingTimer.cancel();\n mSliderDuration = duration;\n mCycleTimer = new Timer();\n mAutoRecover = autoRecover;\n mCycleTask = new TimerTask() {\n @Override\n public void run() {\n mh.sendEmptyMessage(0);\n }\n };\n mCycleTimer.schedule(mCycleTask, delay, mSliderDuration);\n mCycling = true;\n mAutoCycle = true;\n }\n\n /**\n * runtime call\n * pause auto cycle.\n */\n private void pauseAutoCycle() {\n if (mCycling) {\n mCycleTimer.cancel();\n mCycleTask.cancel();\n mCycling = false;\n } else {\n if (mResumingTimer != null && mResumingTask != null) {\n recoverCycle();\n }\n }\n }\n\n\n /**\n * when paused cycle, this method can wake it up.\n */\n private void recoverCycle() {\n if (!mAutoRecover || !mAutoCycle) {\n return;\n }\n\n if (!mCycling) {\n if (mResumingTask != null && mResumingTimer != null) {\n mResumingTimer.cancel();\n mResumingTask.cancel();\n }\n mResumingTimer = new Timer();\n mResumingTask = new TimerTask() {\n @Override\n public void run() {\n startAutoCycle();\n }\n };\n mResumingTimer.schedule(mResumingTask, mSliderDuration);\n }\n }\n\n /**\n * set the duration between two slider changes. the duration value must bigger or equal to 500\n *\n * @param duration how long\n */\n public void setDuration(long duration) {\n if (duration >= 500) {\n mSliderDuration = duration;\n if (mAutoCycle && mCycling) {\n startAutoCycle();\n }\n }\n }\n\n /**\n * stop the auto circle\n */\n public void stopAutoCycle() {\n if (mCycleTask != null) {\n mCycleTask.cancel();\n }\n if (mCycleTimer != null) {\n mCycleTimer.cancel();\n }\n if (mResumingTimer != null) {\n mResumingTimer.cancel();\n }\n if (mResumingTask != null) {\n mResumingTask.cancel();\n }\n mAutoCycle = false;\n mCycling = false;\n }\n\n public void setOnSliderMeasurementFinal() {\n\n }\n\n public void addOnPageChangeListener(ViewPagerEx.OnPageChangeListener onPageChangeListener) {\n if (onPageChangeListener != null) {\n mViewPager.addOnPageChangeListener(onPageChangeListener);\n }\n }\n\n public void removeOnPageChangeListener(ViewPagerEx.OnPageChangeListener onPageChangeListener) {\n mViewPager.removeOnPageChangeListener(onPageChangeListener);\n }\n\n\n @Override\n public boolean onInterceptTouchEvent(MotionEvent ev) {\n int action = ev.getAction();\n switch (action) {\n case MotionEvent.ACTION_DOWN:\n pauseAutoCycle();\n break;\n\n case MotionEvent.ACTION_MOVE:\n if (getRealAdapter().getCount() <= 1) {\n return true;\n }\n break;\n }\n return false;\n }\n\n /**\n * set ViewPager transformer.\n *\n * @param reverseDrawingOrder the boolean for order\n * @param transformer BaseTransformer\n */\n public void setPagerTransformer(boolean reverseDrawingOrder, BaseTransformer transformer) {\n mViewPagerTransformer = transformer;\n mViewPagerTransformer.setCustomAnimationInterface(mCustomAnimation);\n mViewPager.setPageTransformer(reverseDrawingOrder, mViewPagerTransformer);\n }\n\n\n /**\n * set the duration between two slider changes.\n *\n * @param period by how many mil second to slide to the next one\n * @param interpolator with what interpolator\n */\n public void setSliderTransformDuration(int period, Interpolator interpolator) {\n try {\n final Field mScroller = ViewPagerEx.class.getDeclaredField(\"mScroller\");\n mScroller.setAccessible(true);\n final FixedSpeedScroller scroller = new FixedSpeedScroller(mViewPager.getContext(), interpolator, period);\n mScroller.set(mViewPager, scroller);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n\n public void setSliderTransformDuration(Interpolator interpolator) {\n setSliderTransformDuration(mTransformerSpan, interpolator);\n }\n\n /**\n * presentation of indicators\n */\n public enum PresentationConfig {\n Smart(\"Smart\")/* {\n @Override\n public Object getInstance() {\n return new Object();\n }\n }*/,\n Dots(\"Dots\"),\n Numbers(\"Numbers\");\n private final String name;\n\n PresentationConfig(String s) {\n name = s;\n }\n\n public String toString() {\n return name;\n }\n\n public boolean equals(String other) {\n return (other == null) ? false : name.equals(other);\n }\n\n public static PresentationConfig byVal(final int presentationInt) {\n for (TransformerL t : TransformerL.values()) {\n if (t.ordinal() == presentationInt) {\n return values()[t.ordinal()];\n }\n }\n return Smart;\n }\n\n // public abstract <T> getInstance();\n\n }\n\n /**\n * preset transformers and their names\n */\n\n\n /**\n * set a preset viewpager transformer by id.\n *\n * @param transformerId the recongized transformer ID\n */\n public void setPresetTransformer(int transformerId) {\n setPresetTransformer(TransformerL.fromVal(transformerId));\n }\n\n /**\n * set preset PagerTransformer via the name of transforemer.\n *\n * @param transformerName the transformer name in string\n */\n public void setPresetTransformer(String transformerName) {\n for (TransformerL t : TransformerL.values()) {\n if (t.equals(transformerName)) {\n setPresetTransformer(t);\n return;\n }\n }\n }\n\n /**\n * Inject your custom animation into PageTransformer, you can know more details in\n * {@link com.hkm.slider.Animations.BaseAnimationInterface},\n * and you can see a example in {@link com.hkm.slider.Animations.DescriptionAnimation}\n *\n * @param animation the base animation for interface\n */\n public void setCustomAnimation(BaseAnimationInterface animation) {\n mCustomAnimation = animation;\n if (mViewPagerTransformer != null) {\n mViewPagerTransformer.setCustomAnimationInterface(mCustomAnimation);\n }\n }\n\n /**\n * pretty much right? enjoy it. :-D\n *\n * @param ts the transformer object\n */\n public void setPresetTransformer(TransformerL ts) {\n if (ts == TransformerL.Shuffle) {\n setPagerTransformer(true, getShuffleTransformer());\n } else\n setPagerTransformer(true, ts.getTranformFunction());\n }\n\n /**\n * return a random TransformerL between [0, the length of enum -1)\n *\n * @return BaseTransformer\n */\n public BaseTransformer getShuffleTransformer() {\n mIsShuffle = true;\n return TransformerL.randomSymbol();\n }\n\n /**\n * Set the visibility of the indicators.\n *\n * @param visibility the page visibility\n */\n public void setIndicatorVisibility(PagerIndicator.IndicatorVisibility visibility) {\n if (mIndicator != null) {\n mIndicator.setIndicatorVisibility(visibility);\n }\n }\n\n /**\n * get the indicator if it is visible\n *\n * @return PagerIndicator\n */\n public PagerIndicator.IndicatorVisibility getIndicatorVisibility() {\n if (mIndicator == null) {\n return mIndicator.getIndicatorVisibility();\n }\n return PagerIndicator.IndicatorVisibility.Invisible;\n\n }\n\n /**\n * get the {@link com.hkm.slider.Indicators.PagerIndicator} instance.\n * You can manipulate the properties of the indicator.\n *\n * @return in return with PagerIndicator\n */\n public PagerIndicator getPagerIndicator() {\n return mIndicator;\n }\n\n public void setPresetIndicator(PresetIndicators presetIndicator) {\n PagerIndicator pagerIndicator = (PagerIndicator) findViewById(presetIndicator.getResourceId());\n setCustomIndicator(pagerIndicator);\n }\n\n private InfinitePagerAdapter getWrapperAdapter() {\n PagerAdapter adapter = mViewPager.getAdapter();\n if (adapter != null) {\n return (InfinitePagerAdapter) adapter;\n } else {\n return null;\n }\n }\n\n private SliderAdapter getRealAdapter() {\n PagerAdapter adapter = mViewPager.getAdapter();\n if (adapter != null) {\n return ((InfinitePagerAdapter) adapter).getRealAdapter();\n }\n return null;\n }\n\n /**\n * get the current item position\n *\n * @return the int position\n */\n public int getCurrentPosition() {\n if (getRealAdapter() == null)\n throw new IllegalStateException(\"You did not set a slider adapter\");\n int itemsCount = getRealAdapter().getCount();\n if (itemsCount < 1) {\n return 0;\n }\n return mViewPager.getCurrentItem() % itemsCount;\n }\n\n /**\n * get current slider.\n *\n * @return the sliderview\n */\n public BaseSliderView getCurrentSlider() {\n\n if (getRealAdapter() == null)\n throw new IllegalStateException(\"You did not set a slider adapter\");\n\n int count = getRealAdapter().getCount();\n int realCount = mViewPager.getCurrentItem() % count;\n return getRealAdapter().getSliderView(realCount);\n }\n\n /**\n * remove the slider at the position. Notice: It's a not perfect method, a very small bug still exists.\n *\n * @param position int position\n */\n public void removeSliderAt(int position) {\n if (getRealAdapter() != null) {\n getRealAdapter().removeSliderAt(position);\n //mViewPager.setCurrentItem(mViewPager.getCurrentItem(), false);\n }\n }\n\n /**\n * remove all the sliders. Notice: It's a not perfect method, a very small bug still exists.\n */\n public void removeAllSliders() {\n if (getRealAdapter() != null) {\n int count = getRealAdapter().getCount();\n getRealAdapter().removeAllSliders();\n //a small bug, but fixed by this trick.\n //bug: when remove adapter's all the sliders.some caching slider still alive.\n mViewPager.setCurrentItem(mViewPager.getCurrentItem() + count, false);\n }\n }\n\n /**\n * clear self means unregister the dataset observer and cancel all Timer\n */\n public void destroySelf() {\n mSliderAdapter.unregisterDataSetObserver(sliderDataObserver);\n stopAutoCycle();\n mViewPager.removeAllViews();\n }\n\n /**\n * Preset Indicators\n */\n public enum PresetIndicators {\n Center_Bottom(\"Center_Bottom\", R.id.default_center_bottom_indicator),\n Right_Bottom(\"Right_Bottom\", R.id.default_bottom_right_indicator),\n Left_Bottom(\"Left_Bottom\", R.id.default_bottom_left_indicator),\n Center_Top(\"Center_Top\", R.id.default_center_top_indicator),\n Right_Top(\"Right_Top\", R.id.default_center_top_right_indicator);\n\n private final String name;\n private final int id;\n\n PresetIndicators(String name, int id) {\n this.name = name;\n this.id = id;\n }\n\n public String toString() {\n return name;\n }\n\n public int getResourceId() {\n return id;\n }\n }\n\n\n @Override\n public void onDetachedFromWindow() {\n super.onDetachedFromWindow();\n if (mCycleTimer != null) mCycleTimer.cancel();\n if (mCycleTask != null) mCycleTask.cancel();\n if (mResumingTask != null) mResumingTask.cancel();\n if (mResumingTimer != null) mResumingTimer.cancel();\n mh.removeCallbacksAndMessages(null);\n }\n\n public boolean isAutoAdjustSlideHeightInternal() {\n return mAutoAdjustSliderHeight;\n }\n\n public void setAutoAdjustImageByHeight() {\n mAutoAdjustSliderHeight = true;\n addOnPageChangeListener(new ViewPagerEx.OnPageChangeListener() {\n @Override\n public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {\n setFitToCurrentImageHeight();\n Log.d(\"tagup\", \"position start \" + position);\n }\n\n @Override\n public void onPageSelected(int position) {\n Log.d(\"tagup\", \"position selected \" + position);\n }\n\n @Override\n public void onPageScrollStateChanged(int state) {\n Log.d(\"tagup\", \"position state \" + state);\n if (mOnImageLoadWithAdjustableHeight != null && temp_adjustment_height > 0 && state == 0) {\n mOnImageLoadWithAdjustableHeight.onNotified(temp_adjustment_height, temp_adjustment_height > temp_adjustmentcontent_max_height);\n temp_adjustment_height = -1;\n }\n }\n });\n setAutoAdjustImageFullContentMaxHeight(CONTEXT_DEFAULT_MAX_HEIGHT_AS_SCREEN_HEIGHT);\n }\n\n private int temp_adjustment_height = -1;\n private int temp_adjustmentcontent_max_height = -1;\n public static final int CONTEXT_DEFAULT_MAX_HEIGHT_AS_SCREEN_HEIGHT = -2;\n\n /**\n * set this param to enable the height of the\n *\n * @param maxHeight the maximum height\n */\n public void setAutoAdjustImageFullContentMaxHeight(final int maxHeight) {\n if (maxHeight == CONTEXT_DEFAULT_MAX_HEIGHT_AS_SCREEN_HEIGHT) {\n Resources resources = getContext().getResources();\n DisplayMetrics metrics = resources.getDisplayMetrics();\n temp_adjustmentcontent_max_height = metrics.heightPixels;\n } else {\n temp_adjustmentcontent_max_height = maxHeight;\n }\n }\n\n /**\n * additional call that is optional for user to make their own implementation\n *\n * @param wing listener\n */\n public final void setOnImageLoadWithAdjustableHeightListener(final OnImageLoadWithAdjustableHeight wing) {\n setAutoAdjustImageByHeight();\n mOnImageLoadWithAdjustableHeight = wing;\n }\n\n\n public void setFitToCurrentImageHeight() {\n if (getCurrentSlider().getImageView() instanceof ImageView) {\n ImageView p = (ImageView) getCurrentSlider().getImageView();\n if (p.getDrawable() != null) {\n int current_width = getMeasuredWidth();\n //(int) LoyalUtil.convertDpToPixel(image.getIntrinsicHeight(), getContext())\n Drawable image = p.getDrawable();\n float ratio = (float) image.getIntrinsicHeight() / (float) image.getIntrinsicWidth();\n\n final int fit_height = (int) (current_width * ratio);\n // Rect rec = new Rect(0, 0, image.getIntrinsicWidth(), image.getIntrinsicHeight());\n // requestRectangleOnScreen(rec);\n // onLayout(true, 0, 0, p.getDrawable().getIntrinsicWidth(), p.getDrawable().getIntrinsicHeight());\n if (getLayoutParams() instanceof RelativeLayout.LayoutParams) {\n // RelativeLayout.LayoutParams m = (RelativeLayout.LayoutParams) getLayoutParams();\n // int[] rules = m.getRules();\n RelativeLayout.LayoutParams h = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, fit_height);\n /* if (rules.length > 0) {\n for (int i = 0; i < rules.length; i++) {\n h.addRule(rules[i]);\n }\n }\n */\n setLayoutParams(h);\n } else if (getLayoutParams() instanceof LinearLayout.LayoutParams) {\n // LinearLayout.LayoutParams m = (LinearLayout.LayoutParams) getLayoutParams();\n // int[] rules = m.getRules();\n LinearLayout.LayoutParams h = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, fit_height);\n setLayoutParams(h);\n }\n temp_adjustment_height = fit_height;\n }\n }\n }\n\n @Override\n protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {\n super.onMeasure(widthMeasureSpec, heightMeasureSpec);\n }\n}",
"public abstract class BaseSliderView {\n protected Object current_image_holder;\n protected Context mContext;\n protected boolean imageLoaded = false;\n private RequestCreator rq = null;\n private final Bundle mBundle;\n protected int mTargetWidth, mTargetHeight;\n /**\n * Error place holder image.\n */\n private int mErrorPlaceHolderRes;\n\n /**\n * Empty imageView placeholder.\n */\n private int mEmptyPlaceHolderRes;\n\n private String mUrl;\n private File mFile;\n private int mRes;\n private int mSlideNumber;\n protected OnSliderClickListener mOnSliderClickListener;\n\n protected boolean mErrorDisappear, mLongClickSaveImage;\n protected boolean mImageLocalStorageEnable;\n\n private ImageLoadListener mLoadListener;\n\n private String mDescription;\n\n private Uri touch_information;\n /**\n * Scale type of the image.\n */\n protected ScaleType mScaleType = ScaleType.Fit;\n\n /**\n * reference of the parent\n */\n protected WeakReference<SliderLayout> sliderContainer;\n protected Typeface mTypeface;\n\n public void setSliderContainerInternal(SliderLayout b) {\n this.sliderContainer = new WeakReference<SliderLayout>(b);\n }\n\n public enum ScaleType {\n CenterCrop, CenterInside, Fit, FitCenterCrop\n }\n\n protected BaseSliderView(Context context) {\n mContext = context;\n this.mBundle = new Bundle();\n mLongClickSaveImage = false;\n mImageLocalStorageEnable = false;\n }\n\n public final void setSlideOrderNumber(final int order) {\n mSlideNumber = order;\n }\n\n public final int getSliderOrderNumber() {\n return mSlideNumber;\n }\n\n /**\n * the placeholder image when loading image from url or file.\n *\n * @param resId Image resource id\n * @return BaseSliderView\n */\n public BaseSliderView empty(int resId) {\n mEmptyPlaceHolderRes = resId;\n return this;\n }\n\n public BaseSliderView descriptionTypeface(Typeface typeface) {\n mTypeface = typeface;\n return this;\n }\n\n protected void setupDescription(TextView descTextView) {\n descTextView.setText(mDescription);\n if (mTypeface != null) {\n descTextView.setTypeface(mTypeface);\n }\n }\n\n /**\n * determine whether remove the image which failed to download or load from file\n *\n * @param disappear boolean\n * @return BaseSliderView\n */\n public BaseSliderView errorDisappear(boolean disappear) {\n mErrorDisappear = disappear;\n return this;\n }\n\n /**\n * if you set errorDisappear false, this will set a error placeholder image.\n *\n * @param resId image resource id\n * @return BaseSliderView\n */\n public BaseSliderView error(int resId) {\n mErrorPlaceHolderRes = resId;\n return this;\n }\n\n /**\n * the description of a slider image.\n *\n * @param description String\n * @return BaseSliderView\n */\n public BaseSliderView description(String description) {\n mDescription = description;\n return this;\n }\n\n /**\n * the url of the link or something related when the touch happens.\n *\n * @param info Uri\n * @return BaseSliderView\n */\n public BaseSliderView setUri(Uri info) {\n touch_information = info;\n return this;\n }\n\n /**\n * set a url as a image that preparing to load\n *\n * @param url String\n * @return BaseSliderView\n */\n public BaseSliderView image(String url) {\n if (mFile != null || mRes != 0) {\n throw new IllegalStateException(\"Call multi image function,\" +\n \"you only have permission to call it once\");\n }\n mUrl = url;\n return this;\n }\n\n /**\n * set a file as a image that will to load\n *\n * @param file java.io.File\n * @return BaseSliderView\n */\n public BaseSliderView image(File file) {\n if (mUrl != null || mRes != 0) {\n throw new IllegalStateException(\"Call multi image function,\" +\n \"you only have permission to call it once\");\n }\n mFile = file;\n return this;\n }\n\n public BaseSliderView image(@DrawableRes int res) {\n if (mUrl != null || mFile != null) {\n throw new IllegalStateException(\"Call multi image function,\" +\n \"you only have permission to call it once\");\n }\n mRes = res;\n return this;\n }\n\n /**\n * get the url of the image path\n *\n * @return the path in string\n */\n public String getUrl() {\n return mUrl;\n }\n\n /**\n * get the url from the touch event\n *\n * @return the touch event URI\n */\n public Uri getTouchURI() {\n return touch_information;\n }\n\n public boolean isErrorDisappear() {\n return mErrorDisappear;\n }\n\n public int getEmpty() {\n return mEmptyPlaceHolderRes;\n }\n\n public int getError() {\n return mErrorPlaceHolderRes;\n }\n\n public String getDescription() {\n return mDescription;\n }\n\n public Context getContext() {\n return mContext;\n }\n\n /**\n * set a slider image click listener\n *\n * @param l the listener\n * @return the base slider\n */\n public BaseSliderView setOnSliderClickListener(OnSliderClickListener l) {\n mOnSliderClickListener = l;\n return this;\n }\n\n protected View.OnLongClickListener mDefaultLongClickListener = null;\n protected WeakReference<FragmentManager> fmg;\n\n /**\n * to enable the slider for saving images\n *\n * @param mfmg FragmentManager\n * @return this thing\n */\n public BaseSliderView enableSaveImageByLongClick(FragmentManager mfmg) {\n mLongClickSaveImage = true;\n mDefaultLongClickListener = null;\n this.fmg = new WeakReference<FragmentManager>(mfmg);\n return this;\n }\n\n /**\n * to set custom listener for long click event\n *\n * @param listen the listener\n * @return thos thomg\n */\n public BaseSliderView setSliderLongClickListener(View.OnLongClickListener listen) {\n mDefaultLongClickListener = listen;\n mLongClickSaveImage = false;\n return this;\n }\n\n public BaseSliderView setSliderLongClickListener(View.OnLongClickListener listen, FragmentManager mfmg) {\n mDefaultLongClickListener = listen;\n mLongClickSaveImage = false;\n this.fmg = new WeakReference<FragmentManager>(mfmg);\n return this;\n }\n\n public BaseSliderView resize(int targetWidth, int targetHeight) {\n if (targetWidth < 0) {\n throw new IllegalArgumentException(\"Width must be positive number or 0.\");\n }\n if (targetHeight < 0) {\n throw new IllegalArgumentException(\"Height must be positive number or 0.\");\n }\n if (targetHeight == 0 && targetWidth == 0) {\n throw new IllegalArgumentException(\"At least one dimension has to be positive number.\");\n }\n mTargetWidth = targetWidth;\n mTargetHeight = targetHeight;\n return this;\n }\n\n public BaseSliderView enableImageLocalStorage() {\n mImageLocalStorageEnable = true;\n return this;\n }\n\n\n protected void hideLoadingProgress(View mView) {\n if (mView.findViewById(R.id.ns_loading_progress) != null) {\n hideoutView(mView.findViewById(R.id.ns_loading_progress));\n }\n }\n\n /**\n * when {@link #mLongClickSaveImage} is true and this function will be triggered to watch the long action run\n *\n * @param mView the slider view object\n */\n private void triggerOnLongClick(View mView) {\n if (mLongClickSaveImage && fmg != null) {\n if (mDefaultLongClickListener == null) {\n mDefaultLongClickListener = new View.OnLongClickListener() {\n @TargetApi(Build.VERSION_CODES.HONEYCOMB)\n @Override\n public boolean onLongClick(View v) {\n final saveImageDialog saveImageDial = new saveImageDialog();\n saveImageDial.show(fmg.get(), mDescription);\n return false;\n }\n };\n }\n mView.setOnLongClickListener(mDefaultLongClickListener);\n }\n }\n\n private final View.OnClickListener click_triggered = new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (mOnSliderClickListener != null) {\n mOnSliderClickListener.onSliderClick(BaseSliderView.this);\n }\n }\n };\n\n /**\n * When you want to implement your own slider view, please call this method in the end in `getView()` method\n *\n * @param v the whole view\n * @param targetImageView where to place image\n */\n protected void bindEventAndShowPicasso(final View v, final ImageView targetImageView) {\n current_image_holder = targetImageView;\n v.setOnClickListener(click_triggered);\n mLoadListener.onStart(this);\n final Picasso p = Picasso.with(mContext);\n rq = null;\n if (mUrl != null) {\n rq = p.load(mUrl);\n } else if (mFile != null) {\n rq = p.load(mFile);\n } else if (mRes != 0) {\n rq = p.load(mRes);\n } else {\n return;\n }\n if (rq == null) {\n return;\n }\n if (getEmpty() != 0) {\n rq.placeholder(getEmpty());\n }\n if (getError() != 0) {\n rq.error(getError());\n }\n if (mTargetWidth > 0 || mTargetHeight > 0) {\n rq.resize(mTargetWidth, mTargetHeight);\n }\n if (mImageLocalStorageEnable) {\n rq.memoryPolicy(MemoryPolicy.NO_STORE, MemoryPolicy.NO_CACHE);\n }\n\n switch (mScaleType) {\n case Fit:\n rq.fit();\n break;\n case CenterCrop:\n rq.fit().centerCrop();\n break;\n case CenterInside:\n rq.fit().centerInside();\n break;\n }\n\n rq.into(targetImageView, new Callback() {\n @Override\n public void onSuccess() {\n imageLoaded = true;\n hideLoadingProgress(v);\n triggerOnLongClick(v);\n reportStatusEnd(true);\n }\n\n @Override\n public void onError() {\n reportStatusEnd(false);\n }\n });\n }\n\n protected void bindEventShowGlide(final View v, final ImageView targetImageView) {\n RequestOptions requestOptions = new RequestOptions();\n\n v.setOnClickListener(click_triggered);\n final RequestManager glideRM = Glide.with(mContext);\n RequestBuilder rq;\n if (mUrl != null) {\n rq = glideRM.load(mUrl);\n } else if (mFile != null) {\n rq = glideRM.load(mFile);\n } else if (mRes != 0) {\n rq = glideRM.load(mRes);\n } else {\n return;\n }\n\n if (getEmpty() != 0) {\n requestOptions.placeholder(getEmpty());\n }\n if (getError() != 0) {\n requestOptions.error(getError());\n }\n\n switch (mScaleType) {\n case Fit:\n requestOptions.fitCenter();\n break;\n case CenterCrop:\n requestOptions.centerCrop();\n break;\n case CenterInside:\n requestOptions.fitCenter();\n break;\n }\n\n requestOptions.diskCacheStrategy(DiskCacheStrategy.ALL);\n if (mTargetWidth > 0 || mTargetHeight > 0) {\n requestOptions.override(mTargetWidth, mTargetHeight);\n }\n\n rq.apply(requestOptions);\n\n rq.listener(new RequestListener() {\n @Override\n public boolean onLoadFailed(@Nullable GlideException e, Object model, com.bumptech.glide.request.target.Target target, boolean isFirstResource) {\n reportStatusEnd(false);\n return false;\n }\n\n @Override\n public boolean onResourceReady(Object resource, Object model, com.bumptech.glide.request.target.Target target, DataSource dataSource, boolean isFirstResource) {\n hideLoadingProgress(v);\n triggerOnLongClick(v);\n reportStatusEnd(true);\n return false;\n }\n });\n rq.transition(DrawableTransitionOptions.withCrossFade());\n\n additionalGlideModifier(rq);\n rq.into(targetImageView);\n }\n\n protected void additionalGlideModifier(RequestBuilder requestBuilder) {\n\n }\n protected void applyImageWithGlide(View v, final ImageView targetImageView) {\n current_image_holder = targetImageView;\n LoyalUtil.glideImplementation(getUrl(), targetImageView, getContext());\n hideLoadingProgress(v);\n triggerOnLongClick(v);\n reportStatusEnd(true);\n imageLoaded = true;\n }\n\n protected void applyImageWithPicasso(View v, final ImageView targetImageView) {\n current_image_holder = targetImageView;\n LoyalUtil.picassoImplementation(getUrl(), targetImageView, getContext());\n hideLoadingProgress(v);\n triggerOnLongClick(v);\n imageLoaded = true;\n reportStatusEnd(true);\n }\n\n protected void applyImageWithSmartBoth(View v, final ImageView target) {\n current_image_holder = target;\n LoyalUtil.hybridImplementation(getUrl(), target, getContext());\n hideLoadingProgress(v);\n triggerOnLongClick(v);\n imageLoaded = true;\n reportStatusEnd(true);\n }\n\n\n protected void applyImageWithSmartBothAndNotifyHeight(View v, final ImageView target) {\n current_image_holder = target;\n LoyalUtil.hybridImplementation(getUrl(), target, getContext(), new Runnable() {\n @Override\n public void run() {\n imageLoaded = true;\n if (sliderContainer == null) return;\n if (sliderContainer.get().getCurrentPosition() == getSliderOrderNumber()) {\n sliderContainer.get().setFitToCurrentImageHeight();\n }\n\n }\n });\n hideLoadingProgress(v);\n triggerOnLongClick(v);\n reportStatusEnd(true);\n }\n\n private void reportStatusEnd(boolean b) {\n if (mLoadListener != null) {\n mLoadListener.onEnd(b, this);\n }\n }\n\n final android.os.Handler nh = new android.os.Handler();\n\n private int notice_save_image_success = R.string.success_save_image;\n\n public final void setMessageSaveImageSuccess(@StringRes final int t) {\n notice_save_image_success = t;\n }\n\n protected void workAroundGetImagePicasso() {\n\n final Target target = new Target() {\n @Override\n public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {\n\n }\n\n @Override\n public void onBitmapFailed(Drawable errorDrawable) {\n\n }\n\n @Override\n public void onPrepareLoad(Drawable placeHolderDrawable) {\n\n }\n };\n }\n\n protected void workGetImage(ImageView imageView) {\n imageView.setDrawingCacheEnabled(true);\n imageView.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));\n imageView.layout(0, 0, imageView.getMeasuredWidth(), imageView.getMeasuredHeight());\n imageView.buildDrawingCache(true);\n output_bitmap = Bitmap.createBitmap(imageView.getDrawingCache());\n imageView.setDrawingCacheEnabled(false);\n }\n\n private Bitmap output_bitmap = null;\n\n private class getImageTask extends AsyncTask<Void, Void, Integer> {\n private ImageView imageView;\n\n public getImageTask(ImageView taskTarget) {\n imageView = taskTarget;\n }\n\n @Override\n protected Integer doInBackground(Void... params) {\n int tried = 0;\n while (tried < 5) {\n try {\n workGetImage(imageView);\n return 1;\n } catch (Exception e) {\n tried++;\n }\n }\n return 0;\n }\n\n @Override\n protected void onPostExecute(Integer result) {\n super.onPostExecute(result);\n if (result == 1) {\n CapturePhotoUtils.insertImage(mContext, output_bitmap, mDescription, new CapturePhotoUtils.Callback() {\n @Override\n public void complete() {\n nh.post(new Runnable() {\n @Override\n public void run() {\n if (fmg == null) return;\n String note = mContext.getString(notice_save_image_success);\n final SMessage sm = SMessage.message(note);\n sm.show(fmg.get(), \"done\");\n }\n });\n }\n }\n );\n } else {\n String m = mContext.getString(R.string.image_not_read);\n final SMessage sm = SMessage.message(m);\n sm.show(fmg.get(), \"try again\");\n }\n }\n }\n\n /**\n * should use OnImageSavedListener instead or other listener for dialogs\n */\n @Deprecated\n @SuppressLint(\"ValidFragment\")\n @TargetApi(Build.VERSION_CODES.HONEYCOMB)\n public static class SMessage extends DialogFragment {\n public static SMessage message(final String mes) {\n Bundle h = new Bundle();\n h.putString(\"message\", mes);\n SMessage e = new SMessage();\n e.setArguments(h);\n return e;\n }\n\n @Override\n public Dialog onCreateDialog(Bundle savedInstanceState) {\n // Use the Builder class for convenient dialog construction\n AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());\n builder.setMessage(getArguments().getString(\"message\"))\n .setNeutralButton(R.string.okay_now, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int id) {\n dialog.dismiss();\n }\n })\n ;\n return builder.create();\n }\n }\n\n\n @SuppressLint(\"ValidFragment\")\n @TargetApi(Build.VERSION_CODES.HONEYCOMB)\n public class saveImageDialog extends DialogFragment {\n @Override\n public Dialog onCreateDialog(Bundle savedInstanceState) {\n if (mContext == null) return null;\n // Use the Builder class for convenient dialog construction\n AlertDialog.Builder builder = new AlertDialog.Builder(mContext);\n builder.setMessage(R.string.save_image)\n .setPositiveButton(R.string.yes_save, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int id) {\n saveImageActionTrigger();\n }\n })\n .setNegativeButton(R.string.no_keep, new DialogInterface.OnClickListener() {\n public void onClick(DialogInterface dialog, int id) {\n dialog.dismiss();\n }\n });\n // Create the AlertDialog object and return it\n return builder.create();\n }\n }\n\n protected void saveImageActionTrigger() {\n if (current_image_holder == null) return;\n if (current_image_holder instanceof ImageView) {\n ImageView fast = (ImageView) current_image_holder;\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {\n if (mContext.getApplicationContext().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {\n // mContext.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, AnyNumber);\n } else {\n getImageTask t = new getImageTask(fast);\n t.execute();\n }\n } else {\n getImageTask t = new getImageTask(fast);\n t.execute();\n }\n }\n }\n\n @TargetApi(Build.VERSION_CODES.JELLY_BEAN)\n final protected void hideoutView(@Nullable final View view) {\n if (view == null) return;\n view.animate().alpha(0f).withEndAction(new Runnable() {\n @Override\n public void run() {\n view.setVisibility(View.INVISIBLE);\n }\n });\n }\n\n public BaseSliderView setScaleType(ScaleType type) {\n mScaleType = type;\n return this;\n }\n\n public ScaleType getScaleType() {\n return mScaleType;\n }\n\n /**\n * the extended class have to implement getView(), which is called by the adapter,\n * every extended class response to render their own view.\n *\n * @return View\n */\n public abstract View getView();\n\n /**\n * set a listener to get a message , if load error.\n *\n * @param l ImageLoadListener\n */\n public void setOnImageLoadListener(ImageLoadListener l) {\n mLoadListener = l;\n }\n\n public interface OnSliderClickListener {\n void onSliderClick(BaseSliderView coreSlider);\n }\n\n /**\n * when you have some extra information, please put it in this bundle.\n *\n * @return Bundle\n */\n public Bundle getBundle() {\n return mBundle;\n }\n\n public interface ImageLoadListener {\n void onStart(BaseSliderView target);\n\n void onEnd(boolean result, BaseSliderView target);\n }\n\n public Object getImageView() {\n return current_image_holder;\n }\n\n public interface OnImageSavedListener {\n void onImageSaved(String description);\n\n void onImageSaveFailed();\n }\n\n protected OnImageSavedListener onImageSavedListener = null;\n\n public OnImageSavedListener getOnImageSavedListener() {\n return onImageSavedListener;\n }\n\n public void setOnImageSavedListener(OnImageSavedListener onImageSavedListener) {\n this.onImageSavedListener = onImageSavedListener;\n }\n}"
] | import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.os.Build;
import android.os.Handler;
import android.support.v4.view.animation.LinearOutSlowInInterpolator;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.hkm.loyalns.R;
import com.hkm.loyalns.Util.DataProvider;
import com.hkm.loyalns.mod.BaseApp;
import com.hkm.loyalns.modules.CustomNumberView;
import com.hkm.loyalns.modules.NumZero;
import com.hkm.loyalns.modules.TransformerAdapter;
import com.hkm.slider.Animations.DescriptionAnimation;
import com.hkm.slider.Indicators.PagerIndicator;
import com.hkm.slider.SliderLayout;
import com.hkm.slider.SliderTypes.BaseSliderView;
import com.hkm.slider.SliderTypes.TextSliderView;
import com.hkm.slider.TransformerL;
import java.util.ArrayList;
import java.util.HashMap; | package com.hkm.loyalns.demos;
public class ExampleClassic extends BaseApp {
@SuppressLint("ResourceAsColor")
protected void setupSlider() {
// remember setup first
mDemoSlider.setPresetTransformer(TransformerL.Accordion);
mDemoSlider.setPresetIndicator(SliderLayout.PresetIndicators.Center_Bottom);
mDemoSlider.setCustomAnimation(new DescriptionAnimation());
mDemoSlider.setDuration(4000);
mDemoSlider.addOnPageChangeListener(this);
mDemoSlider.setOffscreenPageLimit(3);
mDemoSlider.setSliderTransformDuration(400, new LinearOutSlowInInterpolator());
mDemoSlider.getPagerIndicator().setDefaultIndicatorColorRes(R.color.red_pink_26, R.color.red_pink_27);
final NumZero n = new NumZero(this);
mDemoSlider.setNumLayout(n);
mDemoSlider.presentation(SliderLayout.PresentationConfig.Numbers);
ListView l = (ListView) findViewById(R.id.transformers);
l.setAdapter(new TransformerAdapter(this));
l.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
mDemoSlider.setPresetTransformer(((TextView) view).getText().toString());
Toast.makeText(ExampleClassic.this, ((TextView) view).getText().toString(), Toast.LENGTH_SHORT).show();
}
});
//and data second. it is a must because you will except the data to be streamed into the pipline.
mDemoSlider.setEnableMaxHeightFromAllSliders(new SliderLayout.OnViewConfigurationFinalized() {
@Override
public void onDeterminedMaxHeight(int height) {
final int heifght = 700;
mFrameMain.setLayoutParams(new RelativeLayout.LayoutParams(-1, heifght));
mDemoSlider.setCurrentPositionStatic(0);
}
});
defaultCompleteSlider(DataProvider.getFileSrcHorizontal());
}
/**
* this is the example of the dynamic loading of the sliders
*
* @param maps the list of the slider
*/
protected void customSliderView(final HashMap<String, String> maps) {
for (String name : maps.keySet()) { | CustomNumberView textSliderView = new CustomNumberView(this); | 2 |
miurahr/tmpotter | src/main/java/org/tmpotter/filters/bitext/ImportWizardBiTextFile.java | [
"public static final String getString(final String strKey) {\n return (_bundle.getString(strKey));\n}",
"public interface IImportWizardPanel {\n /**\n * Initialize panel when registered.\n * @param controller controller reference.\n * @param pref key-value preference.\n */\n void init(ImportWizardController controller, ImportPreference pref);\n\n /**\n * Call when show the panel.\n */\n void onShow();\n\n String getId();\n\n boolean isCombinedFormat();\n\n JPanel getPanel();\n\n String getName();\n\n String getDesc();\n\n String getNextFinishCommand();\n\n String getBackCommand();\n\n void updatePref();\n}",
"public class ImportPreference {\n private URI originalFileUri;\n private URI translationFileUri;\n private String originalLang;\n private String translationLang;\n private String sourceEncoding;\n private String translationEncoding;\n private String filter;\n private File currentPath;\n private Map<String, String> config = new TreeMap<>();\n\n public File getOriginalFilePath() {\n return new File(originalFileUri);\n }\n\n public URI getOriginalFileUri() {\n return originalFileUri;\n }\n\n public void setOriginalFilePath(File originalFilePath) {\n originalFileUri = originalFilePath.toURI();\n }\n\n public void setOriginalFilePath(URI uri) {\n originalFileUri = uri;\n }\n\n public File getTranslationFilePath() {\n return new File(translationFileUri);\n }\n\n public URI getTranslationFileUri() {\n return translationFileUri;\n }\n\n public void setTranslationFilePath(File translationFilePath) {\n translationFileUri = translationFilePath.toURI();\n }\n\n public void setTranslationFilePath(URI uri) {\n translationFileUri = uri;\n }\n\n public String getOriginalLang() {\n return originalLang;\n }\n\n public void setOriginalLang(String originalLang) {\n this.originalLang = originalLang;\n }\n\n public String getTranslationLang() {\n return translationLang;\n }\n\n public void setTranslationLang(String translationLang) {\n this.translationLang = translationLang;\n }\n\n public String getSourceEncoding() {\n return sourceEncoding;\n }\n\n public void setSourceEncoding(String encoding) {\n this.sourceEncoding = encoding;\n }\n\n public String getTranslationEncoding() {\n return translationEncoding;\n }\n\n public void setTranslationEncoding(String translationEncoding) {\n this.translationEncoding = translationEncoding;\n }\n\n public String getFilter() {\n return filter;\n }\n\n public void setFilter(String filter) {\n this.filter = filter;\n }\n\n public File getCurrentPath() {\n if (currentPath != null) {\n return currentPath;\n } else if (originalFileUri != null) {\n return new File(originalFileUri);\n }\n return null;\n }\n\n public void setCurrentPath(File path) {\n currentPath = path;\n }\n\n public String getConfigValue(final String key) {\n return config.get(key);\n }\n\n public String getConfigValueOrDefault(final String key, final String defaultValue) {\n if (config.containsKey(key)) {\n return config.get(key);\n }\n return defaultValue;\n }\n\n public void setConfigValue(final String key, final String value) {\n config.put(key, value);\n }\n}",
"public class ImportWizardController {\n\n private ImportWizard wizard;\n private ImportPreference pref;\n private boolean finished = false;\n\n public ImportWizardController(final ImportWizard wizard) {\n this.wizard = wizard;\n pref = wizard.getPref();\n registerPanels();\n onStartup();\n }\n\n private void registerPanels() {\n IImportWizardPanel p = new ImportWizardSelectTypePanel();\n wizard.registerWizardPanel(p.getId(), p);\n for (IImportWizardPanel panel : PluginUtils.getWizards()) {\n panel.init(this, pref);\n wizard.registerWizardPanel(panel.getId(), panel);\n }\n }\n\n public final void registerPanel(final String id, final IImportWizardPanel panel) {\n\t wizard.registerWizardPanel(id, panel);\n }\n\n public final void onStartup() {\n wizard.setButtonBackEnabled(false);\n wizard.setButtonNextEnabled(true);\n wizard.showPanel(ImportWizardSelectTypePanel.id);\n }\n\n public final String getSourceLocale() {\n return pref.getOriginalLang();\n }\n\n public final String getTargetLocale() {\n return pref.getTranslationLang();\n }\n\n public final File getSourcePath() {\n return pref.getOriginalFilePath();\n }\n\n public final File getTargetPath() {\n return pref.getTranslationFilePath();\n }\n\n public final void setButtonNextEnabled(boolean b) {\n wizard.setButtonNextEnabled(b);\n }\n\n public final void setButtonBackEnabled(boolean b) {\n wizard.setButtonBackEnabled(b);\n }\n\n public final boolean isFinished() {\n return finished;\n }\n\n public void onBack() {\n String command = wizard.getButtonBackCommand();\n wizard.showPanel(command);\n if (command.equals(ImportWizardSelectTypePanel.id)) {\n wizard.setButtonBackEnabled(false);\n }\n }\n\n public void onNextFinish() {\n String command = wizard.getButtonNextCommand();\n wizard.updatePref();\n if (\"finish\".equals(command)) {\n finished = true;\n wizard.dispose();\n } else {\n wizard.showPanel(command);\n wizard.setButtonBackEnabled(true);\n wizard.setButtonNextEnabled(false);\n }\n }\n\n public void onCancel() {\n wizard.dispose();\n }\n}",
"public class ImportWizardSelectTypePanel extends JPanel implements IImportWizardPanel {\n public static final String id = \"selecttype\";\n private List<JRadioButton> buttons = new ArrayList<>();\n private List<JLabel> labels = new ArrayList<>();\n\n /**\n * Creates new form ImportWizardSelectTypePanel\n */\n public ImportWizardSelectTypePanel() {\n initComponents();\n setOptions();\n }\n\n // dummy methods.\n public void init(final ImportWizardController controller, ImportPreference pref) {}\n\n public void onShow() {}\n\n public String getId() {\n return id;\n }\n\n public boolean isCombinedFormat() {\n return true;\n }\n\n @Override\n public JPanel getPanel() {\n return this;\n }\n\n @Override\n public String getName() {\n return null;\n }\n\n @Override\n public String getDesc() {\n return null;\n }\n\n @Override\n public String getNextFinishCommand() {\n return getSelection();\n }\n\n @Override\n public String getBackCommand() {\n return null;\n }\n\n public String getSelection() {\n if (buttonGroup.getSelection() != null) {\n return buttonGroup.getSelection().getActionCommand();\n }\n return \"\";\n }\n\n @Override\n public void updatePref() {\n }\n\n private void setOptions() {\n // count panels.\n int combined = 0;\n int bitext = 0;\n List<IImportWizardPanel> panels = PluginUtils.getWizards();\n for (IImportWizardPanel panel : panels) {\n if (panel.isCombinedFormat()) {\n combined++;\n } else {\n bitext++;\n }\n }\n // set place holder size.\n panelBiText.setLayout(new java.awt.GridLayout(bitext, 2));\n panelSingle.setLayout(new java.awt.GridLayout(combined, 2));\n // create radioButtons and labels.\n for (IImportWizardPanel panel : panels) {\n JLabel label = new JLabel();\n label.setText(panel.getDesc());\n JRadioButton button = new JRadioButton();\n button.setText(panel.getName());\n button.setActionCommand(panel.getId());\n if (panel.isCombinedFormat()) {\n panelSingle.add(button);\n panelSingle.add(label);\n } else {\n panelBiText.add(button);\n panelBiText.add(label);\n }\n buttonGroup.add(button);\n buttons.add(button);\n labels.add(label);\n }\n add(panelBiText);\n add(panelSingle);\n }\n\n private void initComponents() {\n buttonGroup = new javax.swing.ButtonGroup();\n panelBiText = new javax.swing.JPanel();\n panelSingle = new javax.swing.JPanel();\n\n setLayout(new javax.swing.BoxLayout(this, javax.swing.BoxLayout.Y_AXIS));\n\n panelBiText.setBorder(javax.swing.BorderFactory.createTitledBorder(\"Bi-Text imports\"));\n panelBiText.setLayout(new java.awt.GridLayout(2, 2));\n\n panelSingle.setBorder(javax.swing.BorderFactory.createTitledBorder(\"Single file import\"));\n panelSingle.setLayout(new java.awt.GridLayout(2, 2));\n }\n\n private javax.swing.ButtonGroup buttonGroup;\n private javax.swing.JPanel panelBiText;\n private javax.swing.JPanel panelSingle;\n\n}",
"public class AppConstants {\n private static final String __VERSION_KEY = \"version\";\n private static final String __UPDATE_KEY = \"update\";\n private static final String __REVISION_KEY = \"revision\";\n private static String BRANDING = \"\";\n private static final String NAME = getString(\"WND.APP.TITLE\");\n private static final String VERSION = ResourceBundle\n .getBundle(\"org/tmpotter/Version\")\n .getString(__VERSION_KEY);\n private static final String UPDATE = ResourceBundle\n .getBundle(\"org/tmpotter/Version\")\n .getString(__UPDATE_KEY);\n private static final String REVISION = ResourceBundle\n .getBundle(\"org/tmpotter/Version\")\n .getString(__REVISION_KEY);\n public static final String COPYRIGHT = \"Copyright (C) 2015\";\n public static final String LICENSE =\n \"Released as Free Software under GPL v3 and later\";\n public static final String AUTHORS =\n \"Hiroshi Miura\";\n public static final String CONTRIBUTORS =\n \"TMPotter used components of OmegaT and bitext2tmx.\\n\"\n + \"OmegaT: Alex Buloichik, Thomas Cordonnier,\\n\"\n + \" Aaron Madlon-Kay, Zoltan Bartko,\\n\"\n + \" Didier Briel, Maxym Mykhalchuk, \"\n + \"Keith Godfrey\\n\"\n + \"bitext2tmx: Susana Santos Antón,\\n\"\n + \" Raymond: Martin et al.\";\n public static final String BUILDCLASSPATH = \"build\"\n + File.separator + \"classes\";\n public static final int READ_AHEAD_LIMIT = 65536;\n\n public static final Pattern XML_ENCODING = Pattern\n .compile(\"<\\\\?xml.*?encoding\\\\s*=\\\\s*\\\"(\\\\S+?)\\\".*?\\\\?>\");\n\n public static final String APPLICATION_JAR = \"tmpotter.jar\";\n public static final String DEBUG_CLASSPATH = File.separator + \"classes\";\n\n // Encodings.java\n public static final String ENCODINGS_UTF8 = \"UTF-8\";\n public static final String ENCODINGS_ISO8859_1 = \"ISO-8859-1\";\n public static final String ENCODINGS_CP932 = \"CP932\";\n public static final String ENCODINGS_DEFAULT = \"Default\";\n public static final List<String> straEncodings = Collections.unmodifiableList(\n new ArrayList<String>() {\n {\n add(ENCODINGS_DEFAULT);\n add(ENCODINGS_UTF8);\n add(ENCODINGS_ISO8859_1);\n add(ENCODINGS_CP932);\n }\n }\n );\n public static final String TAG_REPLACEMENT = \"\\b\";\n\n /**\n * Char which should be used instead protected parts.\n * <p>\n * <p>It should be non-letter char, to be able to have\n * correct words counter.\n * <p>\n * <p>This char can be placed around protected text for\n * separate words inside protected text and words\n * outside if there are no spaces between they.\n */\n public static final char TAG_REPLACEMENT_CHAR = '\\b';\n\n /**\n * Pattern that detects language and country,\n * with an optional script in the middle.\n */\n public static final Pattern LANG_AND_COUNTRY = Pattern\n .compile(\"([A-Za-z]{1,8})(?:(?:-|_)(?:[A-Za-z]{4}(?:-|_))?([A-Za-z0-9]{1,8}))?\");\n\n public static final Pattern SPACY_REGEX = Pattern\n .compile(\"((\\\\s|\\\\\\\\n|\\\\\\\\t|\\\\\\\\s)(\\\\+|\\\\*)?)+\");\n\n /**\n * Make app name and version string for human.\n *\n * @return string to indicate for human reading\n */\n public static String getDisplayNameAndVersion() {\n if (!UPDATE.equals(\"0\")) {\n return StringUtil.format(getString(\"app-version-template-pretty-update\"),\n getApplicationDisplayName(), VERSION, UPDATE);\n } else {\n return StringUtil.format(getString(\"app-version-template-pretty\"),\n getApplicationDisplayName(), VERSION);\n }\n }\n\n /**\n * Get the application name for display purposes (includes branding).\n *\n * @return application name for human reading.\n */\n public static String getApplicationDisplayName() {\n return BRANDING.isEmpty() ? NAME : NAME + \" \" + BRANDING;\n }\n\n /**\n * Get the application description.\n *\n * @return string to describe application\n */\n public static String getApplicationDescription() {\n return getString(\"WND.APP.DESCRIPTION\");\n }\n\n public static String getAppNameAndVersion() {\n return StringUtil.format(getString(\"app-version-template\"), NAME, VERSION, UPDATE,\n REVISION);\n }\n\n public static String getVersion() {\n return StringUtil.format(getString(\"version-template\"), VERSION, UPDATE, REVISION);\n }\n}",
"public final class Localization {\n // Init the bundle\n private static Control control = new Utf8ResourceBundleControl();\n private static ResourceBundle _bundle = ResourceBundle\n .getBundle(\"org/tmpotter/Bundle\", control);\n\n private static final ArrayList<String> languageList = new ArrayList<>();\n private static final ArrayList<String> langId = new ArrayList<>();\n\n static {\n languageList.add(getString(\"language-name-arab\"));\n langId.add(\"AR\");\n languageList.add(getString(\"language-name-bulgarian\"));\n langId.add(\"BG\");\n languageList.add(getString(\"language-name-catalan\"));\n langId.add(\"CA\");\n languageList.add(getString(\"language-name-chinese\"));\n langId.add(\"ZH\");\n languageList.add(getString(\"language-name-czech\"));\n langId.add(\"CZ\");\n languageList.add(getString(\"language-name-danish\"));\n langId.add(\"DA\");\n languageList.add(getString(\"language-name-dutch\"));\n langId.add(\"NL\");\n languageList.add(getString(\"language-name-english\"));\n langId.add(\"EN\");\n languageList.add(getString(\"language-name-finnish\"));\n langId.add(\"FI\");\n languageList.add(getString(\"language-name-french\"));\n langId.add(\"FR\");\n languageList.add(getString(\"language-name-german\"));\n langId.add(\"DE\");\n languageList.add(getString(\"language-name-hungarian\"));\n langId.add(\"HU\");\n languageList.add(getString(\"language-name-italian\"));\n langId.add(\"IT\");\n languageList.add(getString(\"language-name-japanese\"));\n langId.add(\"JA\");\n languageList.add(getString(\"language-name-korean\"));\n langId.add(\"KO\");\n languageList.add(getString(\"language-name-norwegian\"));\n langId.add(\"NB\");\n languageList.add(getString(\"language-name-polish\"));\n langId.add(\"PL\");\n languageList.add(getString(\"language-name-portuguese\"));\n langId.add(\"PT\");\n languageList.add(getString(\"language-name-russian\"));\n langId.add(\"RU\");\n languageList.add(getString(\"language-name-spanish\"));\n langId.add(\"ES\");\n languageList.add(getString(\"language-name-swedish\"));\n langId.add(\"SV\");\n languageList.add(getString(\"language-name-thai\"));\n langId.add(\"TH\");\n }\n\n /**\n * Return language name list in local character.\n *\n * @return String array of language name in local language.\n */\n public static String[] getLanguageList() {\n String[] list = new String[languageList.size()];\n return languageList.toArray(list);\n }\n\n public static String getLanguageCode(int index) {\n return langId.get(index);\n }\n\n /**\n * Returns resource bundle.\n *\n * @return bundle object\n */\n public static ResourceBundle getResourceBundle() {\n return _bundle;\n }\n\n /**\n * Private constructor.\n *\n * @noinspection UNUSED_SYMBOL\n */\n private Localization() {\n }\n\n /**\n * l10n: return localized string for given key.\n *\n * @param strKey String to retrieve resource\n * @return String translated string\n */\n public static final String getString(final String strKey) {\n return (_bundle.getString(strKey));\n }\n\n /**\n * Exception on localization.\n */\n @SuppressWarnings(\"serial\")\n public static final class LocalizationException extends Exception {\n public LocalizationException() {\n super();\n }\n\n /**\n * LocalizationException with message parameter.\n *\n * @param msg exception message\n */\n public LocalizationException(final String msg) {\n super(msg);\n }\n }\n}"
] | import org.tmpotter.util.AppConstants;
import org.tmpotter.util.Localization;
import java.io.File;
import java.util.Locale;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.filechooser.FileNameExtensionFilter;
import static org.openide.awt.Mnemonics.setLocalizedText;
import static org.tmpotter.util.Localization.getString;
import org.tmpotter.ui.wizard.IImportWizardPanel;
import org.tmpotter.ui.wizard.ImportPreference;
import org.tmpotter.ui.wizard.ImportWizardController;
import org.tmpotter.ui.wizard.ImportWizardSelectTypePanel; | /* *************************************************************************
*
* TMPotter - Bi-text Aligner/TMX Editor
*
* Copyright (C) 2016 Hiroshi Miura
*
* This file is part of TMPotter.
*
* TMPotter 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.
*
* TMPotter 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 TMPotter. If not, see http://www.gnu.org/licenses/.
*
* *************************************************************************/
package org.tmpotter.filters.bitext;
/**
* Import Wizard Bi-Text filter panel.
*
* @author Hiroshi Miura
*/
public class ImportWizardBiTextFile extends javax.swing.JPanel implements IImportWizardPanel {
public static final String id = "BiTextFilter";
private final String[] idiom = Localization.getLanguageList();
private ImportWizardController wizardController;
private ImportPreference pref;
/**
* Creates new form ImportWizardBiTextFile.
*/
public ImportWizardBiTextFile() {
}
/**
* Initialize Bitext Filter wizard ui.
* {@link IImportWizardPanel#init(ImportWizardController, ImportPreference)}
* @param controller controller.
* @param preference preference to update.
*/
public void init(final ImportWizardController controller,
final ImportPreference preference) {
wizardController = controller;
pref = preference;
initComponents();
}
public void onShow() {
}
/**
* Return ID of BiText filter.
* {@link IImportWizardPanel#getId()}
* @return filter id.
*/
public String getId() {
return id;
}
/**
* This reads two text files.
* {@link IImportWizardPanel#isCombinedFormat()}
* @return false.
*/
public boolean isCombinedFormat() {
return false;
}
/**
* {@link IImportWizardPanel#getPanel()}
* @return this panel.
*/
public JPanel getPanel() {
return this;
}
/**
* Return name of bitext filter.
* {@link IImportWizardPanel#getName()}
* @return name.
*/
public String getName() {
return "Bi-text file";
}
/**
* Return description of bitext filter.
* {@link IImportWizardPanel#getDesc()}
* @return description.
*/
public String getDesc() {
return "Bi-text file.";
}
/**
* Update preference from fields.
* {@link IImportWizardPanel#updatePref()}
*/
public void updatePref() {
pref.setCurrentPath(new File(getOriginalFile()));
pref.setOriginalFilePath(new File(getOriginalFile()));
pref.setTranslationFilePath(new File(getTranslationFile()));
pref.setOriginalLang(getSourceLocale());
pref.setTranslationLang(getTargetLocale());
pref.setSourceEncoding(getOriginalEncoding());
pref.setTranslationEncoding(getTranslationEncoding());
pref.setFilter(id);
}
/**
* Return source language.
* @return source locale.
*/
public final String getSourceLocale() {
return Localization.getLanguageCode(comboOriginalLang.getSelectedIndex());
}
/**
* Set default source locale.
* @param locale source language.
*/
public final void setSourceLocale(String locale) {
//String[] codes = Localization.getLanguageList();
comboOriginalLang.setSelectedItem(locale);
// FIXME
}
/**
* Return target language.
* @return target locale.
*/
public final String getTargetLocale() {
return Localization.getLanguageCode(comboTranslationLang.getSelectedIndex());
}
/**
* Set default target locale.
* @param locale target language.
*/
public final void setTargetLocale(String locale) {
//String[] codes = Localization.getLanguageList();
comboTranslationLang.setSelectedItem(locale);
// FIXME
}
/**
* Return character encoding.
* @return character encoding.
*/
public final String getOriginalEncoding() {
return (String) comboOriginalEncoding.getSelectedItem();
}
/**
* set default character encoding for source text.
* @param encoding encoding.
*/
public final void setOriginalEncoding(String encoding) {
comboOriginalEncoding.setSelectedItem(encoding);
}
/**
* Return character encoding.
* @return encoding.
*/
public final String getTranslationEncoding() {
return (String) comboTranslationEncoding.getSelectedItem();
}
/**
* Set default encoding for translation text.
* @param encoding encoding.
*/
public final void setTranslationEncoding(String encoding) {
comboTranslationEncoding.setSelectedItem(encoding);
}
/**
* Return original file path.
* @return file path.
*/
public final String getOriginalFile() {
return fieldOriginal.getText();
}
/**
* Set default original file path.
* @param file file path.
*/
public final void setOriginalFile(String file) {
fieldOriginal.setText(file);
}
/**
* Return translation file path.
* @return file path.
*/
public final String getTranslationFile() {
return fieldTranslation.getText();
}
/**
* Set default translation file path.
* @param file file path.
*/
public void setTranslationFile(String file) {
fieldTranslation.setText(file);
}
/**
* Return panel id for back button.
* @return id of type selection panel.
*/
public String getBackCommand() { | return ImportWizardSelectTypePanel.id; | 4 |
cgrotz/kademlia | src/main/java/de/cgrotz/kademlia/client/KademliaClient.java | [
"@Data\n@Builder\npublic class Configuration {\n\n private final Key nodeId;\n\n private final long getTimeoutMs;\n private final long networkTimeoutMs;\n private final int kValue;\n\n @Singular\n private final List<Listener> listeners;\n @Singular\n private final List<Listener> advertisedListeners;\n\n public static ConfigurationBuilder defaults() {\n return Configuration.builder()\n .getTimeoutMs(5000)\n .networkTimeoutMs(5000)\n .kValue(20);\n //.listener(new UdpListener(\"0.0.0.0\", 9000))\n //.advertisedListener(new UdpListener(\"127.0.0.1\", 9000));\n }\n}",
"public enum ListenerType {\n UDP(\"udp\", UdpListener.class);\n\n private final String prefix;\n private final Class listenerConfigClass;\n\n ListenerType(String prefix, Class<UdpListener> listenerConfigClass) {\n this.prefix = prefix;\n this.listenerConfigClass = listenerConfigClass;\n }\n\n public String prefix() {\n return prefix;\n }\n\n public Class getListenerConfigClass() {\n return listenerConfigClass;\n }\n}",
"@Data\n@ToString(callSuper = true)\n@EqualsAndHashCode(callSuper = true)\npublic class UdpListener extends Listener {\n\n public UdpListener(String host, int port) {\n super(ListenerType.UDP);\n this.host = host;\n this.port = port;\n }\n public UdpListener(String url) {\n super(ListenerType.UDP);\n\n this.host = url.substring(6, url.lastIndexOf(\":\"));\n this.port = Integer.parseInt(url.substring(url.lastIndexOf(\":\")+1));\n }\n\n private final String host;\n private final int port;\n\n\n public static UdpListener from(String url) {\n return new UdpListener(url);\n }\n}",
"public class NoMatchingListener extends RuntimeException {\n}",
"public class KademliaTimeoutException extends RuntimeException {\n\n public KademliaTimeoutException(Exception e) {\n super(e);\n }\n\n public KademliaTimeoutException() {\n\n }\n}",
"@Data\n@EqualsAndHashCode(of = \"key\")\npublic class Key {\n public final static int ID_LENGTH = 160;\n\n private BigInteger key;\n\n public Key(byte[] result) {\n if(result.length > ID_LENGTH/8 ) {\n throw new RuntimeException(\"ID to long. Needs to be \"+ID_LENGTH+\"bits long.\" );\n }\n this.key = new BigInteger(result);\n }\n\n public Key(BigInteger key) {\n if( key.toByteArray().length > ID_LENGTH/8 ) {\n throw new RuntimeException(\"ID to long. Needs to be \"+ID_LENGTH+\"bits long.\" );\n }\n this.key = key;\n }\n\n public Key(int id) {\n this.key = BigInteger.valueOf(id);\n }\n\n public static Key random() {\n byte[] bytes = new byte[ID_LENGTH / 8];\n SecureRandom sr1 = new SecureRandom();\n sr1.nextBytes(bytes);\n return new Key(bytes);\n }\n\n public static Key build(String key) {\n return new Key(new BigInteger(key,16));\n }\n\n /**\n * Checks the distance between this and another Key\n *\n * @param nid\n *\n * @return The distance of this Key from the given Key\n */\n public Key xor(Key nid)\n {\n return new Key(nid.getKey().xor(this.key));\n }\n\n /**\n * Generates a Key that is some distance away from this Key\n *\n * @param distance in number of bits\n *\n * @return Key The newly generated Key\n */\n public Key generateNodeIdByDistance(int distance)\n {\n byte[] result = new byte[ID_LENGTH / 8];\n\n /* Since distance = ID_LENGTH - prefixLength, we need to fill that amount with 0's */\n int numByteZeroes = (ID_LENGTH - distance) / 8;\n int numBitZeroes = 8 - (distance % 8);\n\n /* Filling byte zeroes */\n for (int i = 0; i < numByteZeroes; i++)\n {\n result[i] = 0;\n }\n\n /* Filling bit zeroes */\n BitSet bits = new BitSet(8);\n bits.set(0, 8);\n\n for (int i = 0; i < numBitZeroes; i++)\n {\n /* Shift 1 zero into the start of the value */\n bits.clear(i);\n }\n bits.flip(0, 8); // Flip the bits since they're in reverse order\n result[numByteZeroes] = (byte) bits.toByteArray()[0];\n\n /* Set the remaining bytes to Maximum value */\n for (int i = numByteZeroes + 1; i < result.length; i++)\n {\n result[i] = Byte.MAX_VALUE;\n }\n\n return this.xor(new Key(result));\n }\n\n /**\n * Counts the number of leading 0's in this Key\n *\n * @return Integer The number of leading 0's\n */\n public int getFirstSetBitIndex()\n {\n int prefixLength = 0;\n\n for (byte b : this.key.toByteArray())\n {\n if (b == 0)\n {\n prefixLength += 8;\n }\n else\n {\n /* If the byte is not 0, we need to count how many MSBs are 0 */\n int count = 0;\n for (int i = 7; i >= 0; i--)\n {\n boolean a = (b & (1 << i)) == 0;\n if (a)\n {\n count++;\n }\n else\n {\n break; // Reset the count if we encounter a non-zero number\n }\n }\n\n /* Add the count of MSB 0s to the prefix length */\n prefixLength += count;\n\n /* Break here since we've now covered the MSB 0s */\n break;\n }\n }\n return prefixLength;\n }\n\n @Override\n public String toString()\n {\n return this.key.toString(16);\n }\n\n\n /**\n * Gets the distance from this Key to another Key\n *\n * @param to\n *\n * @return Integer The distance\n */\n public int getDistance(Key to)\n {\n /**\n * Compute the xor of this and to\n * Get the index i of the first set bit of the xor returned Key\n * The distance between them is ID_LENGTH - i\n */\n return ID_LENGTH - this.xor(to).getFirstSetBitIndex();\n }\n}",
"@Data\n@EqualsAndHashCode(of={\"id\"})\n@Builder\npublic class Node implements Comparable<Node>{\n private Key id;\n @Singular\n private final List<Listener> advertisedListeners;\n private long lastSeen = System.currentTimeMillis();\n\n @Override\n public int compareTo(Node o) {\n if (this.equals(o))\n {\n return 0;\n }\n\n return (this.lastSeen > o.lastSeen) ? 1 : -1;\n }\n}"
] | import de.cgrotz.kademlia.Configuration;
import de.cgrotz.kademlia.config.ListenerType;
import de.cgrotz.kademlia.config.UdpListener;
import de.cgrotz.kademlia.exception.NoMatchingListener;
import de.cgrotz.kademlia.exception.KademliaTimeoutException;
import de.cgrotz.kademlia.node.Key;
import de.cgrotz.kademlia.node.Node;
import de.cgrotz.kademlia.protocol.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.UnsupportedEncodingException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.security.SecureRandom;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.*;
import java.util.function.Consumer; | package de.cgrotz.kademlia.client;
/**
* Created by Christoph on 21.09.2016.
*/
public class KademliaClient {
private final Logger LOGGER;
private static SecureRandom random = new SecureRandom();
private final KademliaClientHandler kademliaClientHandler;
private final Configuration config;
private final Node localNode;
private final DatagramSocket socket;
private Codec codec = new Codec();
private final Duration timeout = Duration.ofSeconds(30);
private ExecutorService executor = Executors.newSingleThreadExecutor();
public KademliaClient(DatagramSocket socket, Configuration config, Node localNode) {
this.LOGGER = LoggerFactory.getLogger(KademliaClient.class.getSimpleName() + " " + localNode.getId().toString());
this.localNode = localNode;
this.config = config;
this.socket = socket;
kademliaClientHandler = new KademliaClientHandler();
}
private void send(Node node, long seqId, Message msg, Consumer<Message> consumer) throws KademliaTimeoutException, NoMatchingListener {
kademliaClientHandler.registerHandler(seqId, consumer);
UdpListener udpListener = node.getAdvertisedListeners().stream() | .filter(listener -> listener.getType() == ListenerType.UDP) | 1 |
free46000/MultiItem | demo/src/main/java/com/freelib/multiitem/demo/FullSpanGridActivity.java | [
"public class BaseItemAdapter extends RecyclerView.Adapter<BaseViewHolder> {\n private List<Object> dataItems = new ArrayList<>();\n private List<Object> headItems = new ArrayList<>();\n private List<Object> footItems = new ArrayList<>();\n private ItemTypeManager itemTypeManager;\n private LoadMoreManager loadMoreManager;\n private OnItemClickListener onItemClickListener;\n private OnItemLongClickListener onItemLongClickListener;\n private ViewHolderParams params = new ViewHolderParams();\n protected AnimationLoader animationLoader = new AnimationLoader();\n\n\n public BaseItemAdapter() {\n itemTypeManager = new ItemTypeManager();\n }\n\n\n /**\n * 为数据源注册ViewHolder的管理类{@link ViewHolderManager}<br>\n * ViewHolder的管理类使adapter与view holder的创建绑定解耦<br>\n * 通过{@link ItemTypeManager}管理不同数据源和ViewHolder的关系<br>\n *\n * @param cls 数据源class\n * @param manager 数据源管理类\n * @param <T> 数据源\n * @param <V> ViewHolder\n * @see #register(Class, ViewHolderManagerGroup) 为相同数据源注册多个ViewHolder的管理类\n */\n public <T, V extends BaseViewHolder> void register(@NonNull Class<T> cls, @NonNull ViewHolderManager<T, V> manager) {\n itemTypeManager.register(cls, manager);\n }\n\n /**\n * 为相同数据源注册多个ViewHolder的管理类{@link ViewHolderManagerGroup}<br>\n * 主要为相同数据源根据内部属性的值对应多个ViewHolderManager设计,常见的如聊天界面的消息<br>\n *\n * @param cls 数据源class\n * @param group 对应相同数据源的一组数据源管理类\n * @param <T> 数据源\n * @param <V> ViewHolder\n * @see #register(Class, ViewHolderManager) 为数据源注册ViewHolder的管理类\n */\n public <T, V extends BaseViewHolder> void register(@NonNull Class<T> cls, @NonNull ViewHolderManagerGroup<T> group) {\n itemTypeManager.register(cls, group);\n }\n\n /**\n * 设置Item view点击监听\n */\n public void setOnItemClickListener(@NonNull OnItemClickListener onItemClickListener) {\n this.onItemClickListener = onItemClickListener;\n }\n\n /**\n * 设置item view长按监听\n */\n public void setOnItemLongClickListener(@NonNull OnItemLongClickListener onItemLongClickListener) {\n this.onItemLongClickListener = onItemLongClickListener;\n }\n\n /**\n * 设置Item list\n */\n public void setDataItems(@NonNull List<? extends Object> dataItems) {\n setItem(dataItems);\n }\n\n /**\n * 添加Item\n */\n public void addDataItem(@NonNull Object item) {\n addDataItem(dataItems.size(), item);\n }\n\n /**\n * 在指定位置添加Item\n */\n public void addDataItem(int position, @NonNull Object item) {\n addDataItems(position, Collections.singletonList(item));\n }\n\n /**\n * 添加ItemList\n */\n public void addDataItems(@NonNull List<? extends Object> items) {\n addDataItems(dataItems.size(), items);\n }\n\n /**\n * 在指定位置添加ItemList\n */\n public void addDataItems(int position, @NonNull List<? extends Object> items) {\n addItem(position, items);\n }\n\n /**\n * add item的最后调用处\n */\n protected void addItem(int position, @NonNull List<? extends Object> items) {\n dataItems.addAll(position, items);\n notifyItemRangeInserted(position + getHeadCount(), items.size());\n }\n\n /**\n * 设置item的最后调用处\n */\n protected void setItem(@NonNull List<? extends Object> dataItems) {\n this.dataItems = (List<Object>) dataItems;\n notifyDataSetChanged();\n }\n\n /**\n * 移动Item的位置 包括数据源和界面的移动\n *\n * @param fromPosition Item之前所在位置\n * @param toPosition Item新的位置\n */\n public void moveDataItem(int fromPosition, int toPosition) {\n //考虑到跨position(如0->2)移动的时候处理不能Collections.swap\n // if(from<to) to = to + 1 - 1;//+1是因为add的时候应该是to位置后1位,-1是因为先remove了from所以位置往前挪了1位\n dataItems.add(toPosition, dataItems.remove(fromPosition));\n notifyItemMoved(fromPosition + getHeadCount(), toPosition + getHeadCount());\n }\n\n\n /**\n * 移除Item 包括数据源和界面的移除\n *\n * @param position 需要被移除Item的position\n */\n public void removeDataItem(int position) {\n removeDataItem(position, 1);\n }\n\n /**\n * 改变Item 包括数据源和界面的移除\n *\n * @param position 需要被移除第一个Item的position\n * @param position 需要被移除Item的个数\n */\n public void removeDataItem(int position, int itemCount) {\n for (int i = 0; i < itemCount; i++) {\n dataItems.remove(position);\n }\n notifyItemRangeRemoved(position + getHeadCount(), itemCount);\n }\n\n /**\n * 添加foot View,默认为充满父布局\n * <p>\n * {@link ViewHolderManager#isFullSpan()}\n * {@link ViewHolderManager#getSpanSize(int)}\n *\n * @param footView foot itemView\n * @see HeadFootHolderManager\n * @see UniqueItemManager\n */\n public void addFootView(@NonNull View footView) {\n addFootItem(new UniqueItemManager(new HeadFootHolderManager(footView)));\n }\n\n /**\n * 添加foot ItemManager ,如是表格不居中需要充满父布局请设置对应属性<br>\n * {@link ViewHolderManager#isFullSpan()}\n * {@link ViewHolderManager#getSpanSize(int)}\n *\n * @param footItem foot item\n * @see HeadFootHolderManager\n */\n public void addFootItem(@NonNull Object footItem) {\n footItems.add(footItem);\n }\n\n /**\n * 添加head View,默认为充满父布局\n * <p>\n * {@link ViewHolderManager#isFullSpan()}\n * {@link ViewHolderManager#getSpanSize(int)}\n *\n * @param headView head itemView\n * @see HeadFootHolderManager\n * @see UniqueItemManager\n */\n public void addHeadView(@NonNull View headView) {\n addHeadItem(new UniqueItemManager(new HeadFootHolderManager(headView)));\n }\n\n /**\n * 添加head ItemManager ,如是表格不居中需要充满父布局请设置对应属性<br>\n * {@link ViewHolderManager#isFullSpan()}\n * {@link ViewHolderManager#getSpanSize(int)}\n *\n * @param headItem head item\n * @see HeadFootHolderManager\n */\n public void addHeadItem(@NonNull Object headItem) {\n headItems.add(headItem);\n }\n\n /**\n * 开启loadMore,使列表支持加载更多<p>\n * 本方法原理是添加{@link #addFootItem(Object)} 并且对添加顺序敏感需要注意在最后调用本方法才可以将加载更多视图放在底部\n *\n * @param loadMoreManager LoadMoreManager\n */\n public void enableLoadMore(@NonNull LoadMoreManager loadMoreManager) {\n this.loadMoreManager = loadMoreManager;\n loadMoreManager.setAdapter(this);\n addFootItem(loadMoreManager);\n }\n\n /**\n * 加载完成\n *\n * @see LoadMoreManager#loadCompleted(boolean)\n */\n public void setLoadCompleted(boolean isLoadAll) {\n if (loadMoreManager != null) {\n loadMoreManager.loadCompleted(isLoadAll);\n }\n }\n\n /**\n * 加载失败\n *\n * @see LoadMoreManager#loadFailed()\n */\n public void setLoadFailed() {\n if (loadMoreManager != null) {\n loadMoreManager.loadFailed();\n }\n }\n\n /**\n * 启动加载动画\n *\n * @param animation BaseAnimation\n */\n public void enableAnimation(BaseAnimation animation) {\n animationLoader.enableLoadAnimation(animation, true);\n }\n\n /**\n * 启动加载动画\n *\n * @param animation BaseAnimation\n * @param isShowAnimWhenFirstLoad boolean 是否只有在第一次展示的时候才使用动画\n */\n public void enableAnimation(BaseAnimation animation, boolean isShowAnimWhenFirstLoad) {\n animationLoader.enableLoadAnimation(animation, isShowAnimWhenFirstLoad);\n }\n\n /**\n * @see AnimationLoader#setInterpolator(Interpolator)\n */\n public void setInterpolator(@NonNull Interpolator interpolator) {\n animationLoader.setInterpolator(interpolator);\n }\n\n /**\n * @see AnimationLoader#setAnimDuration(long)\n */\n public void setAnimDuration(long animDuration) {\n animationLoader.setAnimDuration(animDuration);\n }\n\n /**\n * @return 获取当前数据源List,不包含head和foot\n */\n public List<Object> getDataList() {\n return dataItems;\n }\n\n\n /**\n * @param position int\n * @return 返回指定位置Item\n */\n public Object getItem(int position) {\n if (position < headItems.size()) {\n return headItems.get(position);\n }\n\n position -= headItems.size();\n if (position < dataItems.size()) {\n return dataItems.get(position);\n }\n\n position -= dataItems.size();\n if (position < footItems.size()) {\n return footItems.get(position);\n }\n\n return null;\n }\n\n /**\n * 清空数据\n */\n public void clearAllData() {\n clearData();\n headItems.clear();\n footItems.clear();\n }\n\n /**\n * 清空Item数据不含head 和 foot\n */\n public void clearData() {\n dataItems.clear();\n animationLoader.clear();\n }\n\n\n @Override\n public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {\n ViewHolderManager provider = itemTypeManager.getViewHolderManager(viewType);\n BaseViewHolder viewHolder = provider.onCreateViewHolder(parent);\n viewHolder.viewHolderManager = provider;\n return viewHolder;\n }\n\n @Override\n public void onBindViewHolder(BaseViewHolder holder, int position) {\n Object item = getItem(position);\n ViewHolderManager manager = holder.viewHolderManager;\n params.setItemCount(getItemCount()).setClickListener(onItemClickListener)\n .setLongClickListener(onItemLongClickListener);\n manager.onBindViewHolder(holder, item, params);\n //赋值 方便以后使用\n holder.itemView.setTag(Const.VIEW_HOLDER_TAG, holder);\n holder.itemData = item;\n }\n\n @Override\n public int getItemViewType(int position) {\n int type = itemTypeManager.getItemType(getItem(position));\n if (type < 0) {\n throw new RuntimeException(\"没有为\" + getItem(position).getClass() + \"找到对应的item itemView manager,是否注册了?\");\n }\n return type;\n }\n\n @Override\n public int getItemCount() {\n return dataItems.size() + getHeadCount() + getFootCount();\n }\n\n @Override\n public void onViewAttachedToWindow(BaseViewHolder holder) {\n super.onViewAttachedToWindow(holder);\n// System.out.println(\"onViewAttachedToWindow:::\" + holder.getItemPosition() + \"==\" + holder.getItemData());\n //当StaggeredGridLayoutManager的时候设置充满横屏\n if (holder.getViewHolderManager().isFullSpan() && holder.itemView.getLayoutParams() instanceof StaggeredGridLayoutManager.LayoutParams) {\n StaggeredGridLayoutManager.LayoutParams params = (StaggeredGridLayoutManager.LayoutParams) holder.itemView.getLayoutParams();\n params.setFullSpan(true);\n }\n animationLoader.startAnimation(holder);\n }\n\n @Override\n public void onAttachedToRecyclerView(final RecyclerView recyclerView) {\n super.onAttachedToRecyclerView(recyclerView);\n// System.out.println(\"onAttachedToRecyclerView:::\" + getItemCount());\n RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();\n if (manager instanceof GridLayoutManager) {\n //GridLayoutManager时设置每行的span\n final GridLayoutManager gridManager = ((GridLayoutManager) manager);\n gridManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {\n ViewHolderManager holderManager;\n\n @Override\n public int getSpanSize(int position) {\n holderManager = itemTypeManager.getViewHolderManager(getItemViewType(position));\n return holderManager.getSpanSize(gridManager.getSpanCount());\n }\n });\n }\n }\n\n /**\n * @return head view个数\n */\n public int getHeadCount() {\n return headItems.size();\n }\n\n /**\n * @return foot view个数\n */\n public int getFootCount() {\n return footItems.size();\n }\n\n}",
"public class ImageBean {\n private int img;\n\n public ImageBean(int img) {\n this.img = img;\n }\n\n public int getImg() {\n return img;\n }\n\n public void setImg(int img) {\n this.img = img;\n }\n\n @Override\n public String toString() {\n return img + \"\";\n }\n}",
"public class ImageTextBean extends BaseItemData {\n private int img;\n private String imgUrl;\n private String text;\n\n public ImageTextBean(int img, String text) {\n this.img = img;\n this.text = text;\n }\n\n public ImageTextBean(String imgUrl, String text) {\n this.imgUrl = imgUrl;\n this.text = text;\n }\n\n public int getImg() {\n return img;\n }\n\n public void setImg(int img) {\n this.img = img;\n }\n\n public String getText() {\n return text;\n }\n\n public void setText(String text) {\n this.text = text;\n }\n\n public String getImgUrl() {\n return imgUrl;\n }\n\n public void setImgUrl(String imgUrl) {\n this.imgUrl = imgUrl;\n }\n\n @Override\n public String toString() {\n return text;\n }\n}",
"public class TextBean {\n private String text;\n\n public TextBean(String text) {\n this.text = text;\n }\n\n public String getText() {\n return text;\n }\n\n public void setText(String text) {\n this.text = text;\n }\n\n @Override\n public String toString() {\n return text;\n }\n}",
"public class FullSpanTextViewManager extends TextViewManager {\n @Override\n public boolean isFullSpan() {\n return true;\n }\n}",
"public class ImageAndTextManager extends BaseViewHolderManager<ImageTextBean> {\n\n\n @Override\n public void onBindViewHolder(@NonNull BaseViewHolder holder, @NonNull ImageTextBean data) {\n TextView textView = getView(holder, R.id.text);\n textView.setText(data.getText());\n ImageView imageView = getView(holder, R.id.image);\n imageView.setImageResource(data.getImg());\n }\n\n @Override\n protected int getItemLayoutId() {\n return R.layout.item_image_text;\n }\n\n}",
"public class ImageViewManager extends BaseViewHolderManager<ImageBean> {\n\n\n @Override\n public void onBindViewHolder(@NonNull BaseViewHolder holder, @NonNull ImageBean data) {\n ImageView imageView = getView(holder, R.id.image);\n imageView.setImageResource(data.getImg());\n }\n\n @Override\n protected int getItemLayoutId() {\n return R.layout.item_image;\n }\n\n}"
] | import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.TextView;
import com.freelib.multiitem.adapter.BaseItemAdapter;
import com.freelib.multiitem.demo.bean.ImageBean;
import com.freelib.multiitem.demo.bean.ImageTextBean;
import com.freelib.multiitem.demo.bean.TextBean;
import com.freelib.multiitem.demo.viewholder.FullSpanTextViewManager;
import com.freelib.multiitem.demo.viewholder.ImageAndTextManager;
import com.freelib.multiitem.demo.viewholder.ImageViewManager;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
import java.util.ArrayList;
import java.util.List; | package com.freelib.multiitem.demo;
/**
* 在表格中充满宽度可以时任意ViewHolderManager
* 详见{@link com.freelib.multiitem.adapter.holder.ViewHolderManager#isFullSpan}
* {@link com.freelib.multiitem.adapter.holder.ViewHolderManager#getSpanSize(int)}
*/
@EActivity(R.layout.layout_recycler)
public class FullSpanGridActivity extends AppCompatActivity {
@ViewById(R.id.recyclerView)
protected RecyclerView recyclerView;
public static void startActivity(Context context) {
FullSpanGridActivity_.intent(context).start();
}
@AfterViews
protected void initViews() {
setTitle(R.string.head_foot_grid_title);
recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
//初始化adapter
BaseItemAdapter adapter = new BaseItemAdapter();
//为XXBean数据源注册XXManager管理类
adapter.register(TextBean.class, new FullSpanTextViewManager()); | adapter.register(ImageTextBean.class, new ImageAndTextManager()); | 5 |
chanjarster/artemis-disruptor-miaosha | jms-server/src/main/java/me/chanjar/jms/server/config/ItemAmountUpdateProcessorConfiguration.java | [
"public class DisruptorLifeCycleContainer implements SmartLifecycle {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(DisruptorLifeCycleContainer.class);\n\n private volatile boolean running = false;\n\n private final String disruptorName;\n private final Disruptor disruptor;\n private final int phase;\n\n public DisruptorLifeCycleContainer(String disruptorName, Disruptor disruptor, int phase) {\n this.disruptorName = disruptorName;\n this.disruptor = disruptor;\n this.phase = phase;\n }\n\n @Override\n public boolean isAutoStartup() {\n return true;\n }\n\n @Override\n public void stop(Runnable callback) {\n this.stop();\n callback.run();\n }\n\n @Override\n public void start() {\n LOGGER.info(\"Starting disruptor [{}]\", this.disruptorName);\n disruptor.start();\n this.running = true;\n }\n\n @Override\n public void stop() {\n LOGGER.info(\"Shutdown disruptor [{}]\", this.disruptorName);\n disruptor.shutdown();\n this.running = false;\n }\n\n @Override\n public boolean isRunning() {\n return this.running;\n }\n\n @Override\n public int getPhase() {\n return this.phase;\n }\n}",
"public abstract class StartupOrderConstants {\n\n public static final int DISRUPTOR_REQUEST_DTO = 1;\n public static final int DISRUPTOR_ORDER_INSERT = 2;\n public static final int DISRUPTOR_ITEM_UPDATE = 3;\n\n private StartupOrderConstants() {\n // singleton\n }\n\n}",
"public interface CommandDispatcher {\n\n void dispatch(Command command);\n\n void registerCommandProcessor(CommandProcessor commandProcessor);\n\n}",
"public class ItemAmountUpdateCommand extends Command {\n\n private static final long serialVersionUID = 7896607558242859910L;\n private final Long itemId;\n\n private final int amount;\n\n /**\n * @param requestId Command来源的requestId\n * @param itemId 商品ID\n * @param amount 库存\n */\n public ItemAmountUpdateCommand(String requestId, Long itemId, int amount) {\n super(requestId);\n this.itemId = itemId;\n this.amount = amount;\n }\n\n public Long getItemId() {\n return itemId;\n }\n\n public int getAmount() {\n return amount;\n }\n\n @Override\n public boolean equals(Object o) {\n if (this == o) return true;\n if (o == null || getClass() != o.getClass()) return false;\n\n ItemAmountUpdateCommand that = (ItemAmountUpdateCommand) o;\n\n if (amount != that.amount) return false;\n return itemId != null ? itemId.equals(that.itemId) : that.itemId == null;\n }\n\n @Override\n public int hashCode() {\n int result = itemId != null ? itemId.hashCode() : 0;\n result = 31 * result + amount;\n return result;\n }\n\n @Override\n public String toString() {\n return new ToStringBuilder(this)\n .append(\"id\", id)\n .append(\"requestId\", requestId)\n .append(\"itemId\", itemId)\n .append(\"amount\", amount)\n .toString();\n }\n\n}",
"public class ItemAmountUpdateCommandBuffer implements CommandBuffer<ItemAmountUpdateCommand> {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(ItemAmountUpdateCommandBuffer.class);\n\n private final Map<Long, ItemAmountUpdateCommand> commandMap = new HashMap<>();\n\n private final int capacity;\n\n public ItemAmountUpdateCommandBuffer(int capacity) {\n this.capacity = capacity;\n }\n\n @Override\n public boolean hasRemaining() {\n return commandMap.size() < this.capacity;\n }\n\n /**\n * @param command\n * @throws CommandBufferOverflowException\n */\n @Override\n public void put(ItemAmountUpdateCommand command) {\n\n Long key = command.getItemId();\n if (!hasRemaining() && commandMap.get(key) == null) {\n throw new CommandBufferOverflowException();\n }\n\n ItemAmountUpdateCommand prevValue = this.commandMap.put(key, command);\n if (prevValue != null) {\n LOGGER.info(\"Optimized\", command);\n }\n LOGGER.info(\"Put\", command);\n\n }\n\n @Override\n public void clear() {\n commandMap.clear();\n }\n\n @Override\n public List<ItemAmountUpdateCommand> get() {\n return new ArrayList<>(commandMap.values());\n }\n\n}",
"public class ItemAmountUpdateCommandExecutor implements CommandExecutor<ItemAmountUpdateCommandBuffer> {\n\n private static final Logger LOGGER = LoggerFactory.getLogger(ItemAmountUpdateCommandExecutor.class);\n\n private static final String SQL = \"UPDATE ITEM SET AMOUNT = ? WHERE ID = ?\";\n\n private JdbcTemplate jdbcTemplate;\n\n public ItemAmountUpdateCommandExecutor(JdbcTemplate jdbcTemplate) {\n this.jdbcTemplate = jdbcTemplate;\n }\n\n @Override\n public void execute(ItemAmountUpdateCommandBuffer commandBuffer) {\n\n List<ItemAmountUpdateCommand> commands = commandBuffer.get();\n if (CollectionUtils.isEmpty(commands)) {\n return;\n }\n\n List<Object[]> args = commands.stream().map(cmd -> new Object[] { cmd.getAmount(), cmd.getItemId() })\n .collect(toList());\n try {\n\n jdbcTemplate.batchUpdate(SQL, args);\n commands.forEach(command -> LOGGER.info(\"Executed\", command));\n\n } catch (Exception e) {\n\n commands.forEach(command -> LOGGER.error(\"Failed\", command));\n LOGGER.error(ExceptionUtils.getStackTrace(e));\n\n }\n }\n\n}",
"public class ItemAmountUpdateCommandProcessor implements CommandProcessor<ItemAmountUpdateCommand> {\n\n private final CommandEventProducer<ItemAmountUpdateCommand>[] commandEventProducerList;\n\n private final int producerCount;\n\n public ItemAmountUpdateCommandProcessor(\n CommandEventProducer<ItemAmountUpdateCommand>[] commandEventProducerList) {\n this.commandEventProducerList = commandEventProducerList;\n this.producerCount = commandEventProducerList.length;\n }\n\n @Override\n public Class<ItemAmountUpdateCommand> getMatchClass() {\n return ItemAmountUpdateCommand.class;\n }\n\n @Override\n public void process(ItemAmountUpdateCommand command) {\n\n int index = (int) (command.getItemId() % (long) this.producerCount);\n commandEventProducerList[index].onData(command);\n\n }\n\n}",
"public abstract class BeanRegisterUtils {\n\n private BeanRegisterUtils() {\n }\n\n public static void registerSingleton(ApplicationContext applicationContext, String beanName, Object singletonObject) {\n\n AutowireCapableBeanFactory beanFactory = applicationContext.getAutowireCapableBeanFactory();\n if (!SingletonBeanRegistry.class.isAssignableFrom(beanFactory.getClass())) {\n throw new IllegalArgumentException(\n \"ApplicationContext: \" + applicationContext.getClass().toString()\n + \" doesn't implements SingletonBeanRegistry, cannot register JMS connection at runtime\");\n }\n\n SingletonBeanRegistry beanDefinitionRegistry = (SingletonBeanRegistry) beanFactory;\n beanDefinitionRegistry.registerSingleton(beanName, singletonObject);\n\n }\n\n public static void registerSingleton(BeanDefinitionRegistry registry, String beanName, Object singletonObject) {\n\n if (!SingletonBeanRegistry.class.isAssignableFrom(registry.getClass())) {\n throw new IllegalArgumentException(\n \"BeanDefinitionRegistry: \" + registry.getClass().toString()\n + \" doesn't implements SingletonBeanRegistry, cannot register JMS connection at runtime\");\n }\n\n SingletonBeanRegistry beanDefinitionRegistry = (SingletonBeanRegistry) registry;\n beanDefinitionRegistry.registerSingleton(beanName, singletonObject);\n\n }\n\n}"
] | import com.lmax.disruptor.dsl.Disruptor;
import me.chanjar.jms.base.lifecycle.DisruptorLifeCycleContainer;
import me.chanjar.jms.server.StartupOrderConstants;
import me.chanjar.jms.server.command.infras.CommandDispatcher;
import me.chanjar.jms.server.command.infras.disruptor.*;
import me.chanjar.jms.server.command.item.ItemAmountUpdateCommand;
import me.chanjar.jms.server.command.item.ItemAmountUpdateCommandBuffer;
import me.chanjar.jms.server.command.item.ItemAmountUpdateCommandExecutor;
import me.chanjar.jms.server.command.item.ItemAmountUpdateCommandProcessor;
import me.chanjar.jms.base.utils.BeanRegisterUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.concurrent.Executors; | package me.chanjar.jms.server.config;
@Configuration
@EnableConfigurationProperties(ItemAmountUpdateProcessorConfiguration.Conf.class)
public class ItemAmountUpdateProcessorConfiguration implements ApplicationContextAware {
@Autowired
private Conf conf;
@Autowired | private CommandDispatcher commandDispatcher; | 2 |
Qihoo360/RePlugin | replugin-host-library/replugin-host-lib/src/main/java/com/qihoo360/loader2/Loader.java | [
"public class RePlugin {\n\n static final String TAG = \"RePlugin\";\n\n /**\n * 表示目标进程根据实际情况自动调配\n */\n public static final String PROCESS_AUTO = \"\" + IPluginManager.PROCESS_AUTO;\n\n /**\n * 表示目标为UI进程\n */\n public static final String PROCESS_UI = \"\" + IPluginManager.PROCESS_UI;\n\n /**\n * 表示目标为常驻进程(名字可变,见BuildConfig内字段)\n */\n public static final String PROCESS_PERSIST = \"\" + IPluginManager.PROCESS_PERSIST;\n\n /**\n * 安装此插件 <p>\n * 注意: <p>\n * 1、这里只将APK移动(或复制)到“插件路径”下,不释放优化后的Dex和Native库,不会加载插件 <p>\n * 2、支持“纯APK”和“p-n”(旧版,即将废弃)插件 <p>\n * 3、此方法是【同步】的,耗时较少\n *\n * @param path 插件安装的地址。必须是“绝对路径”。通常可以用context.getFilesDir()来做\n * @return 安装成功的插件信息,外界可直接读取\n * @since 2.0.0 (1.x版本为installDelayed)\n */\n public static PluginInfo install(String path) {\n if (!RePluginFramework.mHostInitialized) {\n return null;\n }\n\n try {\n Object obj = ProxyRePluginVar.install.call(null, path);\n if (obj != null) {\n // 跨ClassLoader进行parcel对象的构造\n Parcel p = ParcelUtils.createFromParcelable((Parcelable) obj);\n return PluginInfo.CREATOR.createFromParcel(p);\n }\n } catch (Exception e) {\n if (LogDebug.LOG) {\n e.printStackTrace();\n }\n }\n return null;\n }\n\n /**\n * 预加载此插件。此方法会立即释放优化后的Dex和Native库,但不会运行插件代码。 <p>\n * 具体用法可参见preload(PluginInfo)的说明\n *\n * @param pluginName 要加载的插件名\n * @return 预加载是否成功\n * @see #preload(PluginInfo)\n * @since 2.0.0\n */\n public static boolean preload(String pluginName) {\n if (!RePluginFramework.mHostInitialized) {\n return false;\n }\n\n try {\n Object obj = ProxyRePluginVar.preload.call(null, pluginName);\n if (obj != null) {\n return (Boolean) obj;\n }\n } catch (Exception e) {\n if (LogDebug.LOG) {\n e.printStackTrace();\n }\n }\n\n return false;\n }\n\n /**\n * 预加载此插件。此方法会立即释放优化后的Dex和Native库,但不会运行插件代码。 <p>\n * 使用场景:在“安装”完成后“提前释放Dex”(时间算在“安装过程”中)。这样下次启动插件时则速度飞快 <p>\n * 注意: <p>\n * 1、该方法非必须调用(见“使用场景”)。换言之,只要涉及到插件加载,就会自动完成preload操作,无需开发者关心 <p>\n * 2、Dex和Native库会占用大量的“内部存储空间”。故除非插件是“确定要用的”,否则不必在安装完成后立即调用此方法 <p>\n * 3、该方法为【同步】调用,且耗时较久(尤其是dex2oat的过程),建议在线程中使用\n *\n * @param pi 要加载的插件信息\n * @return 预加载是否成功\n * @hide\n * @see #install(String)\n * @since 2.0.0\n */\n public static boolean preload(PluginInfo pi) {\n if (!RePluginFramework.mHostInitialized) {\n return false;\n }\n\n try {\n // 跨classloader创建PluginInfo对象\n // TODO 如果有更优雅的方式,可优化\n Object p = ParcelUtils.createFromParcelable(pi, RePluginEnv.getHostCLassLoader(), \"com.qihoo360.replugin.model.PluginInfo\");\n Object obj = ProxyRePluginVar.preload2.call(null, p);\n if (obj != null) {\n return (Boolean) obj;\n }\n } catch (Exception e) {\n if (LogDebug.LOG) {\n e.printStackTrace();\n }\n }\n\n return false;\n }\n\n /**\n * 开启一个插件的Activity <p>\n * 其中Intent的ComponentName的Key应为插件名(而不是包名),可使用createIntent方法来创建Intent对象\n *\n * @param context Context对象\n * @param intent 要打开Activity的Intent,其中ComponentName的Key必须为插件名\n * @return 插件Activity是否被成功打开?\n * FIXME 是否需要Exception来做?\n * @see #createIntent(String, String)\n * @since 1.0.0\n */\n public static boolean startActivity(Context context, Intent intent) {\n if (!RePluginFramework.mHostInitialized) {\n return false;\n }\n\n try {\n Object obj = ProxyRePluginVar.startActivity.call(null, context, intent);\n if (obj != null) {\n return (Boolean) obj;\n }\n } catch (Exception e) {\n if (LogDebug.LOG) {\n e.printStackTrace();\n }\n }\n\n return false;\n }\n\n /**\n * 开启一个插件的Activity,无需调用createIntent或设置ComponentName来修改Intent\n *\n * @param context Context对象\n * @param intent 要打开Activity的Intent,其中ComponentName的Key必须为插件名\n * @param pluginName 插件名。稍后会填充到Intent中\n * @param activity 插件的Activity。稍后会填充到Intent中\n * @see #startActivity(Context, Intent)\n * @since 1.0.0\n */\n public static boolean startActivity(Context context, Intent intent, String pluginName, String activity) {\n if (!RePluginFramework.mHostInitialized) {\n return false;\n }\n\n try {\n Object obj = ProxyRePluginVar.startActivity2.call(null, context, intent, pluginName, activity);\n if (obj != null) {\n return (Boolean) obj;\n }\n } catch (Exception e) {\n if (LogDebug.LOG) {\n e.printStackTrace();\n }\n }\n\n return false;\n }\n\n /**\n * 通过 forResult 方式启动一个插件的 Activity\n *\n * @param activity 源 Activity\n * @param intent 要打开 Activity 的 Intent,其中 ComponentName 的 Key 必须为插件名\n * @param requestCode 请求码\n * @see #startActivityForResult(Activity, Intent, int, Bundle)\n * @since 2.1.3\n */\n public static boolean startActivityForResult(Activity activity, Intent intent, int requestCode) {\n if (!RePluginFramework.mHostInitialized) {\n return false;\n }\n\n try {\n Object obj = ProxyRePluginVar.startActivityForResult.call(null, activity, intent, requestCode);\n if (obj != null) {\n return (Boolean) obj;\n }\n } catch (Exception e) {\n if (LogDebug.LOG) {\n e.printStackTrace();\n }\n }\n\n return false;\n }\n\n /**\n * 通过 forResult 方式启动一个插件的 Activity\n *\n * @param activity 源 Activity\n * @param intent 要打开 Activity 的 Intent,其中 ComponentName 的 Key 必须为插件名\n * @param requestCode 请求码\n * @param options 附加的数据\n * @see #startActivityForResult(Activity, Intent, int, Bundle)\n * @since 2.1.3\n */\n public static boolean startActivityForResult(Activity activity, Intent intent, int requestCode, Bundle options) {\n if (!RePluginFramework.mHostInitialized) {\n return false;\n }\n\n try {\n Object obj = ProxyRePluginVar.startActivityForResult2.call(null, activity, intent, requestCode, options);\n if (obj != null) {\n return (Boolean) obj;\n }\n } catch (Exception e) {\n if (LogDebug.LOG) {\n e.printStackTrace();\n }\n }\n\n return false;\n }\n\n /**\n * 创建一个用来定向到插件组件的Intent <p>\n * <p>\n * 推荐用法: <p>\n * <code>\n * Intent in = RePlugin.createIntent(\"clean\", \"com.qihoo360.mobilesafe.clean.CleanActivity\");\n * </code> <p>\n * 当然,也可以用标准的Android创建方法: <p>\n * <code>\n * Intent in = new Intent(); <p>\n * in.setComponent(new ComponentName(\"clean\", \"com.qihoo360.mobilesafe.clean.CleanActivity\"));\n * </code>\n *\n * @param pluginName 插件名\n * @param cls 目标全名\n * @return 可以被RePlugin识别的Intent\n * @since 1.0.0\n */\n public static Intent createIntent(String pluginName, String cls) {\n if (!RePluginFramework.mHostInitialized) {\n return null;\n }\n\n try {\n return (Intent) ProxyRePluginVar.createIntent.call(null, pluginName, cls);\n } catch (Exception e) {\n if (LogDebug.LOG) {\n e.printStackTrace();\n }\n }\n\n return null;\n }\n\n /**\n * 创建一个用来定向到插件组件的ComponentName,其Key为插件名,Value为目标组件的类全名\n *\n * @param pluginName 插件名\n * @param cls 目标组件全名\n * @return 一个修改过的ComponentName对象\n * @since 1.0.0\n */\n public static ComponentName createComponentName(String pluginName, String cls) {\n if (!RePluginFramework.mHostInitialized) {\n return null;\n }\n\n try {\n return (ComponentName) ProxyRePluginVar.createComponentName.call(null, pluginName, cls);\n } catch (Exception e) {\n if (LogDebug.LOG) {\n e.printStackTrace();\n }\n }\n\n return null;\n }\n\n /**\n * 是否使用Dev版AAR?可支持一些\"调试特性\",但该AAR【千万不要用于发布环境】 <p>\n * Dev版的AAR可支持如下特性: <p>\n * 1、插件签名不正确时仍允许被安装进来,这样利于调试(发布环境上则容易导致严重安全隐患) <p>\n * 2、可以打出一些完整的日志(发布环境上则容易被逆向,进而对框架稳定性、私密性造成严重影响)\n *\n * @return 是否使用Dev版的AAR?\n * @since 1.0.0\n */\n public static boolean isForDev() {\n if (!RePluginFramework.mHostInitialized) {\n return false;\n }\n\n try {\n Object obj = ProxyRePluginVar.isForDev.call(null);\n if (obj != null) {\n return (Boolean) obj;\n }\n } catch (Exception e) {\n if (LogDebug.LOG) {\n e.printStackTrace();\n }\n }\n\n return false;\n }\n\n /**\n * 获取当前版本\n *\n * @return 版本号,如2.2.2等\n * @since 2.2.2\n */\n public static String getVersion() {\n if (!RePluginFramework.mHostInitialized) {\n return null;\n }\n\n try {\n return (String) ProxyRePluginVar.getVersion.call(null);\n } catch (Exception e) {\n if (LogDebug.LOG) {\n e.printStackTrace();\n }\n }\n\n return null;\n }\n\n /**\n * 获取SDK的版本信息\n *\n * @return SDK的版本,如2.0.0等\n * @since 2.0.0\n * @deprecated 已废弃,请使用 getVersion() 方法\n */\n public static String getSDKVersion() {\n return getVersion();\n }\n\n /**\n * 加载插件,并获取插件的包信息 <p>\n * 注意:这里会尝试加载插件,并释放其Jar包。但不会读取资源,也不会释放oat/odex <p>\n * 性能消耗(小 → 大):ComponentList/PackageInfo(This) < Resources < ClassLoader < Context < Binder\n *\n * @param pluginName 插件名\n * @return PackageInfo对象\n * @see PackageInfo\n * @since 1.0.0\n */\n public static PackageInfo fetchPackageInfo(String pluginName) {\n if (!RePluginFramework.mHostInitialized) {\n return null;\n }\n\n try {\n return (PackageInfo) ProxyRePluginVar.fetchPackageInfo.call(null, pluginName);\n } catch (Exception e) {\n if (LogDebug.LOG) {\n e.printStackTrace();\n }\n }\n\n return null;\n }\n\n /**\n * 加载插件,并获取插件的资源信息 <p>\n * 注意:这里会尝试安装插件,并释放其Jar包,读取资源,但不会释放oat/odex。 <p>\n * 性能消耗(小 → 大):ComponentList/PackageInfo < Resources(This) < ClassLoader < Context < Binder\n *\n * @param pluginName 插件名\n * @return Resources对象\n * @see Resources\n * @since 1.0.0\n */\n public static Resources fetchResources(String pluginName) {\n if (!RePluginFramework.mHostInitialized) {\n return null;\n }\n\n try {\n return (Resources) ProxyRePluginVar.fetchResources.call(null, pluginName);\n } catch (Exception e) {\n if (LogDebug.LOG) {\n e.printStackTrace();\n }\n }\n\n return null;\n }\n\n /**\n * 加载插件,并获取插件自身的ClassLoader对象,以调用插件内部的类 <p>\n * 注意:这里会尝试安装插件,并同时加载资源和代码,耗时可能较久 <p>\n * 性能消耗(小 → 大):ComponentList/PackageInfo < Resources < ClassLoader(This) < Context < Binder\n *\n * @param pluginName 插件名\n * @return 插件的ClassLoader对象\n * @since 1.0.0\n */\n public static ClassLoader fetchClassLoader(String pluginName) {\n if (!RePluginFramework.mHostInitialized) {\n return null;\n }\n\n try {\n return (ClassLoader) ProxyRePluginVar.fetchClassLoader.call(null, pluginName);\n } catch (Exception e) {\n if (LogDebug.LOG) {\n e.printStackTrace();\n }\n }\n\n return null;\n }\n\n /**\n * 加载插件,并获取插件自身的Context对象,以获取资源等信息 <p>\n * 注意:这里会尝试安装插件,并同时加载资源和代码,耗时可能较久 <p>\n * 性能消耗(小 → 大):ComponentList/PackageInfo < Resources < ClassLoader < Context(This) < Binder\n *\n * @param pluginName 插件名\n * @return 插件的Context对象\n * @since 1.0.0\n */\n public static Context fetchContext(String pluginName) {\n if (!RePluginFramework.mHostInitialized) {\n return null;\n }\n\n try {\n return (Context) ProxyRePluginVar.fetchContext.call(null, pluginName);\n } catch (Exception e) {\n if (LogDebug.LOG) {\n e.printStackTrace();\n }\n }\n\n return null;\n }\n\n\n /**\n * 加载插件,并通过插件里的Plugin类,获取插件定义的IBinder <p>\n * 注意:这里会尝试安装插件,并同时加载资源和代码,耗时可能较久 <p>\n * 性能消耗(小 → 大):ComponentList/PackageInfo < Resources < Context/ClassLoader < Binder(This) <p>\n * <p>\n * PluginBinder(如使用使用本方法)和GlobalBinder类方法(如getGlobalBinder)的不同: <p>\n * 1、PluginBinder需要指定插件;GlobalBinder无需指定 <p>\n * 2、PluginBinder获取的是插件内部已定义好的Binder;GlobalBinder在获取时必须先在代码中注册\n *\n * @param pluginName 插件名\n * @param module 要加载的插件模块\n * @param process 进程名 TODO 现阶段只能使用IPluginManager中的值,请务必使用它们,否则会出现问题\n * @return 返回插件定义的IBinder对象,供外界使用\n * @see #getGlobalBinder(String)\n * @since 1.0.0\n */\n public static IBinder fetchBinder(String pluginName, String module, String process) {\n if (!RePluginFramework.mHostInitialized) {\n return null;\n }\n\n try {\n return (IBinder) ProxyRePluginVar.fetchBinder2.call(null, pluginName, module, process);\n } catch (Exception e) {\n if (LogDebug.LOG) {\n e.printStackTrace();\n }\n }\n\n return null;\n }\n\n /**\n * 在当前进程加载插件,并通过插件里的Plugin类,获取插件定义的IBinder <p>\n * 注意:这里会尝试安装插件,并同时加载资源和代码,耗时可能较久 <p>\n * 性能消耗(小 → 大):ComponentList/PackageInfo < Resources < Context/ClassLoader < Binder(This) <p>\n * <p>\n * PluginBinder(如使用使用本方法)和GlobalBinder类方法(如getGlobalBinder)的不同: <p>\n * 1、PluginBinder需要指定插件;GlobalBinder无需指定 <p>\n * 2、PluginBinder获取的是插件内部已定义好的Binder;GlobalBinder在获取时必须先在代码中注册\n *\n * @param pluginName 插件名\n * @param module 要加载的插件模块\n * @return 返回插件定义的IBinder对象,供外界使用\n * @see #getGlobalBinder(String)\n * @since 1.0.0\n */\n public static IBinder fetchBinder(String pluginName, String module) {\n if (!RePluginFramework.mHostInitialized) {\n return null;\n }\n\n try {\n return (IBinder) ProxyRePluginVar.fetchBinder.call(null, pluginName, module);\n } catch (Exception e) {\n if (LogDebug.LOG) {\n e.printStackTrace();\n }\n }\n\n return null;\n }\n\n /**\n * 通过ClassLoader对象来获取该ClassLoader应属于哪个插件\n * <p>\n * 该方法消耗非常小,可直接使用\n *\n * @param cl ClassLoader对象\n * @return 插件名\n * @since 1.0.0\n */\n public static String fetchPluginNameByClassLoader(ClassLoader cl) {\n if (!RePluginFramework.mHostInitialized) {\n return null;\n }\n\n try {\n return (String) ProxyRePluginVar.fetchPluginNameByClassLoader.call(null, cl);\n } catch (Exception e) {\n if (LogDebug.LOG) {\n e.printStackTrace();\n }\n }\n\n return null;\n }\n\n /**\n * 通过资源名(包括前缀和具体名字),来获取指定插件里的资源的ID\n * <p>\n * 性能消耗:等同于 fetchResources\n *\n * @param pluginName 插件名\n * @param resTypeAndName 要获取的“资源类型+资源名”,格式为:“[type]/[name]”。例如: <p>\n * → layout/common_title → 从“布局”里获取common_title的ID <p>\n * → drawable/common_bg → 从“可绘制图片”里获取common_bg的ID <p>\n * 详细见Android官方的说明\n * @return 资源的ID。若为0,则表示资源没有找到,无法使用\n * @since 2.2.0 (老的host-lib版本也能使用)\n */\n public static int fetchResourceIdByName(String pluginName, String resTypeAndName) {\n if (!RePluginFramework.mHostInitialized) {\n return 0;\n }\n return RePluginCompat.fetchResourceIdByName(pluginName, resTypeAndName);\n }\n\n /**\n * 通过Layout名,来获取插件内的View,并自动做“强制类型转换”(也可直接使用View类型) <p>\n * 注意:若使用的是公共库,则务必按照Provided的形式引入,否则会出现“不同ClassLoader”导致的ClassCastException <p>\n * 当然,非公共库不受影响,但请务必使用Android Framework内的View(例如WebView、ViewGroup等),或索性直接使用View\n *\n * @param pluginName 插件名\n * @param layoutName Layout名字\n * @param root Optional view to be the parent of the generated hierarchy.\n * @return 插件的View。若为Null则表示获取失败\n * @throws ClassCastException 若不是想要的那个View类型,或者ClassLoader不同,则可能会出现此异常。应确保View类型正确\n * @since 2.2.0 (老的host-lib版本也能使用)\n */\n public static <T extends View> T fetchViewByLayoutName(String pluginName, String layoutName, ViewGroup root) {\n if (!RePluginFramework.mHostInitialized) {\n return null;\n }\n return RePluginCompat.fetchViewByLayoutName(pluginName, layoutName, root);\n }\n\n /**\n * 获取所有插件的列表(指已安装的)\n *\n * @return PluginInfo的表\n * @since 2.0.0(1.x版本为getExistPlugins)\n */\n public static List<PluginInfo> getPluginInfoList() {\n if (!RePluginFramework.mHostInitialized) {\n return null;\n }\n\n try {\n List list = (List) ProxyRePluginVar.getPluginInfoList.call(null);\n if (list != null && list.size() > 0) {\n List<PluginInfo> ret = new ArrayList<>();\n for (Object o : list) {\n // 跨ClassLoader进行parcel对象的构造\n Parcel p = ParcelUtils.createFromParcelable((Parcelable) o);\n PluginInfo nPi = PluginInfo.CREATOR.createFromParcel(p);\n ret.add(nPi);\n }\n\n return ret;\n }\n } catch (Exception e) {\n if (LogDebug.LOG) {\n e.printStackTrace();\n }\n }\n\n return null;\n }\n\n /**\n * 获取指定插件的信息\n *\n * @param name 插件名\n * @return PluginInfo对象\n * @since 1.2.0\n */\n public static PluginInfo getPluginInfo(String name) {\n if (!RePluginFramework.mHostInitialized) {\n return null;\n }\n\n try {\n Object obj = ProxyRePluginVar.getPluginInfo.call(null, name);\n if (obj != null) {\n // 跨ClassLoader进行parcel对象的构造\n Parcel p = ParcelUtils.createFromParcelable((Parcelable) obj);\n return PluginInfo.CREATOR.createFromParcel(p);\n }\n } catch (Exception e) {\n if (LogDebug.LOG) {\n e.printStackTrace();\n }\n }\n\n return null;\n }\n\n /**\n * 获取当前插件的版本号,可以是VersionCode,也可以是meta-data中的ver。\n *\n * @param name 插件名\n * @return 插件版本号。若为-1则表示插件不存在\n * @since 2.0.0\n */\n public static int getPluginVersion(String name) {\n if (!RePluginFramework.mHostInitialized) {\n return -1;\n }\n\n try {\n Object obj = ProxyRePluginVar.getPluginVersion.call(null, name);\n if (obj != null) {\n return (Integer) obj;\n }\n } catch (Exception e) {\n if (LogDebug.LOG) {\n e.printStackTrace();\n }\n }\n\n return -1;\n }\n\n /**\n * 判断插件是否已被安装(但不一定被使用过,如可能不会释放Dex、Native库等) <p>\n * 注意:RePlugin 1.x版本中,isPluginInstalled方法等于现在的isPluginUsed,故含义有变\n *\n * @param pluginName 插件名\n * @return 是否被安装\n * @since 2.0.0 (1.x版本为isPluginExists)\n */\n public static boolean isPluginInstalled(String pluginName) {\n if (!RePluginFramework.mHostInitialized) {\n return false;\n }\n\n try {\n Object obj = ProxyRePluginVar.isPluginInstalled.call(null, pluginName);\n if (obj != null) {\n return (Boolean) obj;\n }\n } catch (Exception e) {\n if (LogDebug.LOG) {\n e.printStackTrace();\n }\n }\n\n return false;\n }\n\n /**\n * 判断插件是否曾被使用过。只要释放过Dex、Native的,就认为是“使用过”的 <p>\n * 和isPluginDexExtracted的区别:插件会在升级完成后,会删除旧Dex。其isPluginDexExtracted为false,而isPluginUsed仍为true\n *\n * @param pluginName 插件名\n * @return 插件是否已被使用过\n * @since 2.0.0\n */\n public static boolean isPluginUsed(String pluginName) {\n if (!RePluginFramework.mHostInitialized) {\n return false;\n }\n\n try {\n Object obj = ProxyRePluginVar.isPluginUsed.call(null, pluginName);\n if (obj != null) {\n return (Boolean) obj;\n }\n } catch (Exception e) {\n if (LogDebug.LOG) {\n e.printStackTrace();\n }\n }\n\n return false;\n }\n\n /**\n * 判断当前插件是否已释放了Dex、Native库等\n *\n * @param pluginName 插件名\n * @return 是否已被使用过\n * @since 2.0.0 (原为isPluginInstalled)\n */\n public static boolean isPluginDexExtracted(String pluginName) {\n if (!RePluginFramework.mHostInitialized) {\n return false;\n }\n\n try {\n Object obj = ProxyRePluginVar.isPluginDexExtracted.call(null, pluginName);\n if (obj != null) {\n return (Boolean) obj;\n }\n } catch (Exception e) {\n if (LogDebug.LOG) {\n e.printStackTrace();\n }\n }\n\n return false;\n }\n\n /**\n * 当前插件是否在运行。只要任意进程在,就都属于此情况\n *\n * @param pluginName 插件名\n * @return 插件是否正在被运行\n * @since 2.0.0\n */\n public static boolean isPluginRunning(String pluginName) {\n if (!RePluginFramework.mHostInitialized) {\n return false;\n }\n\n try {\n Object obj = ProxyRePluginVar.isPluginRunning.call(null, pluginName);\n if (obj != null) {\n return (Boolean) obj;\n }\n } catch (Exception e) {\n if (LogDebug.LOG) {\n e.printStackTrace();\n }\n }\n\n return false;\n }\n\n /**\n * 当前插件是否在指定进程中运行\n *\n * @param pluginName 插件名\n * @param process 指定的进程名,必须为全名\n * @return 插件是否在指定进程中运行\n * @since 2.0.0\n */\n public static boolean isPluginRunningInProcess(String pluginName, String process) {\n if (!RePluginFramework.mHostInitialized) {\n return false;\n }\n\n try {\n Object obj = ProxyRePluginVar.isPluginRunningInProcess.call(null, pluginName, process);\n if (obj != null) {\n return (Boolean) obj;\n }\n } catch (Exception e) {\n if (LogDebug.LOG) {\n e.printStackTrace();\n }\n }\n\n return false;\n }\n\n /**\n * 获取所有正在运行的插件列表\n *\n * @return 所有正在运行的插件的List\n * @see PluginRunningList\n * @since 2.0.0\n */\n public static PluginRunningList getRunningPlugins() {\n if (!RePluginFramework.mHostInitialized) {\n return null;\n }\n\n try {\n Object obj = ProxyRePluginVar.getRunningPlugins.call(null);\n if (obj != null) {\n // 跨ClassLoader创建parcelable对象\n Parcel p = ParcelUtils.createFromParcelable((Parcelable) obj);\n PluginRunningList.CREATOR.createFromParcel(p);\n }\n } catch (Exception e) {\n if (LogDebug.LOG) {\n e.printStackTrace();\n }\n }\n // FIXME\n return null;\n }\n\n /**\n * 获取正在运行此插件的进程名列表 <p>\n * 若要获取PID,可在拿到列表后,通过IPC.getPidByProcessName来反查\n *\n * @param pluginName 要查询的插件名\n * @return 正在运行此插件的进程名列表。一定不会为Null\n * @since 2.0.0\n */\n public static String[] getRunningProcessesByPlugin(String pluginName) {\n if (!RePluginFramework.mHostInitialized) {\n return null;\n }\n\n try {\n return (String[]) ProxyRePluginVar.getRunningProcessesByPlugin.call(null, pluginName);\n } catch (Exception e) {\n if (LogDebug.LOG) {\n e.printStackTrace();\n }\n }\n\n return null;\n }\n\n /**\n * 当前是否处于\"常驻进程\"?\n *\n * @return 是否处于常驻进程\n * @since 1.1.0\n */\n public static boolean isCurrentPersistentProcess() {\n if (!RePluginFramework.mHostInitialized) {\n return false;\n }\n\n try {\n Object obj = ProxyRePluginVar.isCurrentPersistentProcess.call(null);\n if (obj != null) {\n return (Boolean) obj;\n }\n } catch (Exception e) {\n if (LogDebug.LOG) {\n e.printStackTrace();\n }\n }\n\n return false;\n }\n\n /**\n * 注册“安装完成后的通知”广播 <p>\n * 此为“本地”广播,插件内也可以接收到。开发者也可以自行注册,做法: <p>\n * <code>\n * IntentFilter itf = new IntentFilter(MP.ACTION_NEW_PLUGIN); <p>\n * LocalBroadcastManager.getInstance(context).registerReceiver(r, itf);\n * </code>\n *\n * @param context Context对象\n * @param r 要绑定的BroadcastReceiver对象\n * @since 1.0.0\n */\n public static void registerInstalledReceiver(Context context, BroadcastReceiver r) {\n if (!RePluginFramework.mHostInitialized) {\n return;\n }\n\n ProxyRePluginVar.registerInstalledReceiver.call(null, context, r);\n }\n\n /**\n * 注册一个无需插件名,可被全局使用的Binder对象。Binder对象必须事先创建好 <p>\n * 有关GlobalBinder的详细介绍,请参见getGlobalBinder的说明 <p>\n * 有关此方法和registerGlobalBinderDelayed的区别,请参见其方法说明。\n *\n * @param name Binder的描述名\n * @param binder Binder对象\n * @return 是否注册成功\n * @see #getGlobalBinder(String)\n * @see #registerGlobalBinderDelayed(String, IBinderGetter)\n * @since 1.2.0\n */\n public static boolean registerGlobalBinder(String name, IBinder binder) {\n\n if (!RePluginFramework.mHostInitialized) {\n return false;\n }\n\n Object obj = ProxyRePluginVar.registerGlobalBinder.call(null, name, binder);\n\n if (obj != null) {\n return (Boolean) obj;\n }\n\n return false;\n }\n\n /**\n * 注册一个无需插件名,可被全局使用的Binder对象,但Binder对象只有在“用到时”才会被创建 <p>\n * 有关GlobalBinder的详细介绍,请参见getGlobalBinder的说明 <p>\n * <p>\n * 和registerGlobalBinder不同的是: <p>\n * 1、前者的binder对象必须事先创建好并传递到参数中 <p>\n * 适用于Binder在注册时就立即创建(性能消耗小),或未来使用频率非常多的情况。如“用户账号服务”、“基础服务”等 <p>\n * 2、后者会在getGlobalBinder指定的name被首次调用后,才会尝试获取Binder对象 <p>\n * 适用于Binder只在使用时才被创建(确保启动性能快),或未来调用频率较少的情况。如“Root服务”、“特色功能服务”等 <p>\n *\n * @param name Binder的描述名\n * @param getter 当getGlobalBinder调用时匹配到name后,会调用getter.get()方法来获取IBinder对象\n * @return 是否延迟注册成功\n * @since 2.1.0 前面的sdk版本没有keepIBinderGetter\n */\n public static boolean registerGlobalBinderDelayed(String name, IBinderGetter getter) {\n if (!RePluginFramework.mHostInitialized) {\n return false;\n }\n\n try {\n Object obj = ProxyRePluginVar.registerGlobalBinderDelayed.call(null, name, getter);\n if (obj != null) {\n return (Boolean) obj;\n }\n } catch (Exception e) {\n if (LogDebug.LOG) {\n e.printStackTrace();\n }\n }\n\n return false;\n }\n\n /**\n * 取消全局Binder对象的注册。这样当调用getGlobalBinder时将不再返回结果 <p>\n * 有关globalBinder的详细介绍,请参见registerGlobalBinder的说明\n *\n * @param name Binder的描述名\n * @return 是否取消成功\n * @see #getGlobalBinder(String)\n * @since 1.2.0\n */\n public static boolean unregisterGlobalBinder(String name) {\n if (!RePluginFramework.mHostInitialized) {\n return false;\n }\n\n try {\n Object obj = ProxyRePluginVar.unregisterGlobalBinder.call(null, name);\n if (obj != null) {\n return (Boolean) obj;\n }\n } catch (Exception e) {\n if (LogDebug.LOG) {\n e.printStackTrace();\n }\n }\n\n return false;\n }\n\n public static IBinder getGlobalBinder(String name) {\n if (!RePluginFramework.mHostInitialized) {\n return null;\n }\n\n try {\n return (IBinder) ProxyRePluginVar.getGlobalBinder.call(null, name);\n } catch (Exception e) {\n if (LogDebug.LOG) {\n e.printStackTrace();\n }\n }\n\n return null;\n }\n\n /**\n * 注册一个“跳转”类。一旦系统或自身想调用指定类时,将自动跳转到插件里的另一个类。 <p>\n * 例如,系统想访问CallShowService类,但此类在宿主中不存在,只在CallShow中有,则: <p>\n * 未注册“跳转类”时:直接到宿主中寻找CallShowService类,找到后就加载,找不到就崩溃(若不Catch) <p>\n * 注册“挑转类”后,直接将CallShowService的调用“跳转到”插件的CallShowService类中(名字可以不同)。这种情况下,需要调用: <p>\n * <code>\n * RePlugin.registerHookingClass(\"com.qihoo360.mobilesafe.CallShowService\", <p>\n * RePlugin.createComponentName(\"callshow\", \"com.qihoo360.callshow.CallShowService2\"), <p>\n * DummyService.class);\n * </code>\n * <p> <p>\n * 该方法可以玩出很多【新花样】。如,可用于以下场景: <p>\n * <b>* 已在宿主Manifest中声明了插件的四大组件,只是想借助插件化框架来找到该类并加载进来(如前述例子)。</b> <p>\n * <b>* 某些不方便(不好用,或需要云控)的类,想借机替换成插件里的。</b> <p>\n * 如我们有一个LaunchUtils类,现在想使用Utils插件中的同样的类来替代。\n *\n * @param source 要替换的类的全名\n * @param target 要替换的类的目标,需要使用 createComponentName 方法来创建\n * @param defClass 若要替换的类不存在,或插件不可用,则应该使用一个默认的Class。\n * <p>\n * 可替换成如下的形式,也可以传Null。但若访问的是四大组件,传Null可能会导致出现App崩溃(且无法被Catch)\n * <p>\n * DummyService.class\n * <p>\n * DummyActivity.class\n * <p>\n * DummyProvider.class\n * <p>\n * DummyReceiver.class\n * @since 1.0.0\n */\n public static void registerHookingClass(String source, ComponentName target, Class defClass) {\n if (!RePluginFramework.mHostInitialized) {\n return;\n }\n\n ProxyRePluginVar.registerHookingClass.call(null, source, target, defClass);\n }\n\n /**\n * 查询某个 Component 是否是“跳转”类\n *\n * @param component 要查询的组件信息,其中 packageName 为插件名称,className 为要查询的类名称\n * @since 2.0.0\n */\n public static boolean isHookingClass(ComponentName component) {\n if (!RePluginFramework.mHostInitialized) {\n return false;\n }\n\n try {\n Object obj = ProxyRePluginVar.isHookingClass.call(null, component);\n if (obj != null) {\n return (Boolean) obj;\n }\n } catch (Exception e) {\n if (LogDebug.LOG) {\n e.printStackTrace();\n }\n }\n\n return false;\n }\n\n /**\n * 取消对某个“跳转”类的注册,恢复原状。<p>\n * 请参见 registerHookingClass 的详细说明\n *\n * @param source 要替换的类的全名\n * @see #registerHookingClass(String, ComponentName, Class)\n * @since 2.1.6\n */\n public static void unregisterHookingClass(String source) {\n if (!RePluginFramework.mHostInitialized) {\n return;\n }\n\n ProxyRePluginVar.unregisterHookingClass.call(null, source);\n }\n\n /**\n * 注册一个可供其他模块调用的IBinder,供IPlugin.query使用\n *\n * @param name 注册的IBinder名\n * @param binder 注册的IBinder对象\n */\n public static void registerPluginBinder(String name, IBinder binder) {\n RePluginServiceManager.getInstance().addService(name, binder);\n }\n\n /**\n * 获取宿主的Context\n * @return 宿主的Context\n */\n public static Context getHostContext() {\n return RePluginEnv.getHostContext();\n }\n\n /**\n * 获取宿主的ClassLoader\n * @return 宿主的ClassLoader\n */\n public static ClassLoader getHostClassLoader() {\n return RePluginEnv.getHostCLassLoader();\n }\n\n /**\n * 获取该插件的PluginContext\n * @return\n */\n public static Context getPluginContext() {\n return RePluginEnv.getPluginContext();\n }\n\n /**\n * 判断是否运行在宿主环境中\n * @return 是否运行在宿主环境\n */\n public static boolean isHostInitialized() {\n return RePluginFramework.isHostInitialized();\n }\n\n /**\n * dump RePlugin框架运行时的详细信息,包括:Activity 坑位映射表,正在运行的 Service,以及详细的插件信息\n *\n * @param fd\n * @param writer\n * @param args\n * @since 2.2.2\n */\n public static void dump(FileDescriptor fd, PrintWriter writer, String[] args) {\n if (!RePluginFramework.mHostInitialized) {\n return;\n }\n\n try {\n ProxyRePluginVar.dump.call(null, fd, writer, args);\n } catch (Exception e) {\n if (LogDebug.LOG) {\n e.printStackTrace();\n }\n }\n }\n\n static class ProxyRePluginVar {\n\n private static MethodInvoker install;\n\n private static MethodInvoker preload;\n\n private static MethodInvoker preload2;\n\n private static MethodInvoker startActivity;\n\n private static MethodInvoker startActivity2;\n\n private static MethodInvoker startActivityForResult;\n\n private static MethodInvoker startActivityForResult2;\n\n private static MethodInvoker createIntent;\n\n private static MethodInvoker createComponentName;\n\n private static MethodInvoker isForDev;\n\n private static MethodInvoker getVersion;\n\n private static MethodInvoker fetchPackageInfo;\n\n private static MethodInvoker fetchResources;\n\n private static MethodInvoker fetchClassLoader;\n\n private static MethodInvoker fetchContext;\n\n private static MethodInvoker fetchBinder;\n\n private static MethodInvoker fetchBinder2;\n\n private static MethodInvoker fetchPluginNameByClassLoader;\n\n private static MethodInvoker getPluginInfoList;\n\n private static MethodInvoker getPluginInfo;\n\n private static MethodInvoker getPluginVersion;\n\n private static MethodInvoker isPluginInstalled;\n\n private static MethodInvoker isPluginUsed;\n\n private static MethodInvoker isPluginDexExtracted;\n\n private static MethodInvoker isPluginRunning;\n\n private static MethodInvoker isPluginRunningInProcess;\n\n private static MethodInvoker getRunningPlugins;\n\n private static MethodInvoker getRunningProcessesByPlugin;\n\n private static MethodInvoker isCurrentPersistentProcess;\n\n private static MethodInvoker registerInstalledReceiver;\n\n private static MethodInvoker registerGlobalBinder;\n\n private static MethodInvoker registerGlobalBinderDelayed;\n\n private static MethodInvoker unregisterGlobalBinder;\n\n private static MethodInvoker getGlobalBinder;\n\n private static MethodInvoker registerHookingClass;\n\n private static MethodInvoker isHookingClass;\n\n private static MethodInvoker unregisterHookingClass;\n\n private static MethodInvoker dump;\n\n static void initLocked(final ClassLoader classLoader) {\n\n // 初始化Replugin的相关方法\n final String rePlugin = \"com.qihoo360.replugin.RePlugin\";\n install = new MethodInvoker(classLoader, rePlugin, \"install\", new Class<?>[]{String.class});\n preload = new MethodInvoker(classLoader, rePlugin, \"preload\", new Class<?>[]{String.class});\n\n // 这里的参数类型PluginInfo是主程序ClassLoader中的PluginInfo\n try {\n Class hostPluginInfo = classLoader.loadClass(\"com.qihoo360.replugin.model.PluginInfo\");\n preload2 = new MethodInvoker(classLoader, rePlugin, \"preload\", new Class<?>[]{PluginInfo.class});\n } catch (ClassNotFoundException e) {\n //\n }\n\n\n startActivity = new MethodInvoker(classLoader, rePlugin, \"startActivity\", new Class<?>[]{Context.class, Intent.class});\n startActivity2 = new MethodInvoker(classLoader, rePlugin, \"startActivity\", new Class<?>[]{Context.class, Intent.class, String.class, String.class});\n startActivityForResult = new MethodInvoker(classLoader, rePlugin, \"startActivityForResult\", new Class<?>[]{Activity.class, Intent.class, int.class});\n startActivityForResult2 = new MethodInvoker(classLoader, rePlugin, \"startActivityForResult\", new Class<?>[]{Activity.class, Intent.class, int.class, Bundle.class});\n createIntent = new MethodInvoker(classLoader, rePlugin, \"createIntent\", new Class<?>[]{String.class, String.class});\n createComponentName = new MethodInvoker(classLoader, rePlugin, \"createComponentName\", new Class<?>[]{String.class, String.class});\n isForDev = new MethodInvoker(classLoader, rePlugin, \"isForDev\", new Class<?>[]{});\n getVersion = new MethodInvoker(classLoader, rePlugin, \"getVersion\", new Class<?>[]{});\n fetchPackageInfo = new MethodInvoker(classLoader, rePlugin, \"fetchPackageInfo\", new Class<?>[]{String.class});\n fetchResources = new MethodInvoker(classLoader, rePlugin, \"fetchResources\", new Class<?>[]{String.class});\n fetchClassLoader = new MethodInvoker(classLoader, rePlugin, \"fetchClassLoader\", new Class<?>[]{String.class});\n fetchContext = new MethodInvoker(classLoader, rePlugin, \"fetchContext\", new Class<?>[]{String.class});\n fetchBinder = new MethodInvoker(classLoader, rePlugin, \"fetchBinder\", new Class<?>[]{String.class, String.class});\n fetchBinder2 = new MethodInvoker(classLoader, rePlugin, \"fetchBinder\", new Class<?>[]{String.class, String.class, String.class});\n fetchPluginNameByClassLoader = new MethodInvoker(classLoader, rePlugin, \"fetchPluginNameByClassLoader\", new Class<?>[]{ClassLoader.class});\n getPluginInfoList = new MethodInvoker(classLoader, rePlugin, \"getPluginInfoList\", new Class<?>[]{});\n getPluginInfo = new MethodInvoker(classLoader, rePlugin, \"getPluginInfo\", new Class<?>[]{String.class});\n getPluginVersion = new MethodInvoker(classLoader, rePlugin, \"getPluginVersion\", new Class<?>[]{String.class});\n isPluginInstalled = new MethodInvoker(classLoader, rePlugin, \"isPluginInstalled\", new Class<?>[]{String.class});\n isPluginUsed = new MethodInvoker(classLoader, rePlugin, \"isPluginUsed\", new Class<?>[]{String.class});\n isPluginDexExtracted = new MethodInvoker(classLoader, rePlugin, \"isPluginDexExtracted\", new Class<?>[]{String.class});\n isPluginRunning = new MethodInvoker(classLoader, rePlugin, \"isPluginRunning\", new Class<?>[]{String.class});\n isPluginRunningInProcess = new MethodInvoker(classLoader, rePlugin, \"isPluginRunningInProcess\", new Class<?>[]{String.class, String.class});\n getRunningPlugins = new MethodInvoker(classLoader, rePlugin, \"getRunningPlugins\", new Class<?>[]{});\n getRunningProcessesByPlugin = new MethodInvoker(classLoader, rePlugin, \"getRunningProcessesByPlugin\", new Class<?>[]{String.class});\n isCurrentPersistentProcess = new MethodInvoker(classLoader, rePlugin, \"isCurrentPersistentProcess\", new Class<?>[]{});\n registerInstalledReceiver = new MethodInvoker(classLoader, rePlugin, \"registerInstalledReceiver\", new Class<?>[]{Context.class, BroadcastReceiver.class});\n registerGlobalBinder = new MethodInvoker(classLoader, rePlugin, \"registerGlobalBinder\", new Class<?>[]{String.class, IBinder.class});\n\n Class cGetter = null;\n try {\n cGetter = classLoader.loadClass(\"com.qihoo360.replugin.IBinderGetter\");\n } catch (Exception e) {\n // ignore\n }\n registerGlobalBinderDelayed = new MethodInvoker(classLoader, rePlugin, \"registerGlobalBinderDelayed\", new Class<?>[]{String.class, cGetter});\n\n unregisterGlobalBinder = new MethodInvoker(classLoader, rePlugin, \"unregisterGlobalBinder\", new Class<?>[]{String.class});\n getGlobalBinder = new MethodInvoker(classLoader, rePlugin, \"getGlobalBinder\", new Class<?>[]{String.class});\n registerHookingClass = new MethodInvoker(classLoader, rePlugin, \"registerHookingClass\", new Class<?>[]{String.class, ComponentName.class, Class.class});\n isHookingClass = new MethodInvoker(classLoader, rePlugin, \"isHookingClass\", new Class<?>[]{ComponentName.class});\n unregisterHookingClass = new MethodInvoker(classLoader, rePlugin, \"unregisterHookingClass\", new Class<?>[]{String.class});\n dump = new MethodInvoker(classLoader, rePlugin, \"dump\", new Class<?>[]{FileDescriptor.class, PrintWriter.class, (new String[0]).getClass()});\n }\n }\n}",
"public class LogDebug {\n public static final String TAG = \"RePlugin\";\n\n private static final String TAG_PREFIX = TAG + \".\";\n\n /**\n * 是否输出日志?若用的是nolog编译出的AAR,则这里为False\n * 注意:所有使用LogDebug前,必须先用此字段来做判断。这样Release阶段才会被彻底删除掉\n * 如:\n * <code>\n * if (LogDebug.LOG) {\n * LogDebug.v(\"xxx\", \"yyy\");\n * }\n * </code>\n */\n public static final boolean LOG = RePluginInternal.FOR_DEV;\n\n /**\n * 允许Dump出一些内容\n */\n public static final boolean DUMP_ENABLED = LOG;\n\n /**\n * Send a verbose log message.\n *\n * @param tag Used to identify the source of a log message. It usually identifies\n * the class or activity where the log call occurs.\n * @param msg The message you would like logged.\n */\n public static int v(String tag, String msg) {\n if (RePluginInternal.FOR_DEV) {\n return Log.v(TAG_PREFIX + tag, msg);\n }\n return -1;\n }\n\n /**\n * Send a verbose log message and log the exception.\n *\n * @param tag Used to identify the source of a log message. It usually identifies\n * the class or activity where the log call occurs.\n * @param msg The message you would like logged.\n * @param tr An exception to log\n */\n public static int v(String tag, String msg, Throwable tr) {\n if (RePluginInternal.FOR_DEV) {\n return Log.v(TAG_PREFIX + tag, msg, tr);\n }\n return -1;\n }\n\n /**\n * Send a debug log message.\n *\n * @param tag Used to identify the source of a log message. It usually identifies\n * the class or activity where the log call occurs.\n * @param msg The message you would like logged.\n */\n public static int d(String tag, String msg) {\n if (RePluginInternal.FOR_DEV) {\n return Log.d(TAG_PREFIX + tag, msg);\n }\n return -1;\n }\n\n /**\n * Send a debug log message and log the exception.\n *\n * @param tag Used to identify the source of a log message. It usually identifies\n * the class or activity where the log call occurs.\n * @param msg The message you would like logged.\n * @param tr An exception to log\n */\n public static int d(String tag, String msg, Throwable tr) {\n if (RePluginInternal.FOR_DEV) {\n return Log.d(TAG_PREFIX + tag, msg, tr);\n }\n return -1;\n }\n\n /**\n * Send an info log message.\n *\n * @param tag Used to identify the source of a log message. It usually identifies\n * the class or activity where the log call occurs.\n * @param msg The message you would like logged.\n */\n public static int i(String tag, String msg) {\n if (RePluginInternal.FOR_DEV) {\n return Log.i(TAG_PREFIX + tag, msg);\n }\n return -1;\n }\n\n /**\n * Send a inifo log message and log the exception.\n *\n * @param tag Used to identify the source of a log message. It usually identifies\n * the class or activity where the log call occurs.\n * @param msg The message you would like logged.\n * @param tr An exception to log\n */\n public static int i(String tag, String msg, Throwable tr) {\n if (RePluginInternal.FOR_DEV) {\n return Log.i(TAG_PREFIX + tag, msg, tr);\n }\n return -1;\n }\n\n /**\n * Send a warning log message.\n *\n * @param tag Used to identify the source of a log message. It usually identifies\n * the class or activity where the log call occurs.\n * @param msg The message you would like logged.\n */\n public static int w(String tag, String msg) {\n if (RePluginInternal.FOR_DEV) {\n return Log.w(TAG_PREFIX + tag, msg);\n }\n return -1;\n }\n\n /**\n * Send a warning log message and log the exception.\n *\n * @param tag Used to identify the source of a log message. It usually identifies\n * the class or activity where the log call occurs.\n * @param msg The message you would like logged.\n * @param tr An exception to log\n */\n public static int w(String tag, String msg, Throwable tr) {\n if (RePluginInternal.FOR_DEV) {\n return Log.w(TAG_PREFIX + tag, msg, tr);\n }\n return -1;\n }\n\n /**\n * Send a warning log message and log the exception.\n *\n * @param tag Used to identify the source of a log message. It usually identifies\n * the class or activity where the log call occurs.\n * @param tr An exception to log\n */\n public static int w(String tag, Throwable tr) {\n if (RePluginInternal.FOR_DEV) {\n return Log.w(TAG_PREFIX + tag, tr);\n }\n return -1;\n }\n\n /**\n * Send an error log message.\n *\n * @param tag Used to identify the source of a log message. It usually identifies\n * the class or activity where the log call occurs.\n * @param msg The message you would like logged.\n */\n public static int e(String tag, String msg) {\n if (RePluginInternal.FOR_DEV) {\n return Log.e(TAG_PREFIX + tag, msg);\n }\n return -1;\n }\n\n /**\n * Send a error log message and log the exception.\n *\n * @param tag Used to identify the source of a log message. It usually identifies\n * the class or activity where the log call occurs.\n * @param msg The message you would like logged.\n * @param tr An exception to log\n */\n public static int e(String tag, String msg, Throwable tr) {\n if (RePluginInternal.FOR_DEV) {\n return Log.e(TAG_PREFIX + tag, msg, tr);\n }\n return -1;\n }\n\n /**\n * 打印当前内存占用日志,方便外界诊断。注意,这会显著消耗性能(约50ms左右)\n *\n * @param tag Used to identify the source of a log message. It usually identifies\n * the class or activity where the log call occurs.\n * @param msg The message you would like logged.\n */\n public static int printMemoryStatus(String tag, String msg) {\n if (RePluginInternal.FOR_DEV) {\n Debug.MemoryInfo mi = new Debug.MemoryInfo();\n Debug.getMemoryInfo(mi);\n\n String mit = \"desc=, memory_v_0_0_1, process=, \" + IPC.getCurrentProcessName() +\n \", totalPss=, \" + mi.getTotalPss() +\n \", dalvikPss=, \" + mi.dalvikPss +\n \", nativeSize=, \" + mi.nativePss +\n \", otherPss=, \" + mi.otherPss + \", \";\n\n return Log.i(tag + \"-MEMORY\", mit + msg);\n }\n return -1;\n }\n\n /**\n * 打印当前内存占用日志,方便外界诊断。注意,这会显著消耗性能(约50ms左右)\n *\n * @param pi\n * @param load\n * @return\n */\n public static int printPluginInfo(PluginInfo pi, int load) {\n long apk = pi.getApkFile().length();\n long dex = pi.getDexFile().length();\n return printMemoryStatus(TAG, \"act=, loadLocked, flag=, Start, pn=, \" + pi.getName() + \", type=, \" + load +\n \", apk=, \" + apk + \", odex=, \" + dex + \", sys_api=, \" + Build.VERSION.SDK_INT);\n }\n\n /**\n * @deprecated 为兼容卫士,以后干掉\n */\n public static final String PLUGIN_TAG = \"ws001\";\n\n /**\n * @deprecated 为兼容卫士,以后干掉\n */\n public static final String MAIN_TAG = \"ws000\";\n\n /**\n * @deprecated 为兼容卫士,以后干掉\n */\n public static final String MISC_TAG = \"ws002\";\n\n public static final String LOADER_TAG = \"createClassLoader\";\n}",
"public class PluginInfo implements Serializable, Parcelable, Cloneable {\n\n private static final long serialVersionUID = -6531475023210445876L;\n\n private static final String TAG = \"PluginInfo\";\n\n /**\n * 表示一个尚未安装的\"纯APK\"插件,其path指向下载完成后APK所在位置\n */\n public static final int TYPE_NOT_INSTALL = 10;\n\n /**\n * 表示一个释放过的\"纯APK\"插件,其path指向释放后的那个APK包 <p>\n * <p>\n * 注意:此时可能还并未安装,仅仅是将APK拷贝到相应目录而已。例如,若是通过RePlugin.installDelayed时即为如此\n */\n public static final int TYPE_EXTRACTED = 11;\n\n /**\n * 表示为P-n已安装,其path指向释放后的那个Jar包(存在于app_plugins_v3,如clean-10-10-102.jar,一个APK)\n *\n * @deprecated 只用于旧的P-n插件,可能会废弃\n */\n public static final int TYPE_PN_INSTALLED = 1;\n\n /**\n * 内置插件\n */\n public static final int TYPE_BUILTIN = 2;\n\n /**\n * 表示为P-n还未安装,其path指向释放前的那个Jar包(在Files目录下,如p-n-clean.jar,有V5文件头)\n *\n * @deprecated 只用于旧的P-n插件,可能会废弃\n */\n public static final int TYPE_PN_JAR = 3;\n\n /**\n * 表示“不确定的框架版本号”,只有旧P-n插件才需要在Load期间得到框架版本号\n *\n * @deprecated 只用于旧的P-n插件,可能会废弃\n */\n public static final int FRAMEWORK_VERSION_UNKNOWN = 0;\n public static final String PI_PKGNAME = \"pkgname\"; // √\n public static final String PI_ALI = \"ali\"; // √\n public static final String PI_LOW = \"low\"; // √\n public static final String PI_HIGH = \"high\"; // √\n public static final String PI_VER = \"ver\"; // √\n public static final String PI_PATH = \"path\";\n public static final String PI_TYPE = \"type\";\n public static final String PI_NAME = \"name\"; // √\n public static final String PI_UPINFO = \"upinfo\";\n public static final String PI_DELINFO = \"delinfo\";\n public static final String PI_COVERINFO = \"coverinfo\";\n public static final String PI_COVER = \"cover\";\n public static final String PI_VERV = \"verv\";\n public static final String PI_USED = \"used\";\n public static final String PI_FRM_VER = \"frm_ver\";\n\n private transient final Map<String, Object> mJson = new ConcurrentHashMap(1 << 4);\n\n // 若插件需要更新,则会有此值\n private PluginInfo mPendingUpdate;\n\n // 若插件需要卸载,则会有此值\n private PluginInfo mPendingDelete;\n\n // 若插件需要同版本覆盖安装更新,则会有此值\n private PluginInfo mPendingCover;\n private boolean mIsPendingCover; // 若当前为“新的PluginInfo”且为“同版本覆盖”,则为了能区分路径,则需要将此字段同步到Json文件中\n\n // 若当前为“新的PluginInfo”,则其“父Info”是什么?\n // 通常当前这个Info会包裹在“mPendingUpdate/mPendingDelete/mPendingCover”内\n // 此信息【不会】做持久化工作。下次重启进程后会消失\n private PluginInfo mParentInfo;\n\n private PluginInfo(JSONObject jo) {\n initPluginInfo(jo);\n }\n\n private PluginInfo(String name, int low, int high, int ver) {\n put(PI_NAME, name);\n put(PI_LOW, low);\n put(PI_HIGH, high);\n put(PI_VER, ver);\n }\n\n private PluginInfo(String pkgName, String alias, int low, int high, int version, String path, int type) {\n // 如Low、High不正确,则给个默认值(等于应用的“最小支持协议版本”)\n if (low <= 0) {\n low = Constant.ADAPTER_COMPATIBLE_VERSION;\n }\n if (high <= 0) {\n high = Constant.ADAPTER_COMPATIBLE_VERSION;\n }\n\n put(PI_PKGNAME, pkgName);\n put(PI_ALI, alias);\n put(PI_NAME, makeName(pkgName, alias));\n put(PI_LOW, low);\n put(PI_HIGH, high);\n\n setVersion(version);\n setPath(path);\n setType(type);\n }\n\n private void initPluginInfo(JSONObject jo) {\n final Iterator<String> keys = jo.keys();\n while (keys.hasNext()) {\n final String k = keys.next();\n put(k, jo.opt(k));\n }\n // 缓存“待更新”的插件信息\n final JSONObject ujo = jo.optJSONObject(PI_UPINFO);\n if (ujo != null) {\n setPendingUpdate(new PluginInfo(ujo));\n }\n\n // 缓存“待卸载”的插件信息\n final JSONObject djo = jo.optJSONObject(PI_DELINFO);\n if (djo != null) {\n setPendingDelete(new PluginInfo(djo));\n }\n\n // 缓存\"待覆盖安装\"的插件信息\n final JSONObject cjo = jo.optJSONObject(PI_COVERINFO);\n if (cjo != null) {\n setPendingCover(new PluginInfo(cjo));\n }\n\n // 缓存\"待覆盖安装\"的插件覆盖字段\n setIsPendingCover(jo.optBoolean(PI_COVER));\n }\n\n // 通过别名和包名来最终确认插件名\n // 注意:老插件会用到\"name\"字段,同时出于性能考虑,故必须写在Json中。见调用此方法的地方\n private String makeName(String pkgName, String alias) {\n if (!TextUtils.isEmpty(alias)) {\n return alias;\n }\n if (!TextUtils.isEmpty(pkgName)) {\n return pkgName;\n }\n return \"\";\n }\n\n /**\n * 通过插件APK的MetaData来初始化PluginInfo <p>\n * 注意:框架内部接口,外界请不要直接使用\n */\n public static PluginInfo parseFromPackageInfo(PackageInfo pi, String path) {\n ApplicationInfo ai = pi.applicationInfo;\n String pn = pi.packageName;\n String alias = null;\n int low = 0;\n int high = 0;\n int ver = 0;\n\n Bundle metaData = ai.metaData;\n\n // 优先读取MetaData中的内容(如有),并覆盖上面的默认值\n if (metaData != null) {\n // 获取插件别名(如有),如无则将\"包名\"当做插件名\n alias = metaData.getString(\"com.qihoo360.plugin.name\");\n\n // 获取最低/最高协议版本(默认为应用的最小支持版本,以保证一定能在宿主中运行)\n low = metaData.getInt(\"com.qihoo360.plugin.version.low\");\n high = metaData.getInt(\"com.qihoo360.plugin.version.high\");\n\n // 获取插件的版本号。优先从metaData中读取,如无则使用插件的VersionCode\n ver = metaData.getInt(\"com.qihoo360.plugin.version.ver\");\n }\n\n // 针对有问题的字段做除错处理\n if (low <= 0) {\n low = Constant.ADAPTER_COMPATIBLE_VERSION;\n }\n if (high <= 0) {\n high = Constant.ADAPTER_COMPATIBLE_VERSION;\n }\n if (ver <= 0) {\n ver = pi.versionCode;\n }\n\n PluginInfo pli = new PluginInfo(pn, alias, low, high, ver, path, PluginInfo.TYPE_NOT_INSTALL);\n\n // 获取插件的框架版本号\n pli.setFrameworkVersionByMeta(metaData);\n\n return pli;\n }\n\n /**\n * (框架内部接口)通过传入的JSON的字符串来创建PluginInfo对象 <p>\n * 注意:框架内部接口,外界请不要直接使用\n */\n public static PluginInfo parseFromJsonText(String joText) {\n JSONObject jo;\n try {\n jo = new JSONObject(joText);\n } catch (JSONException e) {\n if (LOG) {\n e.printStackTrace();\n }\n return null;\n }\n\n // 三个字段是必备的,其余均可\n if (jo.has(PI_PKGNAME) && jo.has(PI_TYPE) && jo.has(PI_VER)) {\n return new PluginInfo(jo);\n } else {\n return null;\n }\n }\n\n /**\n * 获取插件名,如果有别名,则返回别名,否则返回插件包名 <p>\n * (注意:旧插件\"p-n\"的\"别名\"就是插件名)\n */\n public String getName() {\n return get(PI_NAME, \"\");\n }\n\n /**\n * 获取插件包名\n */\n public String getPackageName() {\n return get(PI_PKGNAME, \"\");\n }\n\n /**\n * 获取插件别名\n */\n public String getAlias() {\n return get(PI_ALI, \"\");\n }\n\n /**\n * 获取插件的版本\n */\n public int getVersion() {\n return get(PI_VER, 0);\n }\n\n /**\n * 获取最新的插件,目前所在的位置\n */\n public String getPath() {\n return get(PI_PATH, \"\");\n }\n\n /**\n * 设置最新的插件,目前所在的位置 <p>\n * 注意:若为“纯APK”方案所用,则修改后需调用PluginInfoList.save来保存,否则会无效\n */\n public void setPath(String path) {\n put(PI_PATH, path);\n }\n\n /**\n * 插件是否被使用过?只要释放过Dex的都认为是true\n *\n * @return 插件是否使用过?\n */\n public boolean isUsed() {\n // 注意:该方法不单纯获取JSON中的值,而是根据插件类型(p-n、纯APK)、所处环境(新插件、当前插件)而定\n if (isPnPlugin()) {\n // 为兼容以前逻辑,p-n仍是判断dex是否存在\n return isDexExtracted();\n } else if (getParentInfo() != null) {\n // 若PluginInfo是其它PluginInfo中的PendingUpdate,则返回那个PluginInfo的Used即可\n return getParentInfo().isUsed();\n } else {\n // 若是纯APK,且不是PendingUpdate,则直接从Json中获取\n return get(PI_USED, false);\n }\n }\n\n /**\n * 设置插件是否被使用过 <p>\n * 注意:若为“纯APK”方案所用,则修改后需调用PluginInfoList.save来保存,否则会无效\n *\n * @param used 插件是否被使用过\n */\n public void setIsUsed(boolean used) {\n put(PI_USED, used);\n }\n\n /**\n * 获取Long型的,可用来对比的版本号\n */\n public long getVersionValue() {\n return get(PI_VERV, 0L);\n }\n\n /**\n * 插件的Dex是否已被优化(释放)了?\n *\n * @return\n */\n public boolean isDexExtracted() {\n File f = getDexFile();\n // 文件存在,且大小不为 0 时,才返回 true。\n return f.exists() && FileUtils.sizeOf(f) > 0;\n }\n\n /**\n * 获取APK存放的文件信息 <p>\n * 若为\"纯APK\"插件,则会位于app_p_a中;若为\"p-n\"插件,则会位于\"app_plugins_v3\"中 <p>\n * 注意:若支持同版本覆盖安装的话,则会位于app_p_c中; <p>\n *\n * @return Apk所在的File对象\n */\n public File getApkFile() {\n return new File(getApkDir(), makeInstalledFileName() + \".jar\");\n }\n\n /**\n * 获取APK存放目录\n *\n * @return\n */\n public String getApkDir() {\n // 必须使用宿主的Context对象,防止出现“目录定位到插件内”的问题\n Context context = RePluginInternal.getAppContext();\n File dir;\n if (isPnPlugin()) {\n dir = context.getDir(Constant.LOCAL_PLUGIN_SUB_DIR, 0);\n } else if (getIsPendingCover()) {\n dir = context.getDir(Constant.LOCAL_PLUGIN_APK_COVER_DIR, 0);\n } else {\n dir = context.getDir(Constant.LOCAL_PLUGIN_APK_SUB_DIR, 0);\n }\n\n return dir.getAbsolutePath();\n }\n\n /**\n * 获取或创建(如果需要)某个插件的Dex目录,用于放置dex文件\n * 注意:仅供框架内部使用;仅适用于Android 4.4.x及以下\n *\n * @param dirSuffix 目录后缀\n * @return 插件的Dex所在目录的File对象\n */\n @NonNull\n private File getDexDir(File dexDir, String dirSuffix) {\n\n File dir = new File(dexDir, makeInstalledFileName() + dirSuffix);\n\n if (!dir.exists()) {\n dir.mkdir();\n }\n return dir;\n }\n\n /**\n * 获取Extra Dex(优化前)生成时所在的目录 <p>\n * 若为\"纯APK\"插件,则会位于app_p_od/xx_ed中;若为\"p-n\"插件,则会位于\"app_plugins_v3_odex/xx_ed\"中 <p>\n * 若支持同版本覆盖安装的话,则会位于app_p_c/xx_ed中; <p>\n * 注意:仅供框架内部使用;仅适用于Android 4.4.x及以下\n *\n * @return 优化前Extra Dex所在目录的File对象\n */\n public File getExtraDexDir() {\n return getDexDir(getDexParentDir(), Constant.LOCAL_PLUGIN_INDEPENDENT_EXTRA_DEX_SUB_DIR);\n }\n\n /**\n * 获取Extra Dex(优化后)生成时所在的目录 <p>\n * 若为\"纯APK\"插件,则会位于app_p_od/xx_eod中;若为\"p-n\"插件,则会位于\"app_plugins_v3_odex/xx_eod\"中 <p>\n * 若支持同版本覆盖安装的话,则会位于app_p_c/xx_eod中; <p>\n * 注意:仅供框架内部使用;仅适用于Android 4.4.x及以下\n *\n * @return 优化后Extra Dex所在目录的File对象\n */\n public File getExtraOdexDir() {\n return getDexDir(getDexParentDir(), Constant.LOCAL_PLUGIN_INDEPENDENT_EXTRA_ODEX_SUB_DIR);\n }\n\n /**\n * 获取Dex(优化后)生成时所在的目录 <p>\n *\n * Android O之前:\n * 若为\"纯APK\"插件,则会位于app_p_od中;若为\"p-n\"插件,则会位于\"app_plugins_v3_odex\"中 <p>\n * 若支持同版本覆盖安装的话,则会位于app_p_c中; <p>\n *\n * Android O:\n * APK存放目录/oat/{cpuType}\n *\n * 注意:仅供框架内部使用\n * @return 优化后Dex所在目录的File对象\n */\n public File getDexParentDir() {\n\n // 必须使用宿主的Context对象,防止出现“目录定位到插件内”的问题\n Context context = RePluginInternal.getAppContext();\n\n if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N_MR1) {\n return new File(getApkDir() + File.separator + \"oat\" + File.separator + VMRuntimeCompat.getArtOatCpuType());\n } else {\n if (isPnPlugin()) {\n return context.getDir(Constant.LOCAL_PLUGIN_ODEX_SUB_DIR, 0);\n } else if (getIsPendingCover()) {\n return context.getDir(Constant.LOCAL_PLUGIN_APK_COVER_DIR, 0);\n } else {\n return context.getDir(Constant.LOCAL_PLUGIN_APK_ODEX_SUB_DIR, 0);\n }\n }\n }\n\n /**\n * 获取Dex(优化后)所在的文件信息 <p>\n *\n * Android O 之前:\n * 若为\"纯APK\"插件,则会位于app_p_od中;若为\"p-n\"插件,则会位于\"app_plugins_v3_odex\"中 <p>\n *\n * Android O:\n * APK存放目录/oat/{cpuType}/XXX.odex\n *\n * 注意:仅供框架内部使用\n *\n * @return 优化后Dex所在文件的File对象\n */\n public File getDexFile() {\n\n if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N_MR1) {\n File dir = getDexParentDir();\n return new File(dir, makeInstalledFileName() + \".odex\");\n } else {\n File dir = getDexParentDir();\n return new File(dir, makeInstalledFileName() + \".dex\");\n }\n }\n\n /**\n * 根据类型来获取SO释放的路径 <p>\n * 若为\"纯APK\"插件,则会位于app_p_n中;若为\"p-n\"插件,则会位于\"app_plugins_v3_libs\"中 <p>\n * 若支持同版本覆盖安装的话,则会位于app_p_c中; <p>\n * 注意:仅供框架内部使用\n *\n * @return SO释放路径所在的File对象\n */\n public File getNativeLibsDir() {\n // 必须使用宿主的Context对象,防止出现“目录定位到插件内”的问题\n Context context = RePluginInternal.getAppContext();\n File dir;\n if (isPnPlugin()) {\n dir = context.getDir(Constant.LOCAL_PLUGIN_DATA_LIB_DIR, 0);\n } else if (getIsPendingCover()) {\n dir = context.getDir(Constant.LOCAL_PLUGIN_APK_COVER_DIR, 0);\n } else {\n dir = context.getDir(Constant.LOCAL_PLUGIN_APK_LIB_DIR, 0);\n }\n return new File(dir, makeInstalledFileName());\n }\n\n /**\n * 获取插件当前所处的类型。详细见TYPE_XXX常量\n */\n public int getType() {\n return get(PI_TYPE, 0);\n }\n\n /**\n * 设置插件当前所处的类型。详细见TYPE_XXX常量 <p>\n * 注意:若为“纯APK”方案所用,则修改后需调用PluginInfoList.save来保存,否则会无效\n */\n public void setType(int type) {\n put(PI_TYPE, type);\n }\n\n /**\n * 是否已准备好了新版本?\n *\n * @return 是否已准备好\n */\n public boolean isNeedUpdate() {\n return mPendingUpdate != null;\n }\n\n /**\n * 获取将来要更新的插件的信息,将会在下次启动时才能被使用\n *\n * @return 插件更新信息\n */\n public PluginInfo getPendingUpdate() {\n return mPendingUpdate;\n }\n\n /**\n * 设置插件的更新信息。此信息有可能等到下次才能被使用 <p>\n * 注意:若为“纯APK”方案所用,则修改后需调用PluginInfoList.save来保存,否则会无效\n *\n * @param info 插件的更新信息\n */\n public void setPendingUpdate(PluginInfo info) {\n mPendingUpdate = info;\n if (info != null) {\n put(PI_UPINFO, info.getJSON());\n } else {\n mJson.remove(PI_UPINFO);\n }\n }\n\n /**\n * 是否需要删除插件?\n *\n * @return 是否需要卸载插件\n */\n public boolean isNeedUninstall() {\n return mPendingDelete != null;\n }\n\n /**\n * 获取将来要卸载的插件的信息,将会在下次启动时才能被使用\n *\n * @return 插件卸载信息\n */\n public PluginInfo getPendingDelete() {\n return mPendingDelete;\n }\n\n /**\n * 设置插件的卸载信息。此信息有可能等到下次才能被使用 <p>\n * 注意:若为“纯APK”方案所用,则修改后需调用PluginInfoList.save来保存,否则会无效\n *\n * @param info 插件的卸载信息\n */\n public void setPendingDelete(PluginInfo info) {\n mPendingDelete = info;\n if (info != null) {\n put(PI_DELINFO, info.getJSON());\n } else {\n mJson.remove(PI_DELINFO);\n }\n }\n\n /**\n * 是否已准备好了新待覆盖的版本?\n *\n * @return 是否已准备好\n */\n public boolean isNeedCover() {\n return mPendingCover != null;\n }\n\n /**\n * 获取将来要覆盖更新的插件的信息,将会在下次启动时才能被使用\n *\n * @return 插件覆盖安装信息\n */\n public PluginInfo getPendingCover() {\n return mPendingCover;\n }\n\n /**\n * 设置插件的覆盖更新信息。此信息有可能等到下次才能被使用 <p>\n * 注意:若为“纯APK”方案所用,则修改后需调用PluginInfoList.save来保存,否则会无效\n *\n * @param info 插件覆盖安装信息\n */\n public void setPendingCover(PluginInfo info) {\n mPendingCover = info;\n if (info != null) {\n put(PI_COVERINFO, info.getJSON());\n } else {\n mJson.remove(PI_COVERINFO);\n }\n }\n\n /**\n * 此PluginInfo是否包含同版本覆盖的字段?只在调用RePlugin.install方法才能看到 <p>\n * 注意:仅框架内部使用\n *\n * @return 是否包含同版本覆盖字段\n */\n public boolean getIsPendingCover() {\n return mIsPendingCover;\n }\n\n /**\n * 设置PluginInfo的同版本覆盖的字段 <p>\n * 注意:仅框架内部使用\n */\n public void setIsPendingCover(boolean coverInfo) {\n mIsPendingCover = coverInfo;\n if (coverInfo) {\n put(PI_COVER, true);\n } else {\n mJson.remove(PI_COVER);\n }\n }\n\n /**\n * 获取最小支持宿主API的版本\n */\n public int getLowInterfaceApi() {\n return get(PI_LOW, Constant.ADAPTER_COMPATIBLE_VERSION);\n }\n\n /**\n * 获取最高支持宿主API的版本\n *\n * @deprecated 可能会废弃\n */\n public int getHighInterfaceApi() {\n return get(PI_HIGH, Constant.ADAPTER_COMPATIBLE_VERSION);\n }\n\n /**\n * 获取框架的版本号 <p>\n * 此版本号不同于“协议版本”。这直接关系到四大组件和其它模块的加载情况\n */\n public int getFrameworkVersion() {\n // 仅p-n插件在用\n // 之所以默认为FRAMEWORK_VERSION_UNKNOWN,是因为在这里还只是读取p-n文件头,框架版本需要在loadDex阶段获得\n return get(PI_FRM_VER, FRAMEWORK_VERSION_UNKNOWN);\n }\n\n /**\n * 设置框架的版本号 <p>\n * 注意:若为“纯APK”方案所用,则修改后需调用PluginInfoList.save来保存,否则会无效\n *\n * @param version 框架版本号\n */\n public void setFrameworkVersion(int version) {\n put(PI_FRM_VER, version);\n }\n\n /**\n * 根据MetaData来设置框架版本号 <p>\n * 注意:若为“纯APK”方案所用,则修改后需调用PluginInfoList.save来保存,否则会无效\n *\n * @param meta MetaData数据\n */\n public void setFrameworkVersionByMeta(Bundle meta) {\n int dfv = RePlugin.getConfig().getDefaultFrameworkVersion();\n int frameVer = 0;\n if (meta != null) {\n frameVer = meta.getInt(\"com.qihoo360.framework.ver\", dfv);\n }\n if (frameVer < 1) {\n frameVer = dfv;\n }\n setFrameworkVersion(frameVer);\n }\n\n // @hide\n public JSONObject getJSON() {\n return new JSONObject(mJson);\n }\n\n /**\n * 生成用于放入app_plugin_v3(app_p_n)等目录下的插件的文件名,其中:<p>\n * 1、“纯APK”方案:得到混淆后的文件名(规则见代码内容) <p>\n * 2、“旧p-n”和“内置插件”(暂定)方案:得到类似 shakeoff_10_10_103 这样的比较规范的文件名 <p>\n * 3、只获取文件名,其目录和扩展名仍需在外面定义\n *\n * @return 文件名(不含扩展名)\n */\n public String makeInstalledFileName() {\n if (isPnPlugin() || getType() == TYPE_BUILTIN) {\n return formatName();\n } else {\n // 混淆插件名字,做法:\n // 1. 生成最初的名字:[插件包名(小写)][协议最低版本][协议最高版本][插件版本][ak]\n // 必须用小写和数字、无特殊字符,否则hashCode后会有一定的重复率\n // 2. 将其生成出hashCode\n // 3. 将整体数字 - 88\n String n = getPackageName().toLowerCase() + getLowInterfaceApi() + getHighInterfaceApi() + getVersion() + \"ak\";\n int h = n.hashCode() - 88;\n return Integer.toString(h);\n }\n }\n\n /**\n * 更新插件信息。通常是在安装完新插件后调用此方法 <p>\n * 只更新一些必要的方法,如插件版本、路径、时间等。\n *\n * @param info 新版本插件信息\n */\n public void update(PluginInfo info) {\n // TODO low high\n setVersion(info.getVersion());\n setPath(info.getPath());\n setType(info.getType());\n setPackageName(info.getPackageName());\n setAlias(info.getAlias());\n }\n\n /**\n * 若此Info为“新PluginInfo”,则这里返回的是“其父Info”的内容。通常和PendingUpdate有关\n *\n * @return 父PluginInfo\n */\n public PluginInfo getParentInfo() {\n return mParentInfo;\n }\n\n // @hide\n public void setParentInfo(PluginInfo parent) {\n mParentInfo = parent;\n }\n\n static PluginInfo createByJO(JSONObject jo) {\n if (jo == null || jo.length() == 0) return null;\n PluginInfo pi = new PluginInfo(jo);\n // 必须有包名或别名\n if (TextUtils.isEmpty(pi.getName())) {\n return null;\n }\n return pi;\n }\n\n private void setPackageName(String pkgName) {\n if (!TextUtils.equals(pkgName, getPackageName())) {\n put(PI_PKGNAME, pkgName);\n }\n }\n\n private void setAlias(String alias) {\n if (!TextUtils.equals(alias, getAlias())) {\n put(PI_ALI, alias);\n }\n }\n\n private void setVersion(int version) {\n put(PI_VER, version);\n put(PI_VERV, buildCompareValue());\n }\n\n // -------------------------\n // Parcelable and Cloneable\n // -------------------------\n\n public static final Creator<PluginInfo> CREATOR = new Creator<PluginInfo>() {\n\n @Override\n public PluginInfo createFromParcel(Parcel source) {\n return new PluginInfo(source);\n }\n\n @Override\n public PluginInfo[] newArray(int size) {\n return new PluginInfo[size];\n }\n };\n\n private PluginInfo(Parcel source) {\n JSONObject jo = null;\n String txt = null;\n try {\n txt = source.readString();\n jo = new JSONObject(txt);\n } catch (JSONException e) {\n if (LogDebug.LOG) {\n LogDebug.e(TAG, \"PluginInfo: mJson error! s=\" + txt, e);\n }\n jo = new JSONObject();\n }\n initPluginInfo(jo);\n }\n\n @Override\n public Object clone() {\n try {\n final String jsonText = getJSON().toString();\n return new PluginInfo(new JSONObject(jsonText));\n } catch (JSONException e) {\n e.printStackTrace();\n }\n return null;\n }\n\n @Override\n public int describeContents() {\n return 0;\n }\n\n @Override\n public void writeToParcel(Parcel dest, int flags) {\n dest.writeString(getJSON().toString());\n }\n\n @Override\n public String toString() {\n final StringBuilder b = new StringBuilder();\n b.append(\"PInfo { \");\n toContentString(b);\n b.append(\" }\");\n return b.toString();\n }\n\n private void toContentString(StringBuilder b) {\n // 插件名 + 版本 + 框架版本\n {\n b.append('<');\n b.append(getName()).append(':').append(getVersion());\n b.append('(').append(getFrameworkVersion()).append(')');\n b.append(\"> \");\n }\n\n // 当前是否为PendingUpdate的信息\n if (mParentInfo != null) {\n b.append(\"[HAS_PARENT] \");\n }\n\n // 插件类型\n {\n if (getType() == TYPE_BUILTIN) {\n b.append(\"[BUILTIN] \");\n } else if (isPnPlugin()) {\n b.append(\"[P-N] \");\n } else {\n b.append(\"[APK] \");\n }\n }\n\n // 插件是否已释放\n if (isDexExtracted()) {\n b.append(\"[DEX_EXTRACTED] \");\n }\n\n // 插件是否“正在使用”\n if (RePlugin.isPluginRunning(getName())) {\n b.append(\"[RUNNING] \");\n }\n\n // 哪些进程使用\n String[] processes = RePlugin.getRunningProcessesByPlugin(getName());\n if (processes != null) {\n b.append(\"processes=\").append(Arrays.toString(processes)).append(' ');\n }\n\n // 插件基本信息\n if (mJson != null) {\n b.append(\"js=\").append(mJson).append(' ');\n }\n\n // 和插件路径有关(除APK路径以外)\n {\n b.append(\"dex=\").append(getDexFile()).append(' ');\n b.append(\"nlib=\").append(getNativeLibsDir());\n }\n }\n\n @Override\n public int hashCode() {\n return mJson.hashCode();\n }\n\n @Override\n public boolean equals(Object obj) {\n if (obj == null) {\n return false;\n }\n\n if (this == obj) {\n return true;\n }\n\n if (this.getClass() != obj.getClass()) {\n return false;\n }\n\n PluginInfo pluginInfo = (PluginInfo) obj;\n\n try {\n return pluginInfo.mJson.toString().equals(mJson.toString());\n } catch (Exception e) {\n return false;\n }\n }\n\n\n // -------------------------\n // FIXME 兼容老的P-n插件\n // -------------------------\n\n public static final String QUERY_COLUMNS[] = {\n PI_NAME, PI_LOW, PI_HIGH, PI_VER, PI_TYPE, \"v5type\", PI_PATH, \"v5index\", \"v5offset\", \"v5length\", \"v5md5\"\n };\n\n private static final Pattern REGEX;\n\n static {\n REGEX = Pattern.compile(Constant.LOCAL_PLUGIN_FILE_PATTERN);\n }\n\n /**\n *\n */\n public static final Comparator<PluginInfo> VERSION_COMPARATOR = new Comparator<PluginInfo>() {\n\n @Override\n public int compare(PluginInfo lhs, PluginInfo rhs) {\n long diff = lhs.getVersionValue() - rhs.getVersionValue();\n if (diff > 0) {\n return 1;\n } else if (diff < 0) {\n return -1;\n }\n return 0;\n }\n };\n\n public static final String format(String name, int low, int high, int ver) {\n return name + \"-\" + low + \"-\" + high + \"-\" + ver;\n }\n\n public static final PluginInfo build(File f) {\n Matcher m = REGEX.matcher(f.getName());\n if (m == null || !m.matches()) {\n if (LOG) {\n LogDebug.d(PLUGIN_TAG, \"PluginInfo.build: skip, no match1, file=\" + f.getAbsolutePath());\n }\n return null;\n }\n MatchResult r = m.toMatchResult();\n if (r == null || r.groupCount() != 4) {\n if (LOG) {\n LogDebug.d(PLUGIN_TAG, \"PluginInfo.build: skip, no match2, file=\" + f.getAbsolutePath());\n }\n return null;\n }\n String name = r.group(1);\n int low = Integer.parseInt(r.group(2));\n int high = Integer.parseInt(r.group(3));\n int ver = Integer.parseInt(r.group(4));\n String path = f.getPath();\n PluginInfo info = new PluginInfo(name, low, high, ver, TYPE_PN_INSTALLED, V5FileInfo.NONE_PLUGIN, path, -1, -1, -1, null);\n if (LOG) {\n LogDebug.d(PLUGIN_TAG, \"PluginInfo.build: found plugin, name=\" + info.getName()\n + \" low=\" + info.getLowInterfaceApi() + \" high=\" + info.getHighInterfaceApi()\n + \" ver=\" + info.getVersion());\n }\n return info;\n }\n\n public static final PluginInfo buildFromBuiltInJson(JSONObject jo) {\n String pkgName = jo.optString(\"pkg\");\n String name = jo.optString(PI_NAME);\n String assetName = jo.optString(PI_PATH);\n if (TextUtils.isEmpty(name) || TextUtils.isEmpty(pkgName) || TextUtils.isEmpty(assetName)) {\n if (LogDebug.LOG) {\n LogDebug.d(TAG, \"buildFromBuiltInJson: Invalid json. j=\" + jo);\n }\n return null;\n }\n int low = jo.optInt(PI_LOW, Constant.ADAPTER_COMPATIBLE_VERSION); // Low应指向最低兼容版本\n int high = jo.optInt(PI_HIGH, Constant.ADAPTER_COMPATIBLE_VERSION); // High同上\n int ver = jo.optInt(PI_VER);\n PluginInfo info = new PluginInfo(pkgName, name, low, high, ver, assetName, TYPE_BUILTIN);\n\n // 从 json 中读取 frameVersion(可选)\n int frameVer = jo.optInt(\"frm\");\n if (frameVer < 1) {\n frameVer = RePlugin.getConfig().getDefaultFrameworkVersion();\n }\n info.setFrameworkVersion(frameVer);\n\n return info;\n }\n\n public static final PluginInfo buildV5(String name, int low, int high, int ver, int v5Type, String v5Path, int v5index, int v5offset, int v5length, String v5md5) {\n return new PluginInfo(name, low, high, ver, TYPE_PN_JAR, v5Type, v5Path, v5index, v5offset, v5length, v5md5);\n }\n\n public static final PluginInfo build(Cursor cursor) {\n String name = cursor.getString(0);\n int v1 = cursor.getInt(1);\n int v2 = cursor.getInt(2);\n int v3 = cursor.getInt(3);\n int type = cursor.getInt(4);\n int v5Type = cursor.getInt(5);\n String path = cursor.getString(6);\n int v5index = cursor.getInt(7);\n int v5offset = cursor.getInt(8);\n int v5length = cursor.getInt(9);\n String v5md5 = cursor.getString(10);\n return new PluginInfo(name, v1, v2, v3, type, v5Type, path, v5index, v5offset, v5length, v5md5);\n }\n\n public static final PluginInfo build(String name, int low, int high, int ver) {\n return new PluginInfo(name, low, high, ver);\n }\n\n // Old Version\n private PluginInfo(String name, int low, int high, int ver, int type, int v5Type, String path, int v5index, int v5offset, int v5length, String v5md5) {\n this(name, name, low, high, ver, path, type);\n\n put(\"v5type\", v5Type);\n put(\"v5index\", v5index);\n put(\"v5offset\", v5offset);\n put(\"v5length\", v5length);\n put(\"v5md5\", v5md5);\n }\n\n private String formatName() {\n return format(getName(), getLowInterfaceApi(), getHighInterfaceApi(), getVersion());\n }\n\n final void to(MatrixCursor cursor) {\n cursor.newRow().add(getName()).add(getLowInterfaceApi()).add(getHighInterfaceApi())\n .add(getVersion()).add(getType()).add(getV5Type()).add(getPath())\n .add(getV5Index()).add(getV5Offset()).add(getV5Length()).add(getV5MD5());\n }\n\n public final void to(Intent intent) {\n intent.putExtra(PI_NAME, getName());\n intent.putExtra(PI_LOW, getLowInterfaceApi());\n intent.putExtra(PI_HIGH, getHighInterfaceApi());\n intent.putExtra(PI_VER, getVersion());\n intent.putExtra(PI_TYPE, getType());\n intent.putExtra(\"v5type\", getV5Type());\n intent.putExtra(PI_PATH, getPath());\n intent.putExtra(\"v5index\", getV5Index());\n intent.putExtra(\"v5offset\", getV5Offset());\n intent.putExtra(\"v5length\", getV5Length());\n intent.putExtra(\"v5md5\", getV5MD5());\n }\n\n public final boolean deleteObsolote(Context context) {\n if (getType() != TYPE_PN_INSTALLED) {\n return true;\n }\n if (TextUtils.isEmpty(getPath())) {\n return true;\n }\n boolean rc = new File(getPath()).delete();\n\n // 同时清除旧的SO库文件\n // Added by Jiongxuan Zhang\n File libDir = getNativeLibsDir();\n PluginNativeLibsHelper.clear(libDir);\n return rc;\n }\n\n /**\n * 判断是否可以替换(将NOT_INSTALLED变为INSTALLED) <p>\n * 条件:目前是BUILT_IN或NOT_INSTALLED,插件基本信息相同\n *\n * @param info 要替换的Info对象\n * @return 是否可以替换\n * @deprecated 只用于旧的P-n插件,可能会废弃\n */\n public final boolean canReplaceForPn(PluginInfo info) {\n if (getType() != TYPE_PN_INSTALLED\n && info.getType() == TYPE_PN_INSTALLED\n && getName().equals(info.getName())\n && getLowInterfaceApi() == info.getLowInterfaceApi()\n && getHighInterfaceApi() == info.getHighInterfaceApi()\n && getVersion() == info.getVersion()) {\n return true;\n }\n return false;\n }\n\n public final boolean match() {\n\n boolean isBlocked = RePlugin.getConfig().getCallbacks().isPluginBlocked(this);\n\n if (LOG) {\n if (isBlocked) {\n LogDebug.d(PLUGIN_TAG, \"match result: plugin is blocked\");\n }\n }\n\n return !isBlocked;\n }\n\n private final long buildCompareValue() {\n long x;\n x = getHighInterfaceApi() & 0x7fff;\n long v1 = x << (32 + 16);\n x = getLowInterfaceApi() & 0xffff;\n long v2 = x << 32;\n long v3 = getVersion();\n return v1 | v2 | v3;\n }\n\n /**\n * 判断是否为p-n类型的插件?\n *\n * @return 是否为p-n类型的插件\n * @deprecated 只用于旧的P-n插件,可能会废弃\n */\n public boolean isPnPlugin() {\n int type = getType();\n return type == TYPE_PN_INSTALLED || type == TYPE_PN_JAR || type == TYPE_BUILTIN;\n }\n\n /**\n * V5类型\n *\n * @deprecated 只用于旧的P-n插件,可能会废弃\n */\n public int getV5Type() {\n return get(\"v5type\", V5FileInfo.NONE_PLUGIN);\n }\n\n /**\n * V5类型:复合插件文件索引\n *\n * @deprecated 只用于旧的P-n插件,可能会废弃\n */\n public int getV5Index() {\n return get(\"v5index\", -1);\n }\n\n /**\n * V5类型:复合插件文件偏移\n *\n * @deprecated 只用于旧的P-n插件,可能会废弃\n */\n public int getV5Offset() {\n return get(\"v5offset\", -1);\n }\n\n /**\n * V5类型:复合插件文件长度\n *\n * @deprecated 只用于旧的P-n插件,可能会废弃\n */\n public int getV5Length() {\n return get(\"v5length\", -1);\n }\n\n /**\n * V5类型:复合插件文件MD5\n *\n * @deprecated 只用于旧的P-n插件,可能会废弃\n */\n public String getV5MD5() {\n return get(\"v5md5\", \"\");\n }\n\n ////\n\n private <T> T get(String name, @NonNull T def) {\n final Object obj = mJson.get(name);\n return (def.getClass().isInstance(obj)) ? (T) obj : def;\n }\n\n public <T> void put(String key, T value) {\n if (key == null || value == null) return;\n mJson.put(key, value); //value & key must not null\n }\n\n}",
"public static final String LOADER_TAG = \"createClassLoader\";",
"public static final boolean LOG = RePluginInternal.FOR_DEV;",
"public static final String PLUGIN_TAG = \"ws001\";"
] | import android.content.Context;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.ComponentInfo;
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.IBinder;
import android.text.TextUtils;
import android.util.Log;
import com.qihoo360.i.Factory;
import com.qihoo360.i.IModule;
import com.qihoo360.i.IPlugin;
import com.qihoo360.mobilesafe.core.BuildConfig;
import com.qihoo360.mobilesafe.parser.manifest.ManifestParser;
import com.qihoo360.replugin.RePlugin;
import com.qihoo360.replugin.base.IPC;
import com.qihoo360.replugin.component.ComponentList;
import com.qihoo360.replugin.component.process.PluginProcessHost;
import com.qihoo360.replugin.component.receiver.PluginReceiverProxy;
import com.qihoo360.replugin.helper.LogDebug;
import com.qihoo360.replugin.helper.LogRelease;
import com.qihoo360.replugin.model.PluginInfo;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.lang.ref.WeakReference;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static com.qihoo360.replugin.helper.LogDebug.LOADER_TAG;
import static com.qihoo360.replugin.helper.LogDebug.LOG;
import static com.qihoo360.replugin.helper.LogDebug.PLUGIN_TAG;
import static com.qihoo360.replugin.helper.LogRelease.LOGR; | /*
* Copyright (C) 2005-2017 Qihoo 360 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.qihoo360.loader2;
/**
* @author RePlugin Team
*/
class Loader {
private final Context mContext;
private final String mPluginName;
final String mPath;
final Plugin mPluginObj;
PackageInfo mPackageInfo;
Resources mPkgResources;
Context mPkgContext;
ClassLoader mClassLoader;
/**
* 记录所有缓存的Component列表
*/
ComponentList mComponents;
Method mCreateMethod;
Method mCreateMethod2;
IPlugin mPlugin;
IPluginHost mPluginHost;
ProxyPlugin mBinderPlugin;
/**
* layout缓存:忽略表
*/
HashSet<String> mIgnores = new HashSet<String>();
/**
* layout缓存:构造器表
*/
HashMap<String, Constructor<?>> mConstructors = new HashMap<String, Constructor<?>>();
static class ProxyPlugin implements IPlugin {
com.qihoo360.loader2.IPlugin mPlugin;
ProxyPlugin(IBinder plugin) {
mPlugin = com.qihoo360.loader2.IPlugin.Stub.asInterface(plugin);
}
@Override
public IModule query(Class<? extends IModule> c) {
IBinder b = null;
try {
b = mPlugin.query(c.getName());
} catch (Throwable e) {
if (LOGR) { | LogRelease.e(PLUGIN_TAG, "query(" + c + ") exception: " + e.getMessage(), e); | 5 |
programingjd/okserver | src/test/java/info/jdavid/ok/server/handler/FileHandlerTest.java | [
"@SuppressWarnings({ \"WeakerAccess\" })\npublic class HttpServer {\n\n final AtomicBoolean started = new AtomicBoolean();\n final AtomicBoolean setup = new AtomicBoolean();\n int port = 8080; // 80\n int securePort = 8181; // 443\n String hostname = null;\n long maxRequestSize = 65536;\n Dispatcher dispatcher = null;\n KeepAliveStrategy keepAliveStrategy = KeepAliveStrategy.DEFAULT;\n RequestHandler requestHandler = null;\n Https https = null;\n\n /**\n * Sets the port number for the server. You can use 0 for \"none\" (to disable the port binding).\n * @param port the port number.\n * @param securePort the secure port number.\n * @return this.\n */\n public final HttpServer ports(final int port, final int securePort) {\n if (started.get()) {\n throw new IllegalStateException(\"The port number cannot be changed while the server is running.\");\n }\n this.port = port;\n this.securePort = securePort;\n return this;\n }\n\n /**\n * Sets the port number for the server. You can use 0 for \"none\" (to disable the port binding).\n * @param port the port number.\n * @return this.\n */\n public final HttpServer port(final int port) {\n if (started.get()) {\n throw new IllegalStateException(\"The port number cannot be changed while the server is running.\");\n }\n this.port = port;\n return this;\n }\n\n /**\n * Gets the port number for the server.\n * @return the server port number.\n */\n public final int port() {\n return port;\n }\n\n /**\n * Sets the port number for the server (secure connections). You can use 0 for \"none\"\n * (to disable the port binding).\n * @param port the port number.\n * @return this.\n */\n @SuppressWarnings(\"UnusedReturnValue\")\n public final HttpServer securePort(final int port) {\n if (started.get()) {\n throw new IllegalStateException(\"The port number cannot be changed while the server is running.\");\n }\n this.securePort = port;\n return this;\n }\n\n /**\n * Gets the port number for the server (secure connections).\n * @return the server secure port number.\n */\n public final int securePort() {\n return securePort;\n }\n\n /**\n * Sets the host name for the server.\n * @param hostname the host name.\n * @return this.\n */\n public final HttpServer hostname(final String hostname) {\n if (started.get()) {\n throw new IllegalStateException(\"The host name cannot be changed while the server is running.\");\n }\n this.hostname = hostname;\n return this;\n }\n\n /**\n * Gets the host name for the server.\n * @return the server host name.\n */\n public final String hostname() {\n return hostname;\n }\n\n /**\n * Sets the maximum request size allowed by the server.\n * @param size the maximum request size in bytes.\n * @return this.\n */\n public final HttpServer maxRequestSize(final long size) {\n if (started.get()) {\n throw new IllegalStateException(\"The max request size cannot be changed while the server is running.\");\n }\n this.maxRequestSize = size;\n return this;\n }\n\n /**\n * Gets the maximum request size allowed by the server.\n * @return the maximum allowed request size.\n */\n public final long maxRequestSize() {\n return maxRequestSize;\n }\n\n /**\n * Sets the Keep-Alive strategy.\n * @param strategy the strategy.\n * @return this\n */\n public final HttpServer keepAliveStrategy(@Nullable final KeepAliveStrategy strategy) {\n if (started.get()) {\n throw new IllegalStateException(\n \"The keep-alive strategy cannot be changed while the server is running.\");\n }\n this.keepAliveStrategy = strategy == null ? KeepAliveStrategy.DEFAULT : strategy;\n return this;\n }\n\n /**\n * Validates the specified handler before it is set as the request handler for the server.\n * @param handler the candidate request handler.\n * @throws IllegalArgumentException if the handler is not suitable.\n */\n protected void validateHandler(@SuppressWarnings(\"unused\") final RequestHandler handler) {}\n\n /**\n * Sets the request handler.\n * @param handler the request handler.\n * @return this\n */\n public final HttpServer requestHandler(final RequestHandler handler) {\n if (started.get()) {\n throw new IllegalStateException(\"The request handler cannot be changed while the server is running.\");\n }\n validateHandler(handler);\n this.requestHandler = handler;\n return this;\n }\n\n private RequestHandler requestHandler() {\n RequestHandler handler = requestHandler;\n if (handler == null) {\n handler = requestHandler = RequestHandlerChain.createDefaultChain();\n }\n return handler;\n }\n\n /**\n * Validates the specified dispatcher before it is set as the request dispatcher for the server.\n * @param dispatcher the candidate request dispatcher.\n * @throws IllegalArgumentException if the dispatcher is not suitable.\n */\n @SuppressWarnings(\"unused\")\n protected void validateDispatcher(final Dispatcher dispatcher) {}\n\n /**\n * Sets a custom dispatcher.\n * @param dispatcher the dispatcher responsible for distributing the connection requests.\n * @return this\n */\n public final HttpServer dispatcher(final Dispatcher dispatcher) {\n if (started.get()) {\n throw new IllegalStateException(\"The dispatcher cannot be changed while the server is running.\");\n }\n validateDispatcher(dispatcher);\n this.dispatcher = dispatcher;\n return this;\n }\n\n /**\n * Validates the specified https settings before they are set for the server.\n * @param https the candidate https settings.\n * @throws IllegalArgumentException if the settings is not suitable.\n */\n @SuppressWarnings(\"unused\")\n protected void validateHttps(final Https https) {}\n\n /**\n * Sets the Https provider.\n * @param https the Https provider.\n * @return this\n */\n public final HttpServer https(final Https https) {\n if (started.get()) {\n throw new IllegalStateException(\"The certificates cannot be changed while the server is running.\");\n }\n validateHttps(https);\n this.https = https;\n return this;\n }\n\n private Dispatcher dispatcher() {\n Dispatcher dispatcher = this.dispatcher;\n if (dispatcher == null) {\n dispatcher = this.dispatcher = new SocketDispatcher.Default();\n }\n return dispatcher;\n }\n\n /**\n * Override to perform tasks right after the server is started. By default, it does nothing.\n */\n protected void setup() {}\n\n /**\n * Shuts down the server.\n */\n @SuppressWarnings(\"Duplicates\")\n public void shutdown() {\n if (!started.get()) return;\n if (dispatcher != null) {\n dispatcher.close();\n try {\n dispatcher.shutdown();\n }\n //catch (final Exception ignore) {}\n finally {\n dispatcher = null;\n started.set(false);\n }\n }\n }\n\n /**\n * Returns whether the server is running or not.\n * @return true if the server has been started, false if it hasn't, or has been stopped since.\n */\n public final boolean isRunning() {\n return started.get();\n }\n\n /**\n * Starts the server.\n */\n public final void start() {\n if (started.getAndSet(true)) {\n throw new IllegalStateException(\"The server has already been started.\");\n }\n try {\n if (!setup.getAndSet(true)) setup();\n final RequestHandler handler = requestHandler();\n if (handler instanceof AbstractRequestHandler) {\n ((AbstractRequestHandler)handler).init();\n }\n final Dispatcher dispatcher = dispatcher();\n dispatcher.start();\n final InetAddress address;\n if (hostname == null) {\n address = null; //new InetSocketAddress(0).getAddress();\n }\n else {\n address = InetAddress.getByName(hostname);\n }\n\n dispatcher.loop(port, securePort, https, address, hostname,\n maxRequestSize, keepAliveStrategy, handler);\n }\n catch (final BindException e) {\n throw new RuntimeException(e);\n }\n catch (final IOException e) {\n logger.error(e.getMessage(), e);\n }\n }\n\n}",
"@SuppressWarnings(\"WeakerAccess\")\npublic final class Https {\n\n final SSLContext context;\n final Map<String, SSLContext> additionalContexts;\n final Platform platform;\n final String[] protocols;\n final String[] cipherSuites;\n final boolean http2;\n\n private Https(@Nullable final byte[] cert,\n @Nullable final Map<String, byte[]> additionalCerts,\n @Nullable final List<String> protocols,\n @Nullable final List<String> cipherSuites,\n final boolean http2) {\n context = createSSLContext(cert);\n final Platform platform = this.platform = Platform.findPlatform();\n additionalContexts =\n new HashMap<>(additionalCerts == null ? 0 : additionalCerts.size());\n if (additionalCerts != null) {\n for (final Map.Entry<String, byte[]> entry : additionalCerts.entrySet()) {\n final SSLContext additionalContext = createSSLContext(entry.getValue());\n if (additionalContext != null) additionalContexts.put(entry.getKey(), additionalContext);\n }\n }\n final List<String> protos = protocols == null ? platform.defaultProtocols() : protocols;\n this.protocols = protos.toArray(new String[protos.size()]);\n final List<String> ciphers = cipherSuites == null ? platform.defaultCipherSuites() : cipherSuites;\n this.cipherSuites = ciphers.toArray(new String[ciphers.size()]);\n this.http2 = http2 && platform.supportsHttp2();\n }\n\n SSLContext getContext(@Nullable final String host) {\n if (host == null) return context;\n final SSLContext additionalContext = additionalContexts.get(host);\n return additionalContext == null ? context : additionalContext;\n }\n\n SSLSocket createSSLSocket(final Socket socket,\n @Nullable final String hostname, final boolean http2) throws IOException {\n final SSLSocketFactory sslFactory = getContext(hostname).getSocketFactory();\n final SSLSocket sslSocket = (SSLSocket)sslFactory.createSocket(socket, null, socket.getPort(), true);\n platform.setupSSLSocket(sslSocket, http2);\n sslSocket.setUseClientMode(false);\n sslSocket.setEnabledProtocols(protocols);\n sslSocket.setEnabledCipherSuites(cipherSuites);\n sslSocket.startHandshake();\n return sslSocket;\n }\n\n private static SSLContext createSSLContext(@Nullable final byte[] certificate) {\n if (certificate == null) return null;\n final InputStream cert = new ByteArrayInputStream(certificate);\n try {\n final KeyStore keyStore = KeyStore.getInstance(\"PKCS12\");\n keyStore.load(cert, new char[0]);\n final KeyManagerFactory kmf =\n KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());\n kmf.init(keyStore, new char[0]);\n final KeyStore trustStore = KeyStore.getInstance(\"JKS\");\n trustStore.load(null, null);\n final TrustManagerFactory tmf =\n TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());\n tmf.init(trustStore);\n final SSLContext context = SSLContext.getInstance(\"TLS\");\n context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());\n return context;\n }\n catch (final GeneralSecurityException e) {\n logger.warn(\"Failed to create SSL context.\", e);\n return null;\n }\n catch (final IOException e) {\n logger.warn(\"Failed to load SSL certificate.\", e);\n return null;\n }\n finally {\n try {\n cert.close();\n }\n catch (final IOException ignore) {}\n }\n }\n\n @SuppressWarnings({ \"WeakerAccess\", \"unused\" })\n public enum Protocol {\n SSL_3(\"SSLv3\"), TLS_1(\"TLSv1\"), TLS_1_1(\"TLSv1.1\"), TLS_1_2(\"TLSv1.2\");\n\n final String name;\n\n Protocol(final String name) {\n this.name = name;\n }\n\n }\n\n /**\n * Builder for the Https class.\n */\n @SuppressWarnings(\"unused\")\n public static final class Builder {\n\n private boolean mHttp2 = false;\n private List<String> mProtocols = null;\n private List<String> mCipherSuites = null;\n private byte[] mCertificate = null;\n private final Map<String, byte[]> mAdditionalCertificates = new HashMap<>(4);\n\n public Builder() {}\n\n /**\n * Sets the primary certificate.\n * @param bytes the certificate (pkcs12).\n * @return this.\n */\n public Builder certificate(final byte[] bytes) {\n return certificate(bytes, true);\n }\n\n /**\n * Sets the primary certificate.\n * @param bytes the certificate (pkcs12).\n * @param allowHttp2 whether to enable http2 (the platform needs to support it).\n * @return this.\n */\n public Builder certificate(final byte[] bytes, final boolean allowHttp2) {\n if (mCertificate != null) throw new IllegalStateException(\"Main certificate already set.\");\n mCertificate = bytes;\n mHttp2 = allowHttp2;\n return this;\n }\n\n /**\n * Adds an additional hostname certificate.\n * @param hostname the hostname.\n * @param bytes the certificate (pkcs12).\n * @return this.\n */\n public Builder addCertificate(final String hostname, final byte[] bytes) {\n if (mAdditionalCertificates.containsKey(hostname)) {\n throw new IllegalStateException(\"Certificate for host \\\"\" + hostname + \"\\\" has already been set.\");\n }\n mAdditionalCertificates.put(hostname, bytes);\n return this;\n }\n\n /**\n * Sets the only allowed protocol.\n * @param protocol the protocol.\n * @return this.\n */\n public Builder protocol(final Protocol protocol) {\n mProtocols = Collections.singletonList(protocol.name);\n return this;\n }\n\n /**\n * Sets the list of allowed protocols.\n * @param protocols the protocols.\n * @return this.\n */\n public Builder protocols(final Protocol[] protocols) {\n final List<String> list = new ArrayList<>(protocols.length);\n for (final Protocol protocol: protocols) {\n list.add(protocol.name);\n }\n this.mProtocols = list;\n return this;\n }\n\n /**\n * Sets the list of allowed cipher suites.\n * @param cipherSuites the cipher suites.\n * @return this.\n */\n public Builder cipherSuites(final String[] cipherSuites) {\n this.mCipherSuites = Arrays.asList(cipherSuites);\n return this;\n }\n\n /**\n * Creates the Https instance.\n * @return the Https instance.\n */\n public Https build() {\n if (mCertificate == null && mAdditionalCertificates.isEmpty()) {\n throw new IllegalStateException(\"At least one certificate should be specified.\");\n }\n return new Https(mCertificate, mAdditionalCertificates, mProtocols, mCipherSuites, mHttp2);\n }\n\n }\n\n}",
"@SuppressWarnings(\"ConstantConditions\")\npublic class HttpsTest {\n\n private static byte[] getCert() {\n final Source source = Okio.source(HttpsTest.class.getResourceAsStream(\"/test.p12\"));\n final Buffer buffer = new Buffer();\n //noinspection TryFinallyCanBeTryWithResources\n try {\n buffer.writeAll(source);\n return buffer.readByteArray();\n }\n catch (final IOException e) {\n throw new RuntimeException(e);\n }\n finally {\n try { source.close(); } catch (final IOException ignore) {}\n buffer.close();\n }\n }\n\n static final byte[] cert = getCert();\n\n public static final OkHttpClient client;\n static {\n try {\n final X509TrustManager trustManager = new X509TrustManager() {\n @Override public void checkClientTrusted(final X509Certificate[] x509Certificates, final String s)\n throws CertificateException {}\n @Override\n public void checkServerTrusted(final X509Certificate[] x509Certificates, final String s)\n throws CertificateException {}\n @Override public X509Certificate[] getAcceptedIssuers() {\n return new X509Certificate[0];\n }\n };\n final SSLContext context = SSLContext.getInstance(\"TLS\");\n context.init(null, new TrustManager[] { trustManager }, new SecureRandom());\n //noinspection Convert2Lambda\n client = new OkHttpClient.Builder().\n sslSocketFactory(context.getSocketFactory(), trustManager).\n// hostnameVerifier((hostname, sslSession) -> true).\n hostnameVerifier(new HostnameVerifier() {\n @Override public boolean verify(final String hostname, final SSLSession sslSession) {return true;}\n }).\n build();\n }\n catch (final GeneralSecurityException e) {\n throw new RuntimeException(e);\n }\n }\n\n\n private static OkHttpClient client() {\n return client.newBuilder().\n readTimeout(0, TimeUnit.SECONDS).\n retryOnConnectionFailure(false).\n connectTimeout(60, TimeUnit.SECONDS).\n connectionPool(new ConnectionPool(0, 1L, TimeUnit.SECONDS)).\n protocols(Collections.singletonList(Protocol.HTTP_1_1)).\n build();\n }\n\n private static final HttpServer SERVER = new HttpServer(); //.dispatcher(new Dispatcher.Logged());\n\n// public Response handle(final String clientIp, final boolean secure, final boolean insecureOnly,\n// final boolean http2, final String method, final HttpUrl url,\n// final Headers requestHeaders, final @Nullable Buffer requestBody) {\n\n @BeforeClass\n public static void startServer() throws IOException {\n //noinspection Convert2Lambda\n SERVER.\n ports(8080, 8181).\n https(new Https.Builder().certificate(cert, false).build()).\n requestHandler(\n new RequestHandler() {\n @Override\n public Response handle(final String clientIp, final boolean secure, final boolean insecureOnly,\n final boolean http2, final String method, final HttpUrl url,\n final Headers requestHeaders, final @Nullable Buffer requestBody) {\n final String s = url + \"\\n\" + secure + \"\\n\" + insecureOnly;\n return new Response.Builder().statusLine(StatusLines.OK).body(s).build();\n }\n }\n// (clientIp, secure, insecureOnly, http2, method, url, requestHeaders, requestBody) -> {\n// final String s = url + \"\\n\" + secure + \"\\n\" + insecureOnly;\n// return new Response.Builder().statusLine(StatusLines.OK).body(s).build();\n// }\n ).\n start();\n // Use an http client once to get rid of the static initializer penalty.\n // This is done so that the first test elapsed time doesn't get artificially high.\n try {\n final OkHttpClient c = client.newBuilder().readTimeout(1, TimeUnit.SECONDS).build();\n c.newCall(new Request.Builder().url(\"http://google.com\").build()).execute();\n }\n catch (final IOException ignore) {}\n }\n\n @AfterClass\n public static void stopServer() {\n SERVER.shutdown();\n }\n\n @Test\n public void testHttps() throws IOException {\n final String result =\n client().newCall(new Request.Builder().url(\"https://localhost:8181\").build()).execute().body().string();\n final String[] split = result.split(\"\\n\");\n assertEquals(3, split.length);\n assertEquals(\"https://localhost:8181/\", split[0]);\n assertEquals(\"true\", split[1]);\n assertEquals(\"false\", split[2]);\n }\n\n @Test\n public void testHttp() throws IOException {\n final String result =\n client().newCall(new Request.Builder().url(\"http://localhost:8080\").build()).execute().body().string();\n final String[] split = result.split(\"\\n\");\n assertEquals(3, split.length);\n assertEquals(\"http://localhost:8080/\", split[0]);\n assertEquals(\"false\", split[1]);\n assertEquals(\"false\", split[1]);\n try {\n client().newCall(new Request.Builder().url(\"http://localhost:8181\").build()).execute();\n fail(\"Secure port 8181 should not accept plain HTTP connections.\");\n }\n catch (final IOException ignore) {}\n }\n\n}",
"@SuppressWarnings({ \"WeakerAccess\", \"unused\" })\npublic class MediaTypes {\n\n public static final MediaType CSS = MediaType.parse(\"text/css\");\n public static final MediaType CSV = MediaType.parse(\"text/csv\");\n public static final MediaType HTML = MediaType.parse(\"text/html\");\n public static final MediaType TEXT = MediaType.parse(\"text/plain\");\n public static final MediaType URI_LIST = MediaType.parse(\"text/uri-list\");\n public static final MediaType XML = MediaType.parse(\"text/xml\");\n\n public static final MediaType ATOM = MediaType.parse(\"application/atom+xml\");\n public static final MediaType GZIP = MediaType.parse(\"application/gzip\");\n public static final MediaType TAR = MediaType.parse(\"application/x-gtar\");\n public static final MediaType XZ = MediaType.parse(\"application/x-xz\");\n public static final MediaType SEVENZ = MediaType.parse(\"application/x-7z-compressed\");\n public static final MediaType ZIP = MediaType.parse(\"application/zip\");\n public static final MediaType RAR = MediaType.parse(\"application/vnd.rar\");\n public static final MediaType JAR = MediaType.parse(\"application/java-archive\");\n public static final MediaType APK = MediaType.parse(\"application/vnd.android.package-archive\");\n public static final MediaType DMG = MediaType.parse(\"application/x-apple-diskimage\");\n public static final MediaType ISO = MediaType.parse(\"application/x-iso9660-image\");\n public static final MediaType JAVASCRIPT = MediaType.parse(\"application/javascript\");\n public static final MediaType JSON = MediaType.parse(\"application/json\");\n public static final MediaType OCTET_STREAM = MediaType.parse(\"application/octet-stream\");\n public static final MediaType PDF = MediaType.parse(\"application/pdf\");\n public static final MediaType WOFF = MediaType.parse(\"application/font-woff\");\n public static final MediaType WOFF2 = MediaType.parse(\"font/woff2\");\n public static final MediaType XHTML = MediaType.parse(\"application/xhtml+xml\");\n public static final MediaType WEB_MANIFEST = MediaType.parse(\"application/manifest+json\");\n\n public static final MediaType OTF = MediaType.parse(\"application/opentype\");\n public static final MediaType TTF = MediaType.parse(\"application/truetype\");\n public static final MediaType EOT = MediaType.parse(\"application/vnd.ms-fontobject\");\n\n public static final MediaType WAV = MediaType.parse(\"audio/x-wav\");\n public static final MediaType MP3 = MediaType.parse(\"audio/mpeg\");\n public static final MediaType OGG = MediaType.parse(\"audio/ogg\");\n\n public static final MediaType MP4 = MediaType.parse(\"video/mp4\");\n public static final MediaType OGV = MediaType.parse(\"video/ogg\");\n public static final MediaType WEBM = MediaType.parse(\"video/webm\");\n\n public static final MediaType EMAIL = MediaType.parse(\"message/rfc822\");\n\n public static final MediaType BYTE_RANGES = MediaType.parse(\"multipart/byteranges\");\n public static final MediaType DIGEST = MediaType.parse(\"multipart/digest\");\n public static final MediaType FORM_DATA = MediaType.parse(\"multipart/form-data\");\n public static final MediaType MIXED = MediaType.parse(\"multipart/mixed\");\n public static final MediaType SIGNED = MediaType.parse(\"multipart/signed\");\n public static final MediaType ENCRYPTED = MediaType.parse(\"multipart/encrypted\");\n\n public static final MediaType JPG = MediaType.parse(\"image/jpeg\");\n public static final MediaType PNG = MediaType.parse(\"image/png\");\n public static final MediaType GIF = MediaType.parse(\"image/gif\");\n public static final MediaType BMP = MediaType.parse(\"image/bmp\");\n public static final MediaType SVG = MediaType.parse(\"image/svg+xml\");\n public static final MediaType ICO = MediaType.parse(\"image/x-icon\");\n public static final MediaType WEBP = MediaType.parse(\"image/webp\");\n\n public static final MediaType SSE = MediaType.parse(\"text/event-stream\");\n\n public static final MediaType DIRECTORY = MediaType.parse(\"text/directory\");\n\n static final Map<String, MediaType> EXTENSIONS = initMap();\n private static Map<String, MediaType> initMap() {\n final Map<String, MediaType> map = new HashMap<>(64);\n map.put(\"html\", HTML);\n map.put(\"css\", CSS);\n map.put(\"js\", JAVASCRIPT);\n map.put(\"jpg\", JPG);\n map.put(\"png\", PNG);\n map.put(\"htm\", HTML);\n map.put(\"xhtml\", XHTML);\n map.put(\"woff\", WOFF);\n map.put(\"woff2\", WOFF2);\n map.put(\"webmanifest\", WEB_MANIFEST);\n map.put(\"otf\", OTF);\n map.put(\"ttf\", TTF);\n map.put(\"eot\", EOT);\n map.put(\"gif\", GIF);\n map.put(\"bmp\", BMP);\n map.put(\"svg\", SVG);\n map.put(\"ico\", ICO);\n map.put(\"webp\", WEBP);\n\n map.put(\"csv\", CSV);\n map.put(\"txt\", TEXT);\n map.put(\"howto\", TEXT);\n map.put(\"readme\", TEXT);\n map.put(\"xml\", XML);\n map.put(\"xsl\", XML);\n map.put(\"gz\", GZIP);\n map.put(\"tar\", TAR);\n map.put(\"xz\", XZ);\n map.put(\"7z\", SEVENZ);\n map.put(\"zip\", ZIP);\n map.put(\"rar\", RAR);\n map.put(\"jar\", JAR);\n map.put(\"apk\", APK);\n map.put(\"dmg\", DMG);\n map.put(\"iso\", ISO);\n map.put(\"json\", JSON);\n map.put(\"bin\", OCTET_STREAM);\n map.put(\"pdf\", PDF);\n\n map.put(\"wav\", WAV);\n map.put(\"mp3\", MP3);\n map.put(\"ogg\", OGG);\n map.put(\"mp4\", MP4);\n map.put(\"ogv\", OGV);\n map.put(\"webm\", WEBM);\n return map;\n }\n\n public static @Nullable MediaType fromUrl(@Nullable final HttpUrl url) {\n if (url == null) return null;\n final List<String> segments = url.pathSegments();\n final int last = segments.size() - 1;\n if (last < 0) return DIRECTORY;\n final String path = segments.get(last);\n int i = path.length();\n if (i == 0) return DIRECTORY;\n int n = 0;\n while (i-- > 0 && ++n < 16) {\n switch (path.charAt(i)) {\n case '.':\n final String ext = path.substring(i+1).toLowerCase();\n return EXTENSIONS.get(ext);\n }\n }\n if (url.encodedPath().startsWith(\"/.well-known/acme-challenge/\")) {\n return MediaTypes.TEXT;\n }\n return null;\n }\n\n public static @Nullable MediaType fromFile(@Nullable final File file) {\n if (file == null) return null;\n if (file.isDirectory()) return DIRECTORY;\n final String filename = file.getName();\n if (\".\".equals(filename) || \"..\".equals(filename)) return DIRECTORY;\n final int i = filename.lastIndexOf('.');\n if (i == -1) {\n if (!file.isFile()) {\n return DIRECTORY; // files with no extension that don't exist (yet) are treated as directories.\n }\n final File parent = file.getParentFile();\n if (parent != null && \"acme-challenge\".equals(parent.getName())) {\n return MediaTypes.TEXT; // return text/plain for certificate acme-challenge files.\n }\n return null;\n }\n final String ext = filename.substring(i+1).toLowerCase();\n return EXTENSIONS.get(ext);\n }\n\n public static Collection<MediaType> defaultAllowedMediaTypes() {\n return Arrays.asList(\n HTML, XHTML, XML, JSON, ATOM, WEB_MANIFEST,\n CSS, JAVASCRIPT, TEXT, CSV,\n PNG, JPG, GIF, ICO, WEBP, SVG,\n WOFF, WOFF2, TTF, OTF, EOT,\n PDF, OCTET_STREAM, ZIP, SEVENZ, TAR, GZIP, XZ,\n MP4, OGV, WEBM, MP3, OGG\n );\n }\n\n}",
"@SuppressWarnings({ \"WeakerAccess\" })\npublic class RequestHandlerChain extends AbstractRequestHandler {\n\n public static void main(final String[] args) {\n cmd(args);\n }\n\n @SuppressWarnings(\"UnusedReturnValue\")\n static HttpServer cmd(final String[] args) {\n //final String[] args = new String[] { \"--root\", \"i:/jdavid/pierreblanche.bitbucket.org\" };\n final Map<String, String> map = new HashMap<>(args.length);\n String key = null;\n String value = null;\n for (final String arg: args) {\n if (arg.startsWith(\"--\")) {\n if (key != null) {\n map.put(key, value);\n }\n key = arg.substring(2);\n value = null;\n }\n else {\n value = value == null ? arg : value + \" \" + arg;\n }\n }\n if (key != null) {\n map.put(key, value);\n }\n if (map.containsKey(\"help\")) {\n usage();\n }\n else {\n final HttpServer server = new HttpServer();\n if (map.containsKey(\"port\")) {\n try {\n final int port = Integer.parseInt(map.get(\"port\"));\n server.port(port);\n }\n catch (final NullPointerException ignore) {\n usage();\n }\n catch (final NumberFormatException ignore) {\n usage();\n }\n }\n if (map.containsKey(\"sport\")) {\n try {\n final int port = Integer.parseInt(map.get(\"sport\"));\n server.securePort(port);\n }\n catch (final NullPointerException ignore) {\n usage();\n }\n catch (final NumberFormatException ignore) {\n usage();\n }\n }\n if (map.containsKey(\"hostname\")) {\n final String hostname = map.get(\"hostname\");\n if (hostname == null) {\n usage();\n }\n else {\n server.hostname(hostname);\n }\n }\n if (map.containsKey(\"cert\")) {\n final String path = map.get(\"cert\");\n if (path == null) {\n usage();\n }\n else {\n BufferedSource source = null;\n try {\n source = Okio.buffer(Okio.source(new File(path)));\n final byte[] cert = source.readByteArray();\n server.https(new Https.Builder().certificate(cert, true).build());\n }\n catch (final FileNotFoundException ignore) {\n System.out.println(\"Could not find certificate: \\\"\" + path + \"\\\".\");\n }\n catch (final IOException ignore) {\n System.out.println(\"Could not read certificate: \\\"\" + path + \"\\\".\");\n }\n finally {\n if (source != null) {\n try {\n source.close();\n }\n catch (final IOException ignore) {}\n }\n }\n }\n }\n final File root;\n if (map.containsKey(\"root\")) {\n final String path = map.get(\"root\");\n if (path == null) {\n root = new File(\".\");\n }\n else {\n root = new File(path);\n }\n }\n else {\n root = new File(\".\");\n }\n server.requestHandler(new RequestHandlerChain().add(new FileHandler(root)));\n server.start();\n return server;\n }\n return null;\n }\n\n private static void usage() {\n System.out.println(\"Usage:\\nAll parameters are optional.\");\n System.out.println(pad(\"--port portnumber\", 30) +\n \"the port to bind to for http (insecure) connections.\");\n System.out.println(pad(\"--sport portnumber\", 30) +\n \"the port to bind to for https (secure) connections.\");\n System.out.println(pad(\"--cert path/to/cert.p12\", 30) +\n \"the path to the p12 certificate for https.\");\n System.out.println(pad(\"--hostname hostname\", 30) +\n \"the hostname to bind to.\");\n System.out.println(pad(\"--root path/to/webroot\", 30) +\n \"the path to the web root directory.\");\n System.out.println(pad(\"--help\", 30) +\n \"prints this help.\");\n }\n\n private static String pad(final String s, @SuppressWarnings(\"SameParameterValue\") final int n) {\n final String tenSpaces = \" \";\n final StringBuilder builder = new StringBuilder(s);\n while (builder.length() < n) {\n builder.append(tenSpaces);\n }\n return builder.substring(0, n);\n }\n\n final Handler acmeHandler;\n final List<Handler> chain = new LinkedList<>();\n\n /**\n * Creates the default chain: a file handler serving the current directory.\n * @return the default request handler chain.\n */\n public static RequestHandlerChain createDefaultChain() {\n return createDefaultChain(new File(\".\"));\n }\n\n /**\n * Creates te default chain: a file handler serving the specified directory.\n * @param webRoot the directory to serve.\n * @return the default request handler chain.\n */\n public static RequestHandlerChain createDefaultChain(final File webRoot) {\n if (webRoot.isFile()) throw new IllegalArgumentException(\"Web root should be a directory.\");\n final File directory;\n try {\n directory = webRoot.getCanonicalFile();\n }\n catch (final IOException e) {\n throw new RuntimeException(e);\n }\n return new RequestHandlerChain(new AcmeChallengeHandler(directory)).\n add(new FileHandler(directory));\n }\n\n /**\n * Creates a new empty request handler chain.\n */\n public RequestHandlerChain() {\n acmeHandler = null;\n }\n\n /**\n * Creates a new empty request handler chain with the specified handler for acme challenges.\n * @param acmeChallengeHandler the acme challenge handler.\n */\n public RequestHandlerChain(final Handler acmeChallengeHandler) {\n acmeHandler = acmeChallengeHandler;\n }\n\n /**\n * Appends a Handler to the chain. Note that the order in which handlers are added matters, as they will be\n * tried in the order that they were added.\n * @param handler the handler.\n * @return this.\n */\n public RequestHandlerChain add(final Handler handler) {\n chain.add(handler.setup());\n return this;\n }\n\n @Override\n protected Response handleAcmeChallenge(final String clientIp, final String method, final HttpUrl url,\n final Headers requestHeaders, @Nullable final Buffer requestBody) {\n final Response.Builder responseBuilder;\n final String[] params;\n if (acmeHandler == null || (params = acmeHandler.matches(method, url)) == null) {\n responseBuilder = handleNotAccepted(clientIp, method, url, requestHeaders);\n }\n else {\n responseBuilder = acmeHandler.handle(\n new Request(clientIp, false, method, url, requestHeaders, requestBody),\n params\n );\n }\n decorateResponse(responseBuilder, clientIp, false, method, url, requestHeaders);\n if (Connection.CLOSE.equalsIgnoreCase(requestHeaders.get(Connection.HEADER))) {\n responseBuilder.header(Connection.HEADER, Connection.CLOSE);\n }\n return responseBuilder.build();\n }\n\n @Override\n protected final Response handle(final String clientIp, final boolean http2,\n final String method, final HttpUrl url,\n final Headers requestHeaders, @Nullable final Buffer requestBody) {\n for (final Handler handler: chain) {\n final String[] params = handler.matches(method, url);\n if (params != null) {\n final Response.Builder responseBuilder =\n handler.handle(new Request(clientIp, http2, method, url, requestHeaders, requestBody), params);\n decorateResponse(responseBuilder, clientIp, http2, method, url, requestHeaders);\n if (Connection.CLOSE.equalsIgnoreCase(requestHeaders.get(Connection.HEADER))) {\n responseBuilder.header(Connection.HEADER, Connection.CLOSE);\n }\n return responseBuilder.build();\n }\n }\n final Response.Builder responseBuilder = handleNotAccepted(clientIp, method, url, requestHeaders);\n decorateResponse(responseBuilder, clientIp, http2, method, url, requestHeaders);\n if (Connection.CLOSE.equalsIgnoreCase(requestHeaders.get(Connection.HEADER))) {\n responseBuilder.header(Connection.HEADER, Connection.CLOSE);\n }\n return responseBuilder.build();\n }\n\n /**\n * Entry point that can be used to decorate (add headers for instance) the response before sending it.\n * @param responseBuilder the response builder object.\n * @param clientIp the client ip address.\n * @param http2 whether the connection is using http2 (h2) rather than http1.1.\n * @param method the request method.\n * @param url the request url.\n * @param requestHeaders the request headers.\n */\n @SuppressWarnings({ \"unused\" })\n protected void decorateResponse(final Response.Builder responseBuilder,\n final String clientIp, final boolean http2,\n final String method, final HttpUrl url,\n final Headers requestHeaders) {\n final int code = responseBuilder.code();\n if (code >= 200 && code < 300) {\n if (http2) {\n for (final HttpUrl push: Preload.getPushUrls(responseBuilder)) {\n responseBuilder.push(push);\n }\n }\n }\n }\n\n /**\n * Handles the requests that were not accepted by any Handler in the chain.\n * The default behaviour is to return an empty 404 NOT FOUND response.\n * @param clientIp the client ip address.\n * @param method the request method.\n * @param url the request url.\n * @param requestHeaders the request headers.\n * @return the response builder object.\n */\n @SuppressWarnings({ \"unused\" })\n protected Response.Builder handleNotAccepted(final String clientIp, final String method,\n final HttpUrl url,final Headers requestHeaders) {\n return new Response.Builder().statusLine(StatusLines.NOT_FOUND).noBody();\n }\n\n}",
"@SuppressWarnings({ \"WeakerAccess\" })\npublic final class AcceptRanges {\n\n private AcceptRanges() {}\n\n /**\n * Accept-Ranges header field name. Used by the server to specify that range requests are supported.\n */\n public static final String HEADER = \"Accept-Ranges\";\n\n /**\n * Content-Range header field name. Used by the server to specify the range returned.\n */\n public static final String CONTENT_RANGE = \"Content-Range\";\n\n public static final String BYTES = \"bytes\";\n\n public static final String RANGE = \"Range\";\n\n public static final String IF_RANGE = \"If-Range\";\n\n public static final MediaType MULTIPART_TYPE = MediaType.parse(\"multipart/byteranges\");\n\n public static class ByteRangesBody extends ResponseBody {\n\n final String boundary;\n final List<Part> parts;\n final long length;\n\n ByteRangesBody(final ByteString boundary, final List<Part> parts) {\n if (parts.isEmpty()) throw new IllegalArgumentException();\n this.boundary = boundary.utf8();\n this.parts = parts;\n long n = 0;\n for (final Part part: parts) {\n n += part.size;\n }\n length = n;\n }\n\n @Override public MediaType contentType() {\n return MediaType.parse(MULTIPART_TYPE.toString() + \"; boundary=\" + boundary);\n }\n\n @Override public long contentLength() {\n return length;\n }\n\n @Override public BufferedSource source() {\n return Okio.buffer(new PartsSource(parts));\n }\n\n public static class Builder {\n\n private static final ByteString SLASH = ByteString.encodeUtf8(\"/\");\n private static final ByteString DASH = ByteString.encodeUtf8(\"-\");\n private static final ByteString DASHES = ByteString.encodeUtf8(\"--\");\n private static final ByteString CRLF = ByteString.encodeUtf8(\"\\r\\n\");\n private static final ByteString CONTENT_TYPE_PREFIX = ByteString.encodeUtf8(\"Content-Type: \");\n private static final ByteString CONTENT_RANGE_PREFIX = ByteString.encodeUtf8(\"Content-Range: bytes \");\n\n final MediaType contentType;\n final List<Part> parts = new ArrayList<>(8);\n final ByteString boundary;\n\n public Builder(final MediaType contentType) {\n this(contentType, null);\n }\n\n public Builder(final MediaType contentType, @Nullable final String boundary) {\n this.contentType = contentType;\n this.boundary = ByteString.encodeUtf8(boundary == null ? UUID.randomUUID().toString() : boundary);\n }\n\n public void addRange(final Source source, final long start, final long end, final long total) {\n final Buffer buffer = new Buffer();\n buffer.write(CRLF);\n buffer.write(DASHES);\n buffer.write(boundary);\n buffer.write(CRLF);\n buffer.write(CONTENT_TYPE_PREFIX);\n buffer.writeUtf8(contentType.toString());\n buffer.write(CRLF);\n buffer.write(CONTENT_RANGE_PREFIX);\n buffer.writeUtf8(String.valueOf(start));\n buffer.write(DASH);\n buffer.writeUtf8(String.valueOf(end));\n buffer.write(SLASH);\n buffer.writeUtf8(String.valueOf(total));\n buffer.write(CRLF);\n buffer.write(CRLF);\n parts.add(new Part(buffer, buffer.size()));\n parts.add(new Part(source, end - start));\n }\n\n public ByteRangesBody build() {\n final Buffer buffer = new Buffer();\n buffer.write(CRLF);\n buffer.write(DASHES);\n buffer.write(boundary);\n buffer.write(DASHES);\n buffer.write(CRLF);\n parts.add(new Part(buffer, buffer.size()));\n return new ByteRangesBody(boundary, parts);\n }\n\n }\n\n static class PartsSource implements Source {\n\n final Timeout timeout = new Timeout();\n final ListIterator<Part> iterator;\n private Part part;\n private long pos = 0L;\n\n PartsSource(final List<Part> parts) {\n if (parts.isEmpty()) throw new IllegalArgumentException();\n iterator = parts.listIterator();\n part = iterator.next();\n }\n\n @Override public long read(final Buffer sink, final long byteCount) throws IOException {\n if (part == null) return -1L;\n final long n = Math.min(byteCount, part.size - pos);\n sink.write(part.source, n);\n pos += n;\n if (pos == part.size) {\n part.close();\n pos = 0L;\n part = iterator.hasNext() ? iterator.next() : null;\n }\n return n;\n }\n\n @Override public Timeout timeout() {\n return timeout;\n }\n\n @Override public void close() {\n while (part != null) {\n try {\n part.close();\n }\n catch (final IOException ignore) {}\n part = iterator.hasNext() ? iterator.next() : null;\n }\n }\n\n }\n\n static class Part {\n\n final Source source;\n final long size;\n\n private Part(final Source source, final long size) {\n this.source = source;\n this.size = size;\n }\n\n public void close() throws IOException {\n source.close();\n }\n\n }\n\n }\n\n}"
] | import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.Cache;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebClientOptions;
import com.gargoylesoftware.htmlunit.WebRequest;
import com.gargoylesoftware.htmlunit.WebResponse;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import info.jdavid.ok.server.HttpServer;
import info.jdavid.ok.server.Https;
import info.jdavid.ok.server.HttpsTest;
import info.jdavid.ok.server.MediaTypes;
import info.jdavid.ok.server.RequestHandlerChain;
import info.jdavid.ok.server.header.AcceptRanges;
import okhttp3.ConnectionPool;
import okhttp3.Headers;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Protocol;
import okhttp3.Request;
import okio.BufferedSource;
import okio.ByteString;
import okio.Okio;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*; | package info.jdavid.ok.server.handler;
@SuppressWarnings("ConstantConditions")
public class FileHandlerTest {
private static final HttpServer SERVER = new HttpServer(); //.dispatcher(new Dispatcher.Logged());
@BeforeClass
public static void startServer() throws IOException {
final File root = getWebRoot();
final File certFile = new File(root, "test.p12");
assertTrue(certFile.isFile());
final byte[] cert = new byte[(int)certFile.length()];
final RandomAccessFile raf = new RandomAccessFile(certFile, "r");
try {
raf.readFully(cert);
}
finally {
raf.close();
}
// try (final RandomAccessFile raf = new RandomAccessFile(certFile, "r")) {
// raf.readFully(cert);
// }
SERVER.
ports(8080, 8181).
https(new Https.Builder().certificate(cert).build()).
maxRequestSize(512).
requestHandler(new RequestHandlerChain() {
@Override
protected boolean allowInsecure(final String method, final HttpUrl url, final Headers requestHeaders,
final boolean insecureOnly) {
return true;
}
}.add(new FileHandler(root))).
start();
}
@AfterClass
public static void stopServer() {
SERVER.shutdown();
}
private static File getWebRoot() throws IOException {
final File projectDir = new File(".").getCanonicalFile();
final File root = new File(new File(new File(projectDir, "src"), "test"), "resources");
assertTrue(root.isDirectory());
return root;
}
private static OkHttpClient client() { | return HttpsTest.client.newBuilder(). | 2 |